repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
wizardofos/Protozoo
extra/exposed/src/main/kotlin/org/jetbrains/exposed/sql/Database.kt
1
4068
package org.jetbrains.exposed.sql import org.jetbrains.exposed.sql.transactions.DEFAULT_ISOLATION_LEVEL import org.jetbrains.exposed.sql.transactions.ThreadLocalTransactionManager import org.jetbrains.exposed.sql.transactions.TransactionManager import org.jetbrains.exposed.sql.vendors.* import java.sql.Connection import java.sql.DatabaseMetaData import java.sql.DriverManager import java.util.* import java.util.concurrent.CopyOnWriteArrayList import javax.sql.DataSource class Database private constructor(val connector: () -> Connection) { internal val metadata: DatabaseMetaData get() = TransactionManager.currentOrNull()?.connection?.metaData ?: with(connector()) { try { metaData } finally { close() } } val url: String by lazy { metadata.url } internal val dialect by lazy { val name = url.removePrefix("jdbc:").substringBefore(':') dialects.firstOrNull {name == it.name} ?: error("No dialect registered for $name. URL=$url") } val vendor: String get() = dialect.name val keywords by lazy(LazyThreadSafetyMode.NONE) { ANSI_SQL_2003_KEYWORDS + VENDORS_KEYWORDS[currentDialect].orEmpty() + metadata.sqlKeywords.split(',') } val identityQuoteString by lazy(LazyThreadSafetyMode.NONE) { metadata.identifierQuoteString!!.trim() } val extraNameCharacters by lazy(LazyThreadSafetyMode.NONE) { metadata.extraNameCharacters!!} val supportsAlterTableWithAddColumn by lazy(LazyThreadSafetyMode.NONE) { metadata.supportsAlterTableWithAddColumn()} val supportsMultipleResultSets by lazy(LazyThreadSafetyMode.NONE) { metadata.supportsMultipleResultSets()} val shouldQuoteIdentifiers by lazy(LazyThreadSafetyMode.NONE) { !metadata.storesMixedCaseQuotedIdentifiers() && metadata.supportsMixedCaseQuotedIdentifiers() } val checkedIdentities = object : LinkedHashMap<String, Boolean> (100) { override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, Boolean>?): Boolean = size >= 1000 } fun needQuotes (identity: String) : Boolean { return checkedIdentities.getOrPut(identity.toLowerCase()) { keywords.any { identity.equals(it, true) } || !identity.isIdentifier() } } private fun String.isIdentifier() = !isEmpty() && first().isIdentifierStart() && all { it.isIdentifierStart() || it in '0'..'9' } private fun Char.isIdentifierStart(): Boolean = this in 'a'..'z' || this in 'A'..'Z' || this == '_' || this in extraNameCharacters companion object { private val dialects = CopyOnWriteArrayList<DatabaseDialect>() init { registerDialect(H2Dialect) registerDialect(MysqlDialect) registerDialect(PostgreSQLDialect) registerDialect(SQLiteDialect) registerDialect(OracleDialect) } fun registerDialect(dialect: DatabaseDialect) { dialects.add(0, dialect) } fun connect(datasource: DataSource, setupConnection: (Connection) -> Unit = {}, manager: (Database) -> TransactionManager = { ThreadLocalTransactionManager(it, DEFAULT_ISOLATION_LEVEL) } ): Database { return Database { datasource.connection!!.apply { setupConnection(this) } }.apply { TransactionManager.manager = manager(this) } } fun connect(url: String, driver: String, user: String = "", password: String = "", setupConnection: (Connection) -> Unit = {}, manager: (Database) -> TransactionManager = { ThreadLocalTransactionManager(it, DEFAULT_ISOLATION_LEVEL) }): Database { Class.forName(driver).newInstance() return Database { DriverManager.getConnection(url, user, password).apply { setupConnection(this) } }.apply { TransactionManager.manager = manager(this) } } } } val Database.name : String get() = url.substringAfterLast('/').substringBefore('?')
mit
1f08d1dd4c2d1eb59bedafe3ae836ccd
42.276596
157
0.674287
4.877698
false
false
false
false
deltaDNA/android-smartads-sdk
library/src/test/kotlin/com/deltadna/android/sdk/ads/AdsTest.kt
1
11415
/* * Copyright (c) 2018 deltaDNA Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.deltadna.android.sdk.ads import com.deltadna.android.sdk.DDNA import com.deltadna.android.sdk.Engagement import com.deltadna.android.sdk.ads.core.AdService import com.deltadna.android.sdk.ads.listeners.AdRegistrationListener import com.deltadna.android.sdk.ads.listeners.InterstitialAdsListener import com.deltadna.android.sdk.ads.listeners.RewardedAdsListener import com.nhaarman.mockito_kotlin.* import org.json.JSONObject import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment @RunWith(RobolectricTestRunner::class) class AdsTest { private val app = RuntimeEnvironment.application private lateinit var uut: Ads private lateinit var settings: Settings private lateinit var analytics: DDNA private lateinit var service: AdService @Before fun before() { settings = mock() analytics = mock() DDNA.initialise(DDNA.Configuration(app, "envKey", "collUrl", "engUrl")) DDNA.instance().inject(analytics) service = mock() uut = Ads(settings, app, null).inject(service) DDNASmartAds.initialise(DDNASmartAds.Configuration(app)) DDNASmartAds.instance().inject(uut) } @After fun after() { DDNASmartAds.instance().scrubAds() DDNA.instance().scrub() } @Test fun isAdAllowed() { uut.isInterstitialAdAllowed(null, true) verify(service).isInterstitialAdAllowed( isNull(), isNull(), eq(true)) with(mock<Engagement<*>>()) { whenever(getDecisionPoint()).then { "decisionPoint" } uut.isInterstitialAdAllowed(this, false) verify(service).isInterstitialAdAllowed( eq("decisionPoint"), isNull(), eq(false)) whenever(getDecisionPoint()).then { "decisionPoint" } whenever(getJson()).then { JSONObject("{\"parameters\":{\"a\":1}}") } uut.isInterstitialAdAllowed(this, true) verify(service).isInterstitialAdAllowed( eq("decisionPoint"), argThat { toString() == "{\"a\":1}" }, eq(true)) } uut.isRewardedAdAllowed(null, true) verify(service).isRewardedAdAllowed( isNull(), isNull(), eq(true)) with(mock<Engagement<*>>()) { whenever(getDecisionPoint()).then { "decisionPoint" } uut.isRewardedAdAllowed(this, false) verify(service).isRewardedAdAllowed( eq("decisionPoint"), isNull(), eq(false)) whenever(getDecisionPoint()).then { "decisionPoint" } whenever(getJson()).then { JSONObject("{\"parameters\":{\"a\":1}}") } uut.isRewardedAdAllowed(this, true) verify(service).isRewardedAdAllowed( eq("decisionPoint"), argThat { toString() == "{\"a\":1}" }, eq(true)) } } @Test fun timeUntilRewardedAdAllowed() { uut.timeUntilRewardedAdAllowed(null) verify(service).timeUntilRewardedAdAllowed(isNull(), isNull()) with(mock<Engagement<*>>()) { whenever(getDecisionPoint()).then { "decisionPoint" } whenever(getJson()).then { JSONObject("{\"parameters\":{\"a\":1}}") } uut.timeUntilRewardedAdAllowed(this) verify(service).timeUntilRewardedAdAllowed( eq("decisionPoint"), argThat { toString() == "{\"a\":1}" }) } } @Test fun isAdAvailable() { uut.hasLoadedInterstitialAd() verify(service).hasLoadedInterstitialAd() uut.hasLoadedRewardedAd() verify(service).hasLoadedRewardedAd() } @Test fun showAd() { uut.showInterstitialAd(null) verify(service).showInterstitialAd(isNull(), isNull()) with(mock<Engagement<*>>()) { whenever(getDecisionPoint()).then { "decisionPoint" } uut.showInterstitialAd(this) verify(service).showInterstitialAd( eq("decisionPoint"), isNull()) whenever(getDecisionPoint()).then { "decisionPoint" } whenever(getJson()).then { JSONObject("{\"parameters\":{\"a\":1}}") } uut.showInterstitialAd(this) verify(service).showInterstitialAd( eq("decisionPoint"), argThat { toString() == "{\"a\":1}" }) } uut.showRewardedAd(null) verify(service).showRewardedAd(isNull(), isNull()) with(mock<Engagement<*>>()) { whenever(getDecisionPoint()).then { "decisionPoint" } uut.showRewardedAd(this) verify(service).showRewardedAd( eq("decisionPoint"), isNull()) whenever(getDecisionPoint()).then { "decisionPoint" } whenever(getJson()).then { JSONObject("{\"parameters\":{\"a\":1}}") } uut.showRewardedAd(this) verify(service).showRewardedAd( eq("decisionPoint"), argThat { toString() == "{\"a\":1}" }) } } @Test fun getLastShownAndSessionCountAndDailyCount() { uut.getLastShown("decisionPoint") verify(service).getLastShown(eq("decisionPoint")) uut.getSessionCount("decisionPoint") verify(service).getSessionCount(eq("decisionPoint")) uut.getDailyCount("decisionPoint") verify(service).getDailyCount(eq("decisionPoint")) } @Test fun registrationCallbacks() { mock<AdRegistrationListener>().run { uut.setAdRegistrationListener(this) uut.onRegisteredForInterstitialAds() verify(this).onRegisteredForInterstitial() uut.onFailedToRegisterForInterstitialAds("reason") verify(this).onFailedToRegisterForInterstitial(eq("reason")) uut.onRegisteredForRewardedAds() verify(this).onRegisteredForRewarded() uut.onFailedToRegisterForRewardedAds("reason") verify(this).onFailedToRegisterForRewarded(eq("reason")) } } @Test fun interstitialCallbacks() { whenever(service.isInterstitialAdAllowed(isNull(), isNull(), eq(false))) .then { true } var listener = mock<InterstitialAdsListener>() InterstitialAd.create(null, listener).run { uut.setInterstitialAd(this) uut.onInterstitialAdOpened() verify(listener).onOpened(same(this)) uut.onInterstitialAdFailedToOpen("reason") verify(listener).onFailedToOpen(same(this), eq("reason")) // reference will be cleared now uut.onInterstitialAdClosed() verifyNoMoreInteractions(listener) } listener = mock<InterstitialAdsListener>() InterstitialAd.create(null, listener).run { uut.setInterstitialAd(this) uut.onInterstitialAdOpened() verify(listener).onOpened(same(this)) uut.onInterstitialAdClosed() verify(listener).onClosed(same(this)) // reference will be cleared now uut.onInterstitialAdFailedToOpen("reason") verifyNoMoreInteractions(listener) } listener = mock<InterstitialAdsListener>() InterstitialAd.create(null, listener).run { uut.setInterstitialAd(this) uut.setInterstitialAd(null) uut.onInterstitialAdOpened() verifyZeroInteractions(listener) } } @Test fun rewardedCallbacks() { whenever(service.isRewardedAdAllowed(isNull(), isNull(), eq(false))) .then { true } var listener = mock<RewardedAdsListener>() RewardedAd.create(null, listener).run { uut.setRewardedAd(this) uut.onRewardedAdOpened("decisionPoint") verify(listener).onOpened(same(this)) uut.onRewardedAdFailedToOpen("reason") verify(listener).onFailedToOpen(same(this), eq("reason")) // reference will be cleared now uut.onRewardedAdClosed(true) verifyNoMoreInteractions(listener) } listener = mock<RewardedAdsListener>() RewardedAd.create(null, listener).run { uut.setRewardedAd(this) uut.onRewardedAdOpened("decisionPoint") verify(listener).onOpened(same(this)) uut.onRewardedAdClosed(true) verify(listener).onClosed(same(this), eq(true)) // reference will be cleared now uut.onRewardedAdFailedToOpen("reason") verifyNoMoreInteractions(listener) } listener = mock<RewardedAdsListener>() RewardedAd.create(null, listener).run { uut.setRewardedAd(this) uut.setRewardedAd(null) uut.onRewardedAdOpened("decisionPoint") verifyZeroInteractions(listener) } val ads = arrayOf<RewardedAd>(mock(), mock()) ads.forEach { uut.registerRewardedAd(it) } uut.onRewardedAdLoaded() ads.forEach { verify(it).onLoaded() } uut.onRewardedAdOpened("decisionPoint") ads.forEach { verify(it).onOpened(eq("decisionPoint")) } } @Test fun `on new session callback calls service`() { uut.onNewSession() verify(service).onNewSession() } @Test fun `on session configured callback calls service`() { val config = JSONObject() uut.onSessionConfigured(true, config) verify(settings).isUserConsent verify(settings).isAgeRestrictedUser verify(service).configure(same(config), eq(true), any(), any()) } @Test fun onLifecycleCallbacks() { uut.onResumed() verify(service).onResume() uut.onPaused() verify(service).onPause() uut.onStopped() verify(service).onDestroy() } }
apache-2.0
c123e9a5139660413c2927310ed9d2c8
33.179641
81
0.574595
5.438304
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-item-quality-bukkit/src/main/kotlin/com/rpkit/itemquality/bukkit/command/itemquality/ItemQualitySetCommand.kt
1
2702
/* * Copyright 2021 Ren Binden * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.itemquality.bukkit.command.itemquality import com.rpkit.core.service.Services import com.rpkit.itemquality.bukkit.RPKItemQualityBukkit import com.rpkit.itemquality.bukkit.itemquality.RPKItemQualityName import com.rpkit.itemquality.bukkit.itemquality.RPKItemQualityService import org.bukkit.Material.AIR import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player class ItemQualitySetCommand(private val plugin: RPKItemQualityBukkit) : CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean { if (sender !is Player) { sender.sendMessage(plugin.messages["not-from-console"]) return true } if (!sender.hasPermission("rpkit.itemquality.command.itemquality.set")) { sender.sendMessage(plugin.messages["no-permission-itemquality-set"]) return true } if (args.isEmpty()) { sender.sendMessage(plugin.messages["itemquality-set-usage"]) return true } val itemQualityService = Services[RPKItemQualityService::class.java] if (itemQualityService == null) { sender.sendMessage(plugin.messages["no-item-quality-service"]) return true } val itemQuality = itemQualityService.getItemQuality(RPKItemQualityName(args.joinToString(" "))) if (itemQuality == null) { sender.sendMessage(plugin.messages["itemquality-set-invalid-quality"]) return true } val item = sender.inventory.itemInMainHand if (item.type == AIR) { sender.sendMessage(plugin.messages["itemquality-set-invalid-item-none"]) return true } itemQualityService.setItemQuality(item, itemQuality) sender.inventory.setItemInMainHand(item) sender.sendMessage(plugin.messages["itemquality-set-valid", mapOf( "quality" to itemQuality.name.value )]) return true } }
apache-2.0
331efaf03772c8f5fd9009c13b9590ac
39.343284
118
0.699482
4.610922
false
false
false
false
elect86/modern-jogl-examples
src/main/kotlin/glNext/tut06/hierarchy.kt
2
17391
package glNext.tut06 import com.jogamp.newt.event.KeyEvent import com.jogamp.opengl.GL.* import com.jogamp.opengl.GL3 import glNext.* import glm.* import glm.mat.Mat3x3 import glm.mat.Mat4 import glm.vec._3.Vec3 import glm.vec._4.Vec4 import main.framework.Framework import uno.buffer.* import uno.glsl.programOf import java.nio.FloatBuffer import java.util.* /** * Created by elect on 24/02/17. */ fun main(args: Array<String>) { Hierarchy_Next().setup("Tutorial 06 - Hierarchy") } class Hierarchy_Next : Framework() { object Buffer { val VERTEX = 0 val INDEX = 1 val MAX = 2 } var theProgram = 0 var modelToCameraMatrixUnif = 0 var cameraToClipMatrixUnif = 0 val cameraToClipMatrix = Mat4(0.0f) val frustumScale = calcFrustumScale(45.0f) fun calcFrustumScale(fovDeg: Float) = 1.0f / glm.tan(fovDeg.rad / 2.0f) val bufferObject = intBufferBig(Buffer.MAX) val vao = intBufferBig(1) val numberOfVertices = 24 val armature = Armature() override fun init(gl: GL3) = with(gl) { initializeProgram(gl) initializeVAO(gl) cullFace { enable() cullFace = back frontFace = cw } depth { test = true mask = true func = lEqual range = 0.0 .. 1.0 } } fun initializeProgram(gl: GL3) = with(gl) { theProgram = programOf(gl, javaClass, "tut06", "pos-color-local-transform.vert", "color-passthrough.frag") withProgram(theProgram) { modelToCameraMatrixUnif = "modelToCameraMatrix".location cameraToClipMatrixUnif = "cameraToClipMatrix".location val zNear = 1.0f val zFar = 100.0f cameraToClipMatrix[0].x = frustumScale cameraToClipMatrix[1].y = frustumScale cameraToClipMatrix[2].z = (zFar + zNear) / (zNear - zFar) cameraToClipMatrix[2].w = -1.0f cameraToClipMatrix[3].z = 2f * zFar * zNear / (zNear - zFar) use { cameraToClipMatrixUnif.mat4 = cameraToClipMatrix } } } fun initializeVAO(gl: GL3) = with(gl) { glGenBuffers(bufferObject) withArrayBuffer(bufferObject[Buffer.VERTEX]) { data(vertexData, GL_STATIC_DRAW) } withElementBuffer(bufferObject[Buffer.INDEX]) { data(indexData, GL_STATIC_DRAW) } initVertexArray(vao) { val colorDataOffset = Vec3.SIZE * numberOfVertices array(bufferObject[Buffer.VERTEX], glf.pos3_col4, 0, colorDataOffset) element(bufferObject[Buffer.INDEX]) } } override fun display(gl: GL3) = with(gl) { clear { color(0) depth() } armature.draw(gl) } override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) { cameraToClipMatrix[0].x = frustumScale * (h / w.f) cameraToClipMatrix[1].y = frustumScale usingProgram(theProgram) { cameraToClipMatrixUnif.mat4 = cameraToClipMatrix } glViewport(w, h) } override fun end(gl: GL3) = with(gl) { glDeleteProgram(theProgram) glDeleteBuffers(bufferObject) glDeleteVertexArray(vao) destroyBuffers(vao, bufferObject, vertexData, indexData) } override fun keyPressed(keyEvent: KeyEvent) { when (keyEvent.keyCode) { KeyEvent.VK_ESCAPE -> quit() KeyEvent.VK_A -> armature.adjBase(true) KeyEvent.VK_D -> armature.adjBase(false) KeyEvent.VK_W -> armature.adjUpperArm(false) KeyEvent.VK_S -> armature.adjUpperArm(true) KeyEvent.VK_R -> armature.adjLowerArm(false) KeyEvent.VK_F -> armature.adjLowerArm(true) KeyEvent.VK_T -> armature.adjWristPitch(false) KeyEvent.VK_G -> armature.adjWristPitch(true) KeyEvent.VK_Z -> armature.adjWristRoll(true) KeyEvent.VK_C -> armature.adjWristRoll(false) KeyEvent.VK_Q -> armature.adjFingerOpen(true) KeyEvent.VK_E -> armature.adjFingerOpen(false) KeyEvent.VK_SPACE -> armature.writePose() } } inner class Armature { val posBase = Vec3(3.0f, -5.0f, -40f) var angBase = -45.0f val posBaseLeft = Vec3(2.0f, 0.0f, 0.0f) val posBaseRight = Vec3(-2.0f, 0.0f, 0.0f) val scaleBaseZ = 3.0f var angUpperArm = -33.75f val sizeUpperArm = 9.0f val posLowerArm = Vec3(0.0f, 0.0f, 8.0f) var angLowerArm = 146.25f val lengthLowerArm = 5.0f val widthLowerArm = 1.5f val posWrist = Vec3(0.0f, 0.0f, 5.0f) var angWristRoll = 0.0f var angWristPitch = 67.5f val lenWrist = 2.0f val widthWrist = 2.0f val posLeftFinger = Vec3(1.0f, 0.0f, 1.0f) val posRightFinger = Vec3(-1.0f, 0.0f, 1.0f) var angFingerOpen = 180.0f val lengthFinger = 2.0f val widthFinger = 0.5f val angLowerFinger = 45.0f val STANDARD_ANGLE_INCREMENT = 11.25f val SMALL_ANGLE_INCREMENT = 9.0f fun draw(gl: GL3) = with(gl) { val modelToCameraStack = MatrixStack() glUseProgram(theProgram) glBindVertexArray(vao[0]) modelToCameraStack .translate(posBase) .rotateY(angBase) // Draw left base. run { modelToCameraStack .push() .translate(posBaseLeft) .scale(Vec3(1.0f, 1.0f, scaleBaseZ)) glUniformMatrix4f(modelToCameraMatrixUnif, modelToCameraStack.top()) glDrawElements(indexData.size, GL_UNSIGNED_SHORT) modelToCameraStack.pop() } // Draw right base. run { modelToCameraStack .push() .translate(posBaseRight) .scale(Vec3(1.0f, 1.0f, scaleBaseZ)) glUniformMatrix4f(modelToCameraMatrixUnif, modelToCameraStack.top()) glDrawElements(indexData.size, GL_UNSIGNED_SHORT) modelToCameraStack.pop() } // Draw main arm. drawUpperArm(gl, modelToCameraStack) glBindVertexArray() glUseProgram() } private fun drawUpperArm(gl: GL3, modelToCameraStack: MatrixStack) = with(gl) { modelToCameraStack .push() .rotateX(angUpperArm) run { modelToCameraStack .push() .translate(Vec3(0.0f, 0.0f, sizeUpperArm / 2.0f - 1.0f)) .scale(Vec3(1.0f, 1.0f, sizeUpperArm / 2.0f)) glUniformMatrix4f(modelToCameraMatrixUnif, modelToCameraStack.top()) glDrawElements(indexData.size, GL_UNSIGNED_SHORT) modelToCameraStack.pop() } drawLowerArm(gl, modelToCameraStack) modelToCameraStack.pop() } private fun drawLowerArm(gl: GL3, modelToCameraStack: MatrixStack) = with(gl) { modelToCameraStack .push() .translate(posLowerArm) .rotateX(angLowerArm) modelToCameraStack .push() .translate(Vec3(0.0f, 0.0f, lengthLowerArm / 2.0f)) .scale(Vec3(widthLowerArm / 2.0f, widthLowerArm / 2.0f, lengthLowerArm / 2.0f)) glUniformMatrix4f(modelToCameraMatrixUnif, modelToCameraStack.top()) glDrawElements(indexData.size, GL_UNSIGNED_SHORT) modelToCameraStack.pop() drawWrist(gl, modelToCameraStack) modelToCameraStack.pop() } private fun drawWrist(gl: GL3, modelToCameraStack: MatrixStack) = with(gl) { modelToCameraStack .push() .translate(posWrist) .rotateZ(angWristRoll) .rotateX(angWristPitch) modelToCameraStack .push() .scale(Vec3(widthWrist / 2.0f, widthWrist / 2.0f, lenWrist / 2.0f)) glUniformMatrix4f(modelToCameraMatrixUnif, modelToCameraStack.top()) glDrawElements(indexData.size, GL_UNSIGNED_SHORT) modelToCameraStack.pop() drawFingers(gl, modelToCameraStack) modelToCameraStack.pop() } private fun drawFingers(gl: GL3, modelToCameraStack: MatrixStack) = with(gl) { // Draw left finger modelToCameraStack .push() .translate(posLeftFinger) .rotateY(angFingerOpen) modelToCameraStack .push() .translate(Vec3(0.0f, 0.0f, lengthFinger / 2.0f)) .scale(Vec3(widthFinger / 2.0f, widthFinger / 2.0f, lengthFinger / 2.0f)) glUniformMatrix4f(modelToCameraMatrixUnif, modelToCameraStack.top()) glDrawElements(indexData.size, GL_UNSIGNED_SHORT) modelToCameraStack.pop() run { // Draw left lower finger modelToCameraStack .push() .translate(Vec3(0.0f, 0.0f, lengthFinger)) .rotateY(-angLowerFinger) modelToCameraStack .push() .translate(Vec3(0.0f, 0.0f, lengthFinger / 2.0f)) .scale(Vec3(widthFinger / 2.0f, widthFinger / 2.0f, lengthFinger / 2.0f)) glUniformMatrix4f(modelToCameraMatrixUnif, modelToCameraStack.top()) glDrawElements(indexData.size, GL_UNSIGNED_SHORT) modelToCameraStack.pop() modelToCameraStack.pop() } modelToCameraStack.pop() // Draw right finger modelToCameraStack .push() .translate(posRightFinger) .rotateY(-angFingerOpen) modelToCameraStack .push() .translate(Vec3(0.0f, 0.0f, lengthFinger / 2.0f)) .scale(Vec3(widthFinger / 2.0f, widthFinger / 2.0f, lengthFinger / 2.0f)) glUniformMatrix4f(modelToCameraMatrixUnif, modelToCameraStack.top()) glDrawElements(indexData.size, GL_UNSIGNED_SHORT) modelToCameraStack.pop() run { // Draw left lower finger modelToCameraStack .push() .translate(Vec3(0.0f, 0.0f, lengthFinger)) .rotateY(angLowerFinger) modelToCameraStack .push() .translate(Vec3(0.0f, 0.0f, lengthFinger / 2.0f)) .scale(Vec3(widthFinger / 2.0f, widthFinger / 2.0f, lengthFinger / 2.0f)) glUniformMatrix4f(modelToCameraMatrixUnif, modelToCameraStack.top()) glDrawElements(indexData.size, GL_UNSIGNED_SHORT) modelToCameraStack.pop() modelToCameraStack.pop() } modelToCameraStack.pop() } fun adjBase(increment: Boolean) { angBase += if (increment) STANDARD_ANGLE_INCREMENT else -STANDARD_ANGLE_INCREMENT angBase %= 360.0f } fun adjUpperArm(increment: Boolean) { angUpperArm += if (increment) STANDARD_ANGLE_INCREMENT else -STANDARD_ANGLE_INCREMENT angUpperArm = glm.clamp(angUpperArm, -90.0f, 0.0f) } fun adjLowerArm(increment: Boolean) { angLowerArm += if (increment) STANDARD_ANGLE_INCREMENT else -STANDARD_ANGLE_INCREMENT angLowerArm = glm.clamp(angLowerArm, 0.0f, 146.25f) } fun adjWristPitch(increment: Boolean) { angWristPitch += if (increment) STANDARD_ANGLE_INCREMENT else -STANDARD_ANGLE_INCREMENT angWristPitch = glm.clamp(angWristPitch, 0.0f, 90.0f) } fun adjWristRoll(increment: Boolean) { angWristRoll += if (increment) STANDARD_ANGLE_INCREMENT else -STANDARD_ANGLE_INCREMENT angWristRoll %= 360.0f } fun adjFingerOpen(increment: Boolean) { angFingerOpen += if (increment) SMALL_ANGLE_INCREMENT else -SMALL_ANGLE_INCREMENT angFingerOpen = glm.clamp(angFingerOpen, 9.0f, 180.0f) } fun writePose() { println("angBase:\t$angBase") println("angUpperArm:\t$angUpperArm") println("angLowerArm:\t$angLowerArm") println("angWristPitch:\t$angWristPitch") println("angWristRoll:\t$angWristRoll") println("angFingerOpen:\t$angFingerOpen") } } private inner class MatrixStack { val matrices = Stack<Mat4>() var currMat = Mat4(1f) internal fun top() = currMat internal fun rotateX(angDeg: Float): MatrixStack { currMat times_ Mat4(this@Hierarchy_Next.rotateX(angDeg)) return this } internal fun rotateY(angDeg: Float): MatrixStack { currMat times_ Mat4(this@Hierarchy_Next.rotateY(angDeg)) return this } internal fun rotateZ(angDeg: Float): MatrixStack { currMat times_ Mat4(this@Hierarchy_Next.rotateZ(angDeg)) return this } internal fun scale(scaleVec: Vec3): MatrixStack { val scaleMat = Mat4(scaleVec) currMat times_ scaleMat return this } internal fun translate(offsetVec: Vec3): MatrixStack { val translateMat = Mat4(1f) translateMat[3] = Vec4(offsetVec) currMat times_ translateMat return this } internal fun push(): MatrixStack { matrices.push(Mat4(currMat)) return this } internal fun pop(): MatrixStack { currMat = matrices.pop() return this } infix fun to(buffer: FloatBuffer) = currMat.to(buffer) } fun rotateX(angDeg: Float): Mat3x3 { val cos = angDeg.rad.cos val sin = angDeg.rad.sin val theMat = Mat3x3(1f) theMat[1].y = cos; theMat[2].y = -sin theMat[1].z = sin; theMat[2].z = cos return theMat } fun rotateY(angDeg: Float): Mat3x3 { val cos = angDeg.rad.cos val sin = angDeg.rad.sin val theMat = Mat3x3(1f) theMat[0].x = cos; theMat[2].x = sin theMat[0].z = -sin; theMat[2].z = cos return theMat } fun rotateZ(angDeg: Float): Mat3x3 { val cos = angDeg.rad.cos val sin = angDeg.rad.sin val theMat = Mat3x3(1f) theMat[0].x = cos; theMat[1].x = -sin theMat[0].y = sin; theMat[1].y = cos return theMat } val GREEN_COLOR = floatArrayOf(0.0f, 1.0f, 0.0f, 1.0f) val BLUE_COLOR = floatArrayOf(0.0f, 0.0f, 1.0f, 1.0f) val RED_COLOR = floatArrayOf(1.0f, 0.0f, 0.0f, 1.0f) val YELLOW_COLOR = floatArrayOf(1.0f, 1.0f, 0.0f, 1.0f) val CYAN_COLOR = floatArrayOf(0.0f, 1.0f, 1.0f, 1.0f) val MAGENTA_COLOR = floatArrayOf(1.0f, 0.0f, 1.0f, 1.0f) val vertexData = floatBufferOf( //Front +1.0f, +1.0f, +1.0f, +1.0f, -1.0f, +1.0f, -1.0f, -1.0f, +1.0f, -1.0f, +1.0f, +1.0f, //Top +1.0f, +1.0f, +1.0f, -1.0f, +1.0f, +1.0f, -1.0f, +1.0f, -1.0f, +1.0f, +1.0f, -1.0f, //Left +1.0f, +1.0f, +1.0f, +1.0f, +1.0f, -1.0f, +1.0f, -1.0f, -1.0f, +1.0f, -1.0f, +1.0f, //Back +1.0f, +1.0f, -1.0f, -1.0f, +1.0f, -1.0f, -1.0f, -1.0f, -1.0f, +1.0f, -1.0f, -1.0f, //Bottom +1.0f, -1.0f, +1.0f, +1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, +1.0f, //Right -1.0f, +1.0f, +1.0f, -1.0f, -1.0f, +1.0f, -1.0f, -1.0f, -1.0f, -1.0f, +1.0f, -1.0f, *GREEN_COLOR, *GREEN_COLOR, *GREEN_COLOR, *GREEN_COLOR, *BLUE_COLOR, *BLUE_COLOR, *BLUE_COLOR, *BLUE_COLOR, *RED_COLOR, *RED_COLOR, *RED_COLOR, *RED_COLOR, *YELLOW_COLOR, *YELLOW_COLOR, *YELLOW_COLOR, *YELLOW_COLOR, *CYAN_COLOR, *CYAN_COLOR, *CYAN_COLOR, *CYAN_COLOR, *MAGENTA_COLOR, *MAGENTA_COLOR, *MAGENTA_COLOR, *MAGENTA_COLOR) val indexData = shortBufferOf( 0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4, 8, 9, 10, 10, 11, 8, 12, 13, 14, 14, 15, 12, 16, 17, 18, 18, 19, 16, 20, 21, 22, 22, 23, 20) }
mit
98be12a0e8e46eddf3a2c300dc7ff8de
28.883162
114
0.531137
4.046301
false
false
false
false
androidx/constraintlayout
projects/ComposeConstraintLayout/app/src/main/java/com/example/constraintlayout/MotionStatesExample.kt
2
13524
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.constraintlayout import android.annotation.SuppressLint import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.layoutId import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.constraintlayout.compose.* import java.util.* @Composable fun ComposeMessage( modifier: Modifier = Modifier ) { var nextState by remember { mutableStateOf<String?>("full") } fun Modifier.clickFromTo(start: String, end: String): Modifier = if (nextState == start) { clickable { nextState = end } } else { this } MotionLayout( modifier = modifier, animationSpec = tween(800), debug = EnumSet.of(MotionLayoutDebugFlags.NONE), motionScene = MotionScene( """ { ConstraintSets: { fab: { iconBox: { width: 50, height: 50, end: ['parent', 'end', 8], bottom: ['parent', 'bottom', 8], alpha: 1.0, }, mailBox: { width: 50, height: 50, end: ['parent', 'end', 8], bottom: ['parent', 'bottom', 8], alpha: 0.0, }, miniBox: { width: 50, height: 50, end: ['parent', 'end', 8], bottom: ['parent', 'bottom', 8], custom: { mValue: 0.0 }, } }, full : { iconBox: { width: 'spread', height: 'spread', centerHorizontally: 'parent', centerVertically: 'parent', alpha: 0.0, }, mailBox: { width: 'spread', height: 'spread', end: ['parent', 'end', 0], start: ['parent', 'start', 0], top: ['parent', 'top', 0], bottom: ['parent', 'bottom', 0], alpha: 1.0, }, miniBox: { width: 'spread', height: 50, top: ['parent', 'top', 40], end: ['parent', 'end', 8], start: ['parent', 'start', 8], custom: { mValue: 0.0 }, } }, minimized: { iconBox: { width: 180, height: 50, end: ['parent', 'end', 8], bottom: ['parent', 'bottom', 8], alpha: 0.0, }, mailBox: { width: 180, height: 50, end: ['parent', 'end', 8], bottom: ['parent', 'bottom', 8], alpha: 0.0, }, miniBox: { width: 180, height: 50, end: ['parent', 'end', 8], bottom: ['parent', 'bottom', 8], custom: { mValue: 1.0 }, } } }, Transitions: { default: { from: 'full', to: 'fab' } } } """ ), constraintSetName = nextState, ) { ComposeMailWidget( modifier = Modifier .layoutId("mailBox"), onMinimize = { nextState = "minimized" }, onClose = { nextState = "fab" } ) Surface( color = MaterialTheme.colors.primaryVariant, contentColor = MaterialTheme.colors.onPrimary, modifier = modifier .layoutId("miniBox") .alpha(motionProperties(id = "miniBox").value.float("mValue")), elevation = 4.dp, shape = RoundedCornerShape(topStart = 8.dp, topEnd = 8.dp) ) { Row( modifier = Modifier.padding(8.dp), horizontalArrangement = Arrangement.End ) { Text( modifier = Modifier.weight(1.0f, true), text = "Subject" ) Icon( imageVector = Icons.Default.KeyboardArrowUp, contentDescription = "Minimize Window", modifier = Modifier.clickFromTo("minimized", "full") ) Spacer(Modifier.width(12.dp)) Icon( imageVector = Icons.Default.Clear, contentDescription = "Close Window", modifier = Modifier.clickFromTo("minimized", "fab") ) } } withContentColor(MaterialTheme.colors.onPrimary) { Row( modifier = Modifier .layoutId("iconBox") .sizeIn(minWidth = 32.dp, minHeight = 32.dp) .background( color = MaterialTheme.colors.primary, shape = RoundedCornerShape(12) ) .padding(8.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Icon( imageVector = Icons.Default.Edit, contentDescription = "Compose Mail", modifier = Modifier .clickFromTo("fab", "full") .fillMaxSize() ) } } } } @Suppress("NOTHING_TO_INLINE") @SuppressLint("ComposableNaming") @Composable inline fun withContentColor(color: Color, noinline content: @Composable () -> Unit) { CompositionLocalProvider(values = arrayOf(LocalContentColor provides color), content = content) } @Composable fun ComposeMailWidget( modifier: Modifier = Modifier, onMinimize: () -> Unit, onClose: () -> Unit ) { Surface( modifier = modifier.padding(top = 16.dp, start = 4.dp, end = 4.dp, bottom = 0.dp), elevation = 6.dp, shape = RoundedCornerShape(topStart = 12.dp, topEnd = 12.dp) ) { ConstraintLayout( modifier = Modifier.padding(top = 4.dp, start = 8.dp, end = 8.dp, bottom = 0.dp), constraintSet = ConstraintSet( """ { topToolbar: { width: 'spread', top: ['parent', 'top', 0], centerHorizontally: 'parent' }, recipient: { top: ['topToolbar', 'bottom', 2], width: 'spread', centerHorizontally: 'parent', }, subject: { top: ['recipient', 'bottom', 4], width: 'spread', centerHorizontally: 'parent', }, message: { height: "spread", width: 'spread', centerHorizontally: 'parent', top: ['subject', 'bottom', 4], bottom: ['bottomToolbar', 'top', 4], }, bottomToolbar: { width: 'spread', centerHorizontally: 'parent', bottom: ['parent', 'bottom', 16], }, } """.trimIndent() ) ) { println("Composing CL") Row( modifier = Modifier.layoutId("topToolbar"), horizontalArrangement = Arrangement.End ) { Icon( imageVector = Icons.Default.KeyboardArrowDown, contentDescription = "Minimize Window", modifier = Modifier.clickable(onClick = onMinimize) ) Spacer(Modifier.width(12.dp)) Icon( imageVector = Icons.Default.Clear, contentDescription = "Close Window", modifier = Modifier.clickable(onClick = onClose) ) } TextField( modifier = Modifier.layoutId("recipient"), value = "", onValueChange = {}, placeholder = { Text("Recipients") } ) TextField( modifier = Modifier.layoutId("subject"), value = "", onValueChange = {}, placeholder = { Text("Subject") } ) TextField( modifier = Modifier .layoutId("message") .fillMaxHeight(), value = "", onValueChange = {}, placeholder = { Text("Message") } ) Row( horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.layoutId("bottomToolbar") ) { Button(onClick = { /*TODO*/ }) { Row { Text(text = "Send") Spacer(modifier = Modifier.width(8.dp)) Icon( imageVector = Icons.Default.Send, contentDescription = "Send Mail", ) } } Button(onClick = { /*TODO*/ }) { Icon( imageVector = Icons.Default.Delete, contentDescription = "Delete Draft", ) } } } } } @Preview(group = "states1") @Composable fun ComposeMessagePreview() { MyTheme { Surface( modifier = Modifier.size(400.dp, 700.dp) ) { ComposeMessage(modifier = Modifier.fillMaxSize()) } } } private val LightColorPalette = lightColors( primary = Color(0xFF6200EE), primaryVariant = Color(0xFF3700B3), secondary = Color(0xFF2C61FF), onSecondary = Color(0xFF050505), /* Other default colors to override background = Color.White, surface = Color.White, onPrimary = Color.White, onSecondary = Color.Black, onBackground = Color.Black, onSurface = Color.Black, */ ) @Composable private fun MyTheme( content: @Composable() () -> Unit ) { MaterialTheme( colors = LightColorPalette, typography = Typography, shapes = Shapes, content = content ) } private val Shapes = Shapes( small = RoundedCornerShape(4.dp), medium = RoundedCornerShape(4.dp), large = RoundedCornerShape(0.dp) ) // Set of Material typography styles to start with private val Typography = Typography( body1 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp ) /* Other default text styles to override button = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.W500, fontSize = 14.sp ), caption = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 12.sp ) */ )
apache-2.0
f4f26d818be2dd8ba6f00a8fe642a2a0
32.06846
99
0.450976
5.437877
false
false
false
false
burntcookie90/Sleep-Cycle-Alarm
wear/src/main/java/butterknife/ButterKnife.kt
1
5343
package butterknife import android.app.Activity import android.app.Dialog import android.app.Fragment import android.support.v4.app.Fragment as SupportFragment import android.support.v7.widget.RecyclerView.ViewHolder import android.view.View import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty public fun <V : View> View.bindView(id: Int) : ReadOnlyProperty<View, V> = required(id, viewFinder) public fun <V : View> Activity.bindView(id: Int) : ReadOnlyProperty<Activity, V> = required(id, viewFinder) public fun <V : View> Dialog.bindView(id: Int) : ReadOnlyProperty<Dialog, V> = required(id, viewFinder) public fun <V : View> Fragment.bindView(id: Int) : ReadOnlyProperty<Fragment, V> = required(id, viewFinder) public fun <V : View> SupportFragment.bindView(id: Int) : ReadOnlyProperty<SupportFragment, V> = required(id, viewFinder) public fun <V : View> ViewHolder.bindView(id: Int) : ReadOnlyProperty<ViewHolder, V> = required(id, viewFinder) public fun <V : View> View.bindOptionalView(id: Int) : ReadOnlyProperty<View, V?> = optional(id, viewFinder) public fun <V : View> Activity.bindOptionalView(id: Int) : ReadOnlyProperty<Activity, V?> = optional(id, viewFinder) public fun <V : View> Dialog.bindOptionalView(id: Int) : ReadOnlyProperty<Dialog, V?> = optional(id, viewFinder) public fun <V : View> Fragment.bindOptionalView(id: Int) : ReadOnlyProperty<Fragment, V?> = optional(id, viewFinder) public fun <V : View> SupportFragment.bindOptionalView(id: Int) : ReadOnlyProperty<SupportFragment, V?> = optional(id, viewFinder) public fun <V : View> ViewHolder.bindOptionalView(id: Int) : ReadOnlyProperty<ViewHolder, V?> = optional(id, viewFinder) public fun <V : View> View.bindViews(vararg ids: Int) : ReadOnlyProperty<View, List<V>> = required(ids, viewFinder) public fun <V : View> Activity.bindViews(vararg ids: Int) : ReadOnlyProperty<Activity, List<V>> = required(ids, viewFinder) public fun <V : View> Dialog.bindViews(vararg ids: Int) : ReadOnlyProperty<Dialog, List<V>> = required(ids, viewFinder) public fun <V : View> Fragment.bindViews(vararg ids: Int) : ReadOnlyProperty<Fragment, List<V>> = required(ids, viewFinder) public fun <V : View> SupportFragment.bindViews(vararg ids: Int) : ReadOnlyProperty<SupportFragment, List<V>> = required(ids, viewFinder) public fun <V : View> ViewHolder.bindViews(vararg ids: Int) : ReadOnlyProperty<ViewHolder, List<V>> = required(ids, viewFinder) public fun <V : View> View.bindOptionalViews(vararg ids: Int) : ReadOnlyProperty<View, List<V>> = optional(ids, viewFinder) public fun <V : View> Activity.bindOptionalViews(vararg ids: Int) : ReadOnlyProperty<Activity, List<V>> = optional(ids, viewFinder) public fun <V : View> Dialog.bindOptionalViews(vararg ids: Int) : ReadOnlyProperty<Dialog, List<V>> = optional(ids, viewFinder) public fun <V : View> Fragment.bindOptionalViews(vararg ids: Int) : ReadOnlyProperty<Fragment, List<V>> = optional(ids, viewFinder) public fun <V : View> SupportFragment.bindOptionalViews(vararg ids: Int) : ReadOnlyProperty<SupportFragment, List<V>> = optional(ids, viewFinder) public fun <V : View> ViewHolder.bindOptionalViews(vararg ids: Int) : ReadOnlyProperty<ViewHolder, List<V>> = optional(ids, viewFinder) private val View.viewFinder: View.(Int) -> View? get() = View::findViewById private val Activity.viewFinder: Activity.(Int) -> View? get() = Activity::findViewById private val Dialog.viewFinder: Dialog.(Int) -> View? get() = Dialog::findViewById private val Fragment.viewFinder: Fragment.(Int) -> View? get() = { view.findViewById(it) } private val SupportFragment.viewFinder: SupportFragment.(Int) -> View? get() = { view.findViewById(it) } private val ViewHolder.viewFinder: ViewHolder.(Int) -> View? get() = { itemView.findViewById(it) } private fun viewNotFound(id:Int, desc: KProperty<*>) : Nothing = throw IllegalStateException("View ID $id for '${desc.name}' not found.") @Suppress("UNCHECKED_CAST") private fun <T, V : View> required(id: Int, finder : T.(Int) -> View?) = Lazy { t : T, desc -> t.finder(id) as V? ?: viewNotFound(id, desc) } @Suppress("UNCHECKED_CAST") private fun <T, V : View> optional(id: Int, finder : T.(Int) -> View?) = Lazy { t : T, desc -> t.finder(id) as V? } @Suppress("UNCHECKED_CAST") private fun <T, V : View> required(ids: IntArray, finder : T.(Int) -> View?) = Lazy { t : T, desc -> ids.map { t.finder(it) as V? ?: viewNotFound(it, desc) } } @Suppress("UNCHECKED_CAST") private fun <T, V : View> optional(ids: IntArray, finder : T.(Int) -> View?) = Lazy { t : T, desc -> ids.map { t.finder(it) as V? }.filterNotNull() } // Like Kotlin's lazy delegate but the initializer gets the target and metadata passed to it private class Lazy<T, V>(private val initializer : (T, KProperty<*>) -> V) : ReadOnlyProperty<T, V> { private object EMPTY private var value: Any? = EMPTY override fun getValue(thisRef : T, property : KProperty<*>) : V { if (value == EMPTY) { value = initializer(thisRef, property) } @Suppress("UNCHECKED_CAST") return value as V } }
apache-2.0
e414e359173dbfeaf2709b15a3517f3e
48.018349
101
0.690249
3.843885
false
false
false
false
NoodleMage/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/util/ChapterRecognition.kt
4
4519
package eu.kanade.tachiyomi.util import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga /** * -R> = regex conversion. */ object ChapterRecognition { /** * All cases with Ch.xx * Mokushiroku Alice Vol.1 Ch. 4: Misrepresentation -R> 4 */ private val basic = Regex("""(?<=ch\.) *([0-9]+)(\.[0-9]+)?(\.?[a-z]+)?""") /** * Regex used when only one number occurrence * Example: Bleach 567: Down With Snowwhite -R> 567 */ private val occurrence = Regex("""([0-9]+)(\.[0-9]+)?(\.?[a-z]+)?""") /** * Regex used when manga title removed * Example: Solanin 028 Vol. 2 -> 028 Vol.2 -> 028Vol.2 -R> 028 */ private val withoutManga = Regex("""^([0-9]+)(\.[0-9]+)?(\.?[a-z]+)?""") /** * Regex used to remove unwanted tags * Example Prison School 12 v.1 vol004 version1243 volume64 -R> Prison School 12 */ private val unwanted = Regex("""(?<![a-z])(v|ver|vol|version|volume|season|s).?[0-9]+""") /** * Regex used to remove unwanted whitespace * Example One Piece 12 special -R> One Piece 12special */ private val unwantedWhiteSpace = Regex("""(\s)(extra|special|omake)""") fun parseChapterNumber(chapter: SChapter, manga: SManga) { // If chapter number is known return. if (chapter.chapter_number == -2f || chapter.chapter_number > -1f) return // Get chapter title with lower case var name = chapter.name.toLowerCase() // Remove comma's from chapter. name = name.replace(',', '.') // Remove unwanted white spaces. unwantedWhiteSpace.findAll(name).let { it.forEach { occurrence -> name = name.replace(occurrence.value, occurrence.value.trim()) } } // Remove unwanted tags. unwanted.findAll(name).let { it.forEach { occurrence -> name = name.replace(occurrence.value, "") } } // Check base case ch.xx if (updateChapter(basic.find(name), chapter)) return // Check one number occurrence. val occurrences: MutableList<MatchResult> = arrayListOf() occurrence.findAll(name).let { it.forEach { occurrence -> occurrences.add(occurrence) } } if (occurrences.size == 1) { if (updateChapter(occurrences[0], chapter)) return } // Remove manga title from chapter title. val nameWithoutManga = name.replace(manga.title.toLowerCase(), "").trim() // Check if first value is number after title remove. if (updateChapter(withoutManga.find(nameWithoutManga), chapter)) return // Take the first number encountered. if (updateChapter(occurrence.find(nameWithoutManga), chapter)) return } /** * Check if volume is found and update chapter * @param match result of regex * @param chapter chapter object * @return true if volume is found */ fun updateChapter(match: MatchResult?, chapter: SChapter): Boolean { match?.let { val initial = it.groups[1]?.value?.toFloat()!! val subChapterDecimal = it.groups[2]?.value val subChapterAlpha = it.groups[3]?.value val addition = checkForDecimal(subChapterDecimal, subChapterAlpha) chapter.chapter_number = initial.plus(addition) return true } return false } /** * Check for decimal in received strings * @param decimal decimal value of regex * @param alpha alpha value of regex * @return decimal/alpha float value */ fun checkForDecimal(decimal: String?, alpha: String?): Float { if (!decimal.isNullOrEmpty()) return decimal?.toFloat()!! if (!alpha.isNullOrEmpty()) { if (alpha!!.contains("extra")) return .99f if (alpha.contains("omake")) return .98f if (alpha.contains("special")) return .97f if (alpha[0] == '.') { // Take value after (.) return parseAlphaPostFix(alpha[1]) } else { return parseAlphaPostFix(alpha[0]) } } return .0f } /** * x.a -> x.1, x.b -> x.2, etc */ private fun parseAlphaPostFix(alpha: Char): Float { return ("0." + Integer.toString(alpha.toInt() - 96)).toFloat() } }
apache-2.0
51fb2825f1f3db298f42e738db19f5a3
30.381944
103
0.568267
4.279356
false
false
false
false
Shynixn/PetBlocks
petblocks-core/src/main/kotlin/com/github/shynixn/petblocks/core/logic/persistence/entity/AIMovementEntity.kt
1
2466
package com.github.shynixn.petblocks.core.logic.persistence.entity import com.github.shynixn.petblocks.api.business.annotation.YamlSerialize import com.github.shynixn.petblocks.api.persistence.entity.AIMovement import com.github.shynixn.petblocks.api.persistence.entity.Particle import com.github.shynixn.petblocks.api.persistence.entity.Sound /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * 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. */ abstract class AIMovementEntity : AIBaseEntity(), AIMovement { /** * Movement sound. */ @YamlSerialize(value = "sound", orderNumber = 5, implementation = SoundEntity::class) override val movementSound: Sound = SoundEntity("CHICKEN_WALK") /** * Movement particle. */ @YamlSerialize(value = "particle", orderNumber = 4, implementation = ParticleEntity::class) override val movementParticle: Particle = ParticleEntity() /** * Climbing height. */ @YamlSerialize(value = "climbing-height", orderNumber = 1) override var climbingHeight: Double = 1.0 /** * Movement speed modifier. */ @YamlSerialize(value = "speed", orderNumber = 2) override var movementSpeed: Double = 1.0 /** * Movement offset from ground. */ @YamlSerialize(value = "offset-y", orderNumber = 3) override var movementYOffSet: Double = 1.0 }
apache-2.0
873bba28d13f1ae2127500ea66ce1219
38.790323
95
0.723033
4.266436
false
false
false
false
yschimke/oksocial
src/main/kotlin/com/baulsupp/okurl/services/gdax/GdaxAuthInterceptor.kt
1
3997
package com.baulsupp.okurl.services.gdax import com.baulsupp.oksocial.output.OutputHandler import com.baulsupp.okurl.authenticator.AuthInterceptor import com.baulsupp.okurl.authenticator.ValidatedCredentials import com.baulsupp.okurl.completion.ApiCompleter import com.baulsupp.okurl.completion.BaseUrlCompleter import com.baulsupp.okurl.completion.CompletionVariableCache import com.baulsupp.okurl.completion.UrlList import com.baulsupp.okurl.credentials.CredentialsStore import com.baulsupp.okurl.credentials.Token import com.baulsupp.okurl.credentials.TokenValue import com.baulsupp.okurl.kotlin.queryList import com.baulsupp.okurl.secrets.Secrets import com.baulsupp.okurl.services.AbstractServiceDefinition import com.baulsupp.okurl.services.gdax.model.Account import com.baulsupp.okurl.services.gdax.model.Product import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.Response import okio.Buffer import okio.ByteString.Companion.decodeBase64 import okio.ByteString.Companion.encodeUtf8 import java.nio.charset.StandardCharsets.UTF_8 class GdaxAuthInterceptor : AuthInterceptor<GdaxCredentials>() { override val serviceDefinition = object : AbstractServiceDefinition<GdaxCredentials>( "api.gdax.com", "GDAX API", "gdax", "https://docs.gdax.com/", "https://www.gdax.com/settings/api" ) { override fun parseCredentialsString(s: String): GdaxCredentials { val parts = s.split(":".toRegex(), 3) return GdaxCredentials(parts[0], parts[1], parts[2]) } override fun formatCredentialsString(credentials: GdaxCredentials) = "${credentials.apiKey}:${credentials.apiSecret}:${credentials.passphrase}" } override suspend fun intercept(chain: Interceptor.Chain, credentials: GdaxCredentials): Response { var request = chain.request() val timestamp = (System.currentTimeMillis() / 1000).toString() val decodedKey = credentials.apiSecret.decodeBase64()!! val sink = Buffer() request.body?.writeTo(sink) val prehash = "" + timestamp + request.method + request.url.encodedPath + sink.snapshot().string(UTF_8) val signature = prehash.encodeUtf8().hmacSha256(decodedKey) request = request.newBuilder() .addHeader("CB-ACCESS-KEY", credentials.apiKey) .addHeader("CB-ACCESS-SIGN", signature.base64()) .addHeader("CB-ACCESS-TIMESTAMP", timestamp) .addHeader("CB-ACCESS-PASSPHRASE", credentials.passphrase) .build() return chain.proceed(request) } override suspend fun authorize( client: OkHttpClient, outputHandler: OutputHandler<Response>, authArguments: List<String> ): GdaxCredentials { val apiKey = Secrets.prompt("GDAX API Key", "gdax.apiKey", "", false) val apiSecret = Secrets.prompt("GDAX API Secret", "gdax.apiSecret", "", true) val apiPassphrase = Secrets.prompt("GDAX Passphrase", "gdax.passphrase", "", true) return GdaxCredentials(apiKey, apiSecret, apiPassphrase) } override suspend fun validate( client: OkHttpClient, credentials: GdaxCredentials ): ValidatedCredentials { val accounts = client.queryList<Account>( "https://api.gdax.com/accounts", TokenValue(credentials) ) return ValidatedCredentials(accounts.map { it.id }.first()) } override suspend fun apiCompleter( prefix: String, client: OkHttpClient, credentialsStore: CredentialsStore, completionVariableCache: CompletionVariableCache, tokenSet: Token ): ApiCompleter { val urlList = UrlList.fromResource(name()) val completer = BaseUrlCompleter(urlList!!, hosts(credentialsStore), completionVariableCache) credentialsStore.get(serviceDefinition, tokenSet)?.let { completer.withVariable("account-id") { client.queryList<Account>("https://api.gdax.com/accounts", tokenSet).map { it.id } } completer.withVariable("product-id") { client.queryList<Product>("https://api.gdax.com/products", tokenSet).map { it.id } } } return completer } }
apache-2.0
7714e7c0488ef6c7be420073416831cb
36.009259
107
0.744308
4.401982
false
false
false
false
epabst/kotlin-showcase
src/jsMain/kotlin/bootstrap/kotlin_wrappers.kt
1
1126
@file:Suppress("unused") package bootstrap import org.w3c.dom.HTMLElement import org.w3c.dom.HTMLInputElement import org.w3c.dom.HTMLSelectElement import react.RBuilder import react.RElementBuilder import kotlin.reflect.KClass typealias FormControlBuilder<T> = RElementBuilder<FormControlProps<T>> private fun <T : HTMLElement> formControlClass() = Form.Control::class.unsafeCast<KClass<Form.Control<T>>>() fun RBuilder.selectControl(handler: FormControlBuilder<HTMLSelectElement>.() -> Unit) { child(formControlClass<HTMLSelectElement>()) { attrs.`as` = "select" handler() } } fun RBuilder.inputFormControl(handler: FormControlBuilder<HTMLInputElement>.() -> Unit) { child(formControlClass<HTMLInputElement>()) { attrs.`as` = "input" handler() } } var FormControlProps<HTMLInputElement>.onAnyChange: ((React.ChangeEvent<HTMLInputElement>) -> Unit)? get() = onChange set(value) { onChange = value; onKeyUp = value } var <T : HTMLElement> FormControlProps<T>.onAnyChange: ((React.ChangeEvent<T>) -> Unit)? get() = onChange set(value) { onChange = value }
apache-2.0
40f6ee49b65080aff0679e073a83e945
30.277778
108
0.722025
3.937063
false
false
false
false
xfournet/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/uast/GrUReferenceExpression.kt
1
937
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.psi.uast import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import org.jetbrains.plugins.groovy.lang.psi.GrQualifiedReference import org.jetbrains.uast.UAnnotation import org.jetbrains.uast.UElement import org.jetbrains.uast.UReferenceExpression class GrUReferenceExpression( override val sourcePsi: GrQualifiedReference<*>, parentProvider: () -> UElement? ) : UReferenceExpression { override val psi: PsiElement = sourcePsi override val javaPsi: PsiElement? = null override val resolvedName: String? = (resolve() as? PsiNamedElement)?.name override val uastParent by lazy(parentProvider) override val annotations: List<UAnnotation> = emptyList() override fun resolve(): PsiElement? = sourcePsi.resolve() }
apache-2.0
769abbf4c01f2ff8fa58e2b694244404
33.740741
140
0.790822
4.504808
false
false
false
false
googlecodelabs/tv-watchnext
step_2/src/main/java/com/example/android/watchnextcodelab/channels/WatchNextTvProvider.kt
1
8444
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.example.android.watchnextcodelab.channels import android.content.ContentUris import android.content.Context import android.net.Uri import android.provider.BaseColumns import android.support.media.tv.TvContractCompat import android.support.media.tv.WatchNextProgram import android.text.TextUtils import android.util.Log import com.example.android.watchnextcodelab.model.Movie private const val TAG = "WatchNextTvProviderFacade" private const val COLUMN_WATCH_NEXT_INTERNAL_PROVIDER_ID_INDEX = 1 private val WATCH_NEXT_MAP_PROJECTION = arrayOf( BaseColumns._ID, TvContractCompat.WatchNextPrograms.COLUMN_INTERNAL_PROVIDER_ID, TvContractCompat.WatchNextPrograms.COLUMN_BROWSABLE) /** * When adding to the watch next row, we perform the following steps: * * 1. If movie exists in the watch next row: * 1. Verify it has ***not*** been removed by the user so we can **update** the program. * 1. If it has been removed by the user (browsable ==0) then **remove** the program from the * Tv Provider and treat the movie as a new program to add. * 1. If it does not exists, then add the movie to the watch next row * */ object WatchNextTvProvider { fun addToWatchNextWatchlist(context: Context, movie: Movie): Long = addToWatchNextRow( context, movie, TvContractCompat.WatchNextPrograms.WATCH_NEXT_TYPE_WATCHLIST) fun addToWatchNextNext(context: Context, movie: Movie): Long = addToWatchNextRow(context, movie, TvContractCompat.WatchNextPrograms.WATCH_NEXT_TYPE_NEXT) fun addToWatchNextContinue(context: Context, movie: Movie, playbackPosition: Int): Long = addToWatchNextRow( context, movie, TvContractCompat.WatchNextPrograms.WATCH_NEXT_TYPE_CONTINUE, playbackPosition) private fun addToWatchNextRow( context: Context, movie: Movie, @TvContractCompat.WatchNextPrograms.WatchNextType watchNextType: Int, playbackPosition: Int? = null): Long { val movieId = movie.movieId.toString() // TODO: Step 3 - find the existing program, see if it has been removed, and check if we // should update the program. // Check if the movie is in the watch next row. val existingProgram = findProgramByMovieId(context, movieId) // If the program is not visible, remove it from the Tv Provider, and treat the movie as a // new watch next program. val removed = removeIfNotBrowsable(context, existingProgram) val shouldUpdateProgram = existingProgram != null && !removed // TODO: Step 6 - Create the content values for the Content Provider. val builder = if (shouldUpdateProgram) { WatchNextProgram.Builder(existingProgram) } else { convertMovie(movie) } // Update the Watch Next type since the user has explicitly asked for the movie to be added // to the Play Next row. // TODO: Step 9 Update the watch next type. builder.setWatchNextType(TvContractCompat.WatchNextPrograms.WATCH_NEXT_TYPE_CONTINUE) .setLastEngagementTimeUtcMillis(System.currentTimeMillis()) if (playbackPosition != null) { builder.setLastPlaybackPositionMillis(playbackPosition) } val contentValues = builder.build().toContentValues() // TODO: Step 7 - Update or add the program to the content provider. if (shouldUpdateProgram) { val program = existingProgram as WatchNextProgram val watchNextProgramId = program.id val watchNextProgramUri = TvContractCompat.buildWatchNextProgramUri(watchNextProgramId) val rowsUpdated = context.contentResolver.update( watchNextProgramUri, contentValues, null, null) if (rowsUpdated < 1) { Log.e(TAG, "Failed to update watch next program $watchNextProgramId") return -1L } return watchNextProgramId } else { val programUri = context.contentResolver.insert( TvContractCompat.WatchNextPrograms.CONTENT_URI, contentValues) if (programUri == null || programUri == Uri.EMPTY) { Log.e(TAG, "Failed to insert movie, $movieId, into the watch next row") } return ContentUris.parseId(programUri) } } fun deleteFromWatchNext(context: Context, movieId: String) { val program = findProgramByMovieId(context = context, movieId = movieId) if (program != null) { removeProgram(context = context, watchNextProgramId = program.id) } } private fun findProgramByMovieId(context: Context, movieId: String): WatchNextProgram? { // TODO: Step 4 - Find the movie by our app's internal id. context.contentResolver .query(TvContractCompat.WatchNextPrograms.CONTENT_URI, WATCH_NEXT_MAP_PROJECTION, null, null, null, null) ?.use { cursor -> if (cursor.moveToFirst()) { do { val watchNextInternalId = cursor.getString(COLUMN_WATCH_NEXT_INTERNAL_PROVIDER_ID_INDEX) if (movieId == watchNextInternalId) { return WatchNextProgram.fromCursor(cursor) } } while (cursor.moveToNext()) } } return null } private fun removeIfNotBrowsable(context: Context, program: WatchNextProgram?): Boolean { // TODO: Step 5 - Check is a program has been removed from the UI by the user. If so, then // remove the program from the content provider. if (program?.isBrowsable == false) { val watchNextProgramId = program.id removeProgram(context, watchNextProgramId) return true } return false } private fun removeProgram(context: Context, watchNextProgramId: Long): Int { val rowsDeleted = context.contentResolver.delete( TvContractCompat.buildWatchNextProgramUri(watchNextProgramId), null, null) if (rowsDeleted < 1) { Log.e(TAG, "Failed to delete program ($watchNextProgramId) from Watch Next row") } return rowsDeleted } private fun convertMovie(movie: Movie): WatchNextProgram.Builder { val movieId = java.lang.Long.toString(movie.movieId) val builder = WatchNextProgram.Builder() builder.setTitle(movie.title) .setDescription(movie.description) .setDurationMillis(movie.duration.toInt()) .setType(TvContractCompat.PreviewPrograms.TYPE_MOVIE) .setIntentUri(Uri .withAppendedPath(BASE_URI, PLAY_VIDEO_ACTION_PATH) .buildUpon() .appendPath(movieId) .build()) .setInternalProviderId(movieId) .setContentId(movieId) .setPreviewVideoUri(Uri.parse(movie.previewVideoUrl)) .setPosterArtUri(Uri.parse(movie.thumbnailUrl)) .setPosterArtAspectRatio(movie.posterArtAspectRatio) .setContentRatings(arrayOf(movie.contentRating)) .setGenre(movie.genre) .setLive(movie.isLive) .setReleaseDate(movie.releaseDate) .setReviewRating(movie.rating) .setReviewRatingStyle(movie.ratingStyle) .setStartingPrice(movie.startingPrice) .setOfferPrice(movie.offerPrice) .setVideoWidth(movie.width) .setVideoHeight(movie.height) return builder } }
apache-2.0
341274f8fe34b34c988556a767b8cf6d
40.596059
100
0.646139
4.978774
false
false
false
false
vsch/idea-multimarkdown
src/main/java/com/vladsch/md/nav/settings/MdRenderingProfile.kt
1
19037
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.settings import com.intellij.openapi.project.Project import com.vladsch.flexmark.util.data.DataKey import com.vladsch.md.nav.editor.util.HtmlPanelProvider import com.vladsch.md.nav.editor.util.InjectHtmlResource import com.vladsch.md.nav.language.MdCodeStyleSettings import com.vladsch.md.nav.settings.api.* import com.vladsch.md.nav.vcs.MdLinkResolver import java.util.* import kotlin.collections.LinkedHashSet class MdRenderingProfile(private val mySettingsExtensions: MdExtendableSettingsImpl = MdExtendableSettingsImpl()) : StateHolderImpl({ MdRenderingProfile() }) , MdExtendableSettings by mySettingsExtensions , MdRenderingProfileHolder { private val myHaveExtensionSettings = LinkedHashSet<DataKey<*>>() init { mySettingsExtensions.initializeExtensions(this) // set all extensions as overriding project settings if they have isOverride by default mySettingsExtensions.extensionKeys.forEach { if ((it.get(extensions) as MdOverrideSettings).isOverrideByDefault) { myHaveExtensionSettings.add(it) } } } var profileName: String = "" /** * this one is the default selected on render settings as default project profile */ @Suppress("MemberVisibilityCanBePrivate") var isDefaultProfile: Boolean = false private set /** * Project Default ie. the one shown in main settings */ var isProjectProfile: Boolean = false private set private val _previewSettings: MdPreviewSettings = MdPreviewSettings() private val _parserSettings: MdParserSettings = MdParserSettings() private val _htmlSettings: MdHtmlSettings = MdHtmlSettings() private val _cssSettings: MdCssSettings = MdCssSettings() private val _styleSettings: MdCodeStyleSettings = MdCodeStyleSettings() // these are project style settings private var _project: Project? = null override var previewSettings: MdPreviewSettings get() = _previewSettings set(value) = _previewSettings.copyFrom(value) override var parserSettings: MdParserSettings get() = _parserSettings set(value) = _parserSettings.copyFrom(value) override var htmlSettings: MdHtmlSettings get() = _htmlSettings set(value) = _htmlSettings.copyFrom(value) override var cssSettings: MdCssSettings get() = _cssSettings set(value) = _cssSettings.copyFrom(value) // FIX: complete implementation of rendering profile code style settings val resolvedStyleSettings: MdCodeStyleSettings get() { val project = _project return if ((isProjectProfile || !haveStyleSettings) && project != null) MdCodeStyleSettings.getInstance(project) else _styleSettings } private val isProjectStyleSettings: Boolean get() = isProjectProfile && _project != null override fun getStyleSettings(): MdCodeStyleSettings { val project = _project return if (isProjectProfile && project != null) MdCodeStyleSettings.getInstance(project) else _styleSettings } override fun setStyleSettings(value: MdCodeStyleSettings) { val project = _project if (isProjectProfile && project != null) MdCodeStyleSettings.getInstance(project).copyFrom(value) else _styleSettings.copyFrom(value) } override fun validateLoadedSettings() { // Allow extensions to validate profile settings and to migrate them if necessary for (validator in MdRenderingProfileValidator.EXTENSIONS.value) { validator.validateSettings(renderingProfile) } mySettingsExtensions.validateLoadedSettings() _previewSettings.validateLoadedSettings() _parserSettings.validateLoadedSettings() _htmlSettings.validateLoadedSettings() _cssSettings.validateLoadedSettings() } fun getProject(): Project? { return _project } fun setProject(project: Project) { _project = project } fun setProjectProfile(project: Project) { assert(this._project == null) this._project = project haveStyleSettings = false haveRightMargin = false isProjectProfile = true } // NOTE: changing to false messes up existing profiles var havePreviewSettings: Boolean = true var haveParserSettings: Boolean = true var haveHtmlSettings: Boolean = true var haveCssSettings: Boolean = true var haveStyleSettings: Boolean = false var haveRightMargin: Boolean = false @Suppress("PropertyName") var RIGHT_MARGIN: Int = MdCodeStyleSettings.DEFAULT_RIGHT_MARGIN fun getRightMargin(): Int { if (!haveRightMargin || (this.RIGHT_MARGIN < MdCodeStyleSettings.MIN_RIGHT_MARGIN || this.RIGHT_MARGIN > MdCodeStyleSettings.MAX_RIGHT_MARGIN)) { if (isProjectStyleSettings || !haveStyleSettings || (_styleSettings.RIGHT_MARGIN < MdCodeStyleSettings.MIN_RIGHT_MARGIN || _styleSettings.RIGHT_MARGIN > MdCodeStyleSettings.MAX_RIGHT_MARGIN)) { return if (_project != null) { resolvedStyleSettings.rightMargin } else { MdCodeStyleSettings.DEFAULT_RIGHT_MARGIN } } return _styleSettings.RIGHT_MARGIN } return this.RIGHT_MARGIN } fun <T : MdSettingsExtension<T>> getHaveExtensionSettings(key: DataKey<T>): Boolean { return myHaveExtensionSettings.contains(key) } fun <T : MdSettingsExtension<T>> setHaveExtensionSettings(key: DataKey<T>, value: Boolean) { if (value) { myHaveExtensionSettings.add(key) } else { myHaveExtensionSettings.remove(key) } } private constructor( isDefaultProfile: Boolean , profileName: String , previewSettings: MdPreviewSettings , parserSettings: MdParserSettings , htmlSettings: MdHtmlSettings , cssSettings: MdCssSettings , styleSettings: MdCodeStyleSettings ) : this() { this.isDefaultProfile = isDefaultProfile this.profileName = profileName this.previewSettings = previewSettings this.parserSettings = parserSettings this.htmlSettings = htmlSettings this.cssSettings = cssSettings this.styleSettings = styleSettings } constructor(other: MdRenderingProfile) : this() { copyFrom(other, true) } fun copyFrom(other: MdRenderingProfile, withExtensions: Boolean) { if (this !== other) { profileName = other.profileName previewSettings = other.previewSettings parserSettings = other.parserSettings htmlSettings = other.htmlSettings cssSettings = other.cssSettings havePreviewSettings = other.havePreviewSettings haveParserSettings = other.haveParserSettings haveHtmlSettings = other.haveHtmlSettings haveCssSettings = other.haveCssSettings _project = _project ?: other._project _styleSettings.copyFrom(other.styleSettings) haveStyleSettings = other.haveStyleSettings haveRightMargin = other.haveRightMargin RIGHT_MARGIN = other.RIGHT_MARGIN if (withExtensions) { mySettingsExtensions.copyFrom(other) myHaveExtensionSettings.clear() myHaveExtensionSettings.addAll(other.myHaveExtensionSettings.intersect(mySettingsExtensions.extensionKeys)) } } } fun isDefault(): Boolean { if (!(havePreviewSettings && haveParserSettings && haveHtmlSettings && haveCssSettings && !haveStyleSettings && !haveRightMargin)) return false if (!mySettingsExtensions.extensionKeys.all { key -> myHaveExtensionSettings.contains(key) }) return false @Suppress("SuspiciousEqualsCombination") if (!(previewSettings.isDefault(previewSettings.htmlPanelProviderInfo) && parserSettings.isDefault(previewSettings.htmlPanelProviderInfo) && htmlSettings.isDefault(previewSettings.htmlPanelProviderInfo) && cssSettings.isDefault(previewSettings.htmlPanelProviderInfo) && (isProjectStyleSettings || _styleSettings == MdCodeStyleSettings.DEFAULT))) return false if (!mySettingsExtensions.extensionKeys.all { key -> // NOTE: kotlin compiler spews up if method changed to property access @Suppress("UsePropertyAccessSyntax") key[mySettingsExtensions.extensions].isDefault() }) return false return true } override fun isExtensionDefault(key: DataKey<MdSettingsExtension<*>>): Boolean { if (!mySettingsExtensions.extensionKeys.contains(key)) return true if (!myHaveExtensionSettings.contains(key)) return false val defaultSetting = key.defaultValue val settingsExtension = key[mySettingsExtensions.extensions] return settingsExtension == defaultSetting } override var renderingProfile: MdRenderingProfile get() = this set(value) { copyFrom(value, true) } override fun getResolvedProfile(parentProfile: MdRenderingProfile): MdRenderingProfile { if (havePreviewSettings && haveParserSettings && haveCssSettings && haveHtmlSettings) { return this } else { val newRenderingProfile = MdRenderingProfile() newRenderingProfile.profileName = profileName newRenderingProfile.previewSettings = if (havePreviewSettings) previewSettings else parentProfile.previewSettings newRenderingProfile.parserSettings = if (haveParserSettings) parserSettings else parentProfile.parserSettings newRenderingProfile.htmlSettings = if (haveHtmlSettings) htmlSettings else parentProfile.htmlSettings newRenderingProfile.cssSettings = if (haveCssSettings) cssSettings else parentProfile.cssSettings // these are copied but resolve to project code style settings on their own newRenderingProfile._project = _project ?: parentProfile._project newRenderingProfile.haveStyleSettings = haveStyleSettings newRenderingProfile.haveRightMargin = haveRightMargin newRenderingProfile._styleSettings.copyFrom(styleSettings) newRenderingProfile.RIGHT_MARGIN = RIGHT_MARGIN mySettingsExtensions.extensionKeys.forEach { key -> if (!myHaveExtensionSettings.contains(key) || !mySettingsExtensions.extensions.contains(key)) { newRenderingProfile.mySettingsExtensions.extensions.set(key, key[parentProfile.mySettingsExtensions.extensions]) } else { newRenderingProfile.mySettingsExtensions.extensions.set(key, key[mySettingsExtensions.extensions]) } newRenderingProfile.myHaveExtensionSettings.add(key) } return newRenderingProfile } } override fun groupNotifications(runnable: Runnable) { runnable.run() } override fun getStateHolder(): StateHolder { val tagItemHolder = TagItemHolder(STATE_ELEMENT_NAME).addItems( StringAttribute("name", { "myName" }, { }), // needed for rendering profiles, is a read only field, ie. it is written out to storage but not read in but used by IDE configuration state splitter StringAttribute("value", { profileName }, { profileName = it }), StringAttribute("profileName", { profileName }, { profileName = it }), BooleanAttribute("havePreviewSettings", { havePreviewSettings }, { havePreviewSettings = it }), BooleanAttribute("haveParserSettings", { haveParserSettings }, { haveParserSettings = it }), BooleanAttribute("haveHtmlSettings", { haveHtmlSettings }, { haveHtmlSettings = it }), BooleanAttribute("haveCssSettings", { haveCssSettings }, { haveCssSettings = it }), BooleanAttribute("haveStyleSettings", { haveStyleSettings }, { haveStyleSettings = it }), BooleanAttribute("haveRightMargin", { haveRightMargin }, { haveRightMargin = it }), IntAttribute("rightMargin", { this.RIGHT_MARGIN }, { this.RIGHT_MARGIN = it }) ) mySettingsExtensions.extensionKeys.forEach { key -> // add haveSettings attribute val name = getKeyHaveSettings(key) tagItemHolder.addItems(BooleanAttribute(name, { myHaveExtensionSettings.contains(key) }, { if (it) myHaveExtensionSettings.add(key) else myHaveExtensionSettings.remove(key) })) } addUnwrappedItems(this, tagItemHolder) return tagItemHolder } private val codeStyleSettingsSerializable: MdCodeStyleSettingsSerializable get() = MdCodeStyleSettingsSerializable(_styleSettings) override fun addUnwrappedItems(container: Any, tagItemHolder: TagItemHolder): TagItemHolder { mySettingsExtensions.addUnwrappedItems(container, tagItemHolder.addItems( UnwrappedSettings(previewSettings), UnwrappedSettings(parserSettings), UnwrappedSettings(htmlSettings), UnwrappedSettings(cssSettings) )) // FIX: enable when UI is ready if (!isProjectProfile && false) { // NOTE: no need to create a new item. Factory just loads settings into the instance val codeStyleSettingsSerializable1 = codeStyleSettingsSerializable tagItemHolder.addItems(UnwrappedItem({ codeStyleSettingsSerializable1 }, {}, { codeStyleSettingsSerializable1.loadState(it) codeStyleSettingsSerializable1 })) } previewSettings.addUnwrappedItems(container, tagItemHolder) parserSettings.addUnwrappedItems(container, tagItemHolder) htmlSettings.addUnwrappedItems(container, tagItemHolder) cssSettings.addUnwrappedItems(container, tagItemHolder) return tagItemHolder } fun injectHtmlResource(linkResolver: MdLinkResolver, injections: ArrayList<InjectHtmlResource?>) { MdPreviewSettings.injectHtmlResource(linkResolver, this, injections) MdCssSettings.injectHtmlResource(linkResolver, this, injections) MdHtmlSettings.injectHtmlResource(this, injections) } fun getName(): String { return profileName } fun setName(name: String) { profileName = name } companion object { const val STATE_ELEMENT_NAME: String = "option" private fun getKeyHaveSettings(key: DataKey<*>): String { val name = key.name var useName = name val pos = name.lastIndexOf('.') if (pos >= 0) useName = useName.substring(pos + 1) useName = useName.removePrefix("MdEnh").removePrefix("Md") useName = "have$useName" return useName } @JvmStatic val DEFAULT: MdRenderingProfile = MdRenderingProfile(true, "", MdPreviewSettings.DEFAULT, MdParserSettings.DEFAULT, MdHtmlSettings.DEFAULT, MdCssSettings.DEFAULT, MdCodeStyleSettings.DEFAULT) @JvmStatic val FOR_SAMPLE_DOC: MdRenderingProfile = MdRenderingProfile(true, "", MdPreviewSettings.DEFAULT, MdParserSettings.FOR_SAMPLE_DOC, MdHtmlSettings.DEFAULT, MdCssSettings.DEFAULT, MdCodeStyleSettings.DEFAULT) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false other as MdRenderingProfile if (havePreviewSettings != other.havePreviewSettings) return false if (haveParserSettings != other.haveParserSettings) return false if (haveHtmlSettings != other.haveHtmlSettings) return false if (haveCssSettings != other.haveCssSettings) return false if (haveStyleSettings != other.haveStyleSettings) return false if (haveRightMargin != other.haveRightMargin) return false if (!myHaveExtensionSettings.containsAll(other.myHaveExtensionSettings)) return false if (!other.myHaveExtensionSettings.containsAll(myHaveExtensionSettings)) return false if (profileName != other.profileName) return false if (previewSettings != other.previewSettings) return false if (parserSettings != other.parserSettings) return false if (htmlSettings != other.htmlSettings) return false if (cssSettings != other.cssSettings) return false if (!isProjectProfile && haveStyleSettings && _styleSettings != other._styleSettings) return false if (RIGHT_MARGIN != other.RIGHT_MARGIN) return false return mySettingsExtensions == other } override fun hashCode(): Int { var result = mySettingsExtensions.hashCode() result += 31 * result + myHaveExtensionSettings.hashCode() result += 31 * result + profileName.hashCode() result += 31 * result + previewSettings.hashCode() result += 31 * result + parserSettings.hashCode() result += 31 * result + htmlSettings.hashCode() result += 31 * result + cssSettings.hashCode() result += 31 * result + _styleSettings.hashCode() result += 31 * result + RIGHT_MARGIN.hashCode() result += 31 * result + havePreviewSettings.hashCode() result += 31 * result + haveParserSettings.hashCode() result += 31 * result + haveHtmlSettings.hashCode() result += 31 * result + haveCssSettings.hashCode() result += 31 * result + haveStyleSettings.hashCode() result += 31 * result + haveRightMargin.hashCode() return result } fun changeToProvider(fromPanelProviderInfo: HtmlPanelProvider.Info?, toPanelProviderInfo: HtmlPanelProvider.Info?): MdRenderingProfile { val newRenderingProfile = MdRenderingProfile(this) newRenderingProfile.previewSettings.changeToProvider(fromPanelProviderInfo, toPanelProviderInfo) newRenderingProfile.cssSettings.changeToProvider(fromPanelProviderInfo, newRenderingProfile.previewSettings.htmlPanelProviderInfo) newRenderingProfile.htmlSettings.changeToProvider(fromPanelProviderInfo, newRenderingProfile.previewSettings.htmlPanelProviderInfo) newRenderingProfile.parserSettings.changeToProvider(fromPanelProviderInfo, newRenderingProfile.previewSettings.htmlPanelProviderInfo) mySettingsExtensions.containedExtensionKeys.forEach { it[newRenderingProfile.extensions].copyFrom(extensions) it[newRenderingProfile.extensions].changeToProvider(fromPanelProviderInfo, toPanelProviderInfo) } return newRenderingProfile } }
apache-2.0
5ac81387cf3bb3681ee3c6b1c9c17641
42.965358
213
0.687661
6.099648
false
false
false
false
uber/RIBs
android/libraries/rib-base/src/main/kotlin/com/uber/rib/core/Rib.kt
1
3922
/* * Copyright (C) 2017. Uber Technologies * * 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.uber.rib.core /** Holds configuration and settings for riblets. */ open class Rib { /** Responsible for app-specific riblet configuration. */ interface Configuration { /** * Called when there is a non-fatal error in the RIB framework. Consumers should route this data * to a place where it can be monitored (crash reporting, monitoring, etc.). * * * If no configuration is set, the default implementation of this will crash the app when * there is a non-fatal error. * * @param errorMessage an error message that describes the error. * @param throwable an optional throwable. */ fun handleNonFatalError(errorMessage: String, throwable: Throwable?) /** * Called when there is a non-fatal warning in the RIB framework. Consumers should route this * data to a place where it can be monitored (crash reporting, monitoring, etc.). * * * NOTE: This API is used in a slightly different way than the [ ][Configuration.handleNonFatalError] error method. Non-fatal errors should * never happen, warnings however can happen in certain conditions. * * @param warningMessage an error message that describes the error. * @param throwable an optional throwable. */ fun handleNonFatalWarning(warningMessage: String, throwable: Throwable?) /** * Called when there is a message that should be logged for debugging. Consumers should route * this data to a debug logging location. * * * If no configuration is set, the default implementation of this will drop the messages. * * @param format Message format - See [String.format] * @param args Arguments to use for printing the message. */ fun handleDebugMessage(format: String, vararg args: Any?) } /** Default, internal implementation that is used when host app does not set a configuration. */ private class DefaultConfiguration : Configuration { override fun handleNonFatalError(errorMessage: String, throwable: Throwable?) { throw RuntimeException(errorMessage, throwable) } override fun handleNonFatalWarning(warningMessage: String, throwable: Throwable?) {} override fun handleDebugMessage(format: String, vararg args: Any?) {} } companion object { /** * Sets the configuration to use in the application. This can only be called once before any RIB * code is used. Calling it twice, or calling it after using RIB code will throw an exception. * * @param configurationToSet to set. */ private var configuration: Configuration? = null @JvmStatic fun setConfiguration(configurationToSet: Configuration) { if (configuration == null) { configuration = configurationToSet } else { if (configuration is DefaultConfiguration) { throw IllegalStateException("Attempting to set a configuration after using RIB code.") } else { throw IllegalStateException( "Attempting to set a configuration after one has previously been set." ) } } } @JvmStatic fun getConfiguration(): Configuration { if (configuration == null) { configuration = DefaultConfiguration() } return configuration!! } } }
apache-2.0
33410d87b89238714b47c493cc48c9e5
36.711538
143
0.690209
4.841975
false
true
false
false
NordicSemiconductor/Android-nRF-Toolbox
profile_bps/src/main/java/no/nordicsemi/android/bps/viewmodel/BPSViewModel.kt
1
3993
/* * Copyright (c) 2022, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. 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. * * 3. Neither the name of the copyright holder 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 * HOLDER 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 no.nordicsemi.android.bps.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import no.nordicsemi.android.analytics.AppAnalytics import no.nordicsemi.android.analytics.Profile import no.nordicsemi.android.analytics.ProfileConnectedEvent import no.nordicsemi.android.bps.data.BPS_SERVICE_UUID import no.nordicsemi.android.bps.repository.BPSRepository import no.nordicsemi.android.bps.view.* import no.nordicsemi.android.navigation.* import no.nordicsemi.android.service.ConnectedResult import no.nordicsemi.android.utils.exhaustive import no.nordicsemi.android.utils.getDevice import no.nordicsemi.ui.scanner.DiscoveredBluetoothDevice import no.nordicsemi.ui.scanner.ScannerDestinationId import javax.inject.Inject @HiltViewModel internal class BPSViewModel @Inject constructor( private val repository: BPSRepository, private val navigationManager: NavigationManager, private val analytics: AppAnalytics ) : ViewModel() { private val _state = MutableStateFlow<BPSViewState>(NoDeviceState) val state = _state.asStateFlow() init { navigationManager.navigateTo(ScannerDestinationId, UUIDArgument(BPS_SERVICE_UUID)) navigationManager.recentResult.onEach { if (it.destinationId == ScannerDestinationId) { handleArgs(it) } }.launchIn(viewModelScope) } private fun handleArgs(args: DestinationResult) { when (args) { is CancelDestinationResult -> navigationManager.navigateUp() is SuccessDestinationResult -> connectDevice(args.getDevice()) }.exhaustive } fun onEvent(event: BPSViewEvent) { when (event) { DisconnectEvent -> navigationManager.navigateUp() OpenLoggerEvent -> repository.openLogger() }.exhaustive } private fun connectDevice(device: DiscoveredBluetoothDevice) { repository.downloadData(viewModelScope, device).onEach { _state.value = WorkingState(it) (it as? ConnectedResult)?.let { analytics.logEvent(ProfileConnectedEvent(Profile.BPS)) } }.launchIn(viewModelScope) } }
bsd-3-clause
b79846e6a83eba0374b2b9f8bf93d3a8
39.744898
90
0.754821
4.83414
false
false
false
false
square/duktape-android
zipline/src/jniMain/kotlin/app/cash/zipline/internal/bridge/throwablesJni.kt
1
1807
/* * Copyright (C) 2021 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.cash.zipline.internal.bridge /** When encoding a stacktrace, chop Zipline frames off below the inbound call. */ internal actual fun stacktraceString(throwable: Throwable): String { for ((index, element) in throwable.stackTrace.withIndex()) { if (element.className.startsWith(Endpoint::class.qualifiedName!!)) { throwable.stackTrace = throwable.stackTrace.sliceArray(0 until index) break } } return throwable.stackTraceToString().trim() } /** When decoding a stacktrace, chop Zipline frames off above the outbound call. */ internal actual fun toInboundThrowable( stacktraceString: String, constructor: (String) -> Throwable, ): Throwable { // Strip empty lines and format 'at' to match java.lang.Throwable. val canonicalString = stacktraceString .replace(Regex("\n[ ]+at "), "\n\tat ") .replace(Regex("\n+"), "\n") .trim() val result = constructor(canonicalString) val stackTrace = result.stackTrace for (i in stackTrace.size - 1 downTo 0) { if (stackTrace[i].className == OutboundCallHandler::class.qualifiedName) { result.stackTrace = stackTrace.sliceArray(i + 1 until stackTrace.size) break } } return result }
apache-2.0
a4bf35d6edfd5fe24e480801e53b29b4
34.431373
83
0.716104
4.221963
false
false
false
false
tipsy/javalin
javalin-openapi/src/main/java/io/javalin/plugin/openapi/utils/OpenApiVersionUtil.kt
1
763
package io.javalin.plugin.openapi.utils object OpenApiVersionUtil { var logWarnings = true val javaVersion = System.getProperty("java.version").split(".")[0].replace(Regex("[^0-9]+"), "").toInt() val kotlinVersion = KotlinVersion.CURRENT.minor // let's face it, to JetBrains minor means major val hasIssue = javaVersion >= 15 || kotlinVersion >= 5 val warning = try { when { javaVersion >= 15 && kotlinVersion >= 5 -> "JDK15 and Kotlin 1.5 break reflection in different ways" javaVersion >= 15 -> "JDK 15 has a breaking change to reflection" kotlinVersion >= 5 -> "Kotlin 1.5 has a breaking change to reflection" else -> null } } catch (e: Exception) { null } }
apache-2.0
cbd4487cfa81b2fc15152e2693fe45a4
41.388889
112
0.622543
4.488235
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/registry/type/block/BlockStateRegistry.kt
1
3201
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.registry.type.block import it.unimi.dsi.fastutil.objects.Object2IntMap import it.unimi.dsi.fastutil.objects.Object2IntMaps import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap import org.lanternpowered.api.block.BlockState import org.lanternpowered.api.block.BlockType import org.lanternpowered.api.block.BlockTypes import org.lanternpowered.api.registry.CatalogTypeRegistry import org.lanternpowered.server.game.registry.InternalRegistries.readJsonArray import org.lanternpowered.server.registry.mutableInternalCatalogTypeRegistry import org.lanternpowered.server.state.IState import org.lanternpowered.server.util.palette.asPalette val BlockStateRegistry = mutableInternalCatalogTypeRegistry<BlockState>() /** * The global [BlockState] palette. */ val GlobalBlockStatePalette = BlockStateRegistry.asPalette { BlockTypes.AIR.get().defaultState } /** * Loads the block state registry. */ fun loadBlockStateRegistry(registry: CatalogTypeRegistry<BlockType>) { BlockStateRegistry.load { for (type in registry.all) { val baseId = InternalBlockStateData.blockStateStartIds.getInt(type.key.formatted) for (state in type.validStates) { state as IState<*> val id = baseId + state.index this.register(id, state) } } } } /** * Internal data related to block states. */ object InternalBlockStateData { /** * A map with all the network ids for the [BlockType]s. Multiple * ids may be reserved depending on the amount of states of the block type. */ var blockStateStartIds: Object2IntMap<String> var blockTypeIds: Object2IntMap<String> var blockStatesAssigned: Int init { val blockStateStartIds = Object2IntOpenHashMap<String>() blockStateStartIds.defaultReturnValue(-1) val blockTypeIds = Object2IntOpenHashMap<String>() blockTypeIds.defaultReturnValue(-1) var blockStates = 0 val jsonArray = readJsonArray("block") for ((blockTypes, index) in (0 until jsonArray.size()).withIndex()) { val element = jsonArray[index] var id: String var states = 1 if (element.isJsonPrimitive) { id = element.asString } else { val obj = element.asJsonObject id = obj["id"].asString if (obj.has("states")) { states = obj["states"].asInt } } blockStateStartIds[id] = blockStates blockStates += states blockTypeIds[id] = blockTypes } this.blockStatesAssigned = blockStates this.blockStateStartIds = Object2IntMaps.unmodifiable(blockStateStartIds) this.blockTypeIds = Object2IntMaps.unmodifiable(blockTypeIds) } }
mit
472f806589200e5448e2810c817040cb
34.966292
96
0.68135
4.592539
false
true
false
false
raatiniemi/worker
app/src/main/java/me/raatiniemi/worker/data/repository/TimeIntervalRoomRepository.kt
1
2904
/* * Copyright (C) 2018 Tobias Raatiniemi * * 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, version 2 of the License. * * 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 me.raatiniemi.worker.data.repository import me.raatiniemi.worker.data.projects.TimeIntervalDao import me.raatiniemi.worker.data.projects.toEntity import me.raatiniemi.worker.domain.model.Project import me.raatiniemi.worker.domain.model.TimeInterval import me.raatiniemi.worker.domain.repository.TimeIntervalRepository import me.raatiniemi.worker.util.Optional class TimeIntervalRoomRepository(private val timeIntervals: TimeIntervalDao) : TimeIntervalRepository { override fun findAll(project: Project, milliseconds: Long): List<TimeInterval> { return timeIntervals.findAll(projectId = project.id!!, startInMilliseconds = milliseconds) .map { it.toTimeInterval() } .toList() } override fun findById(id: Long): Optional<TimeInterval> { val entity = timeIntervals.find(id) ?: return Optional.empty() return Optional.ofNullable(entity.toTimeInterval()) } override fun findActiveByProjectId(projectId: Long): Optional<TimeInterval> { val entity = timeIntervals.findActiveTime(projectId) ?: return Optional.empty() return Optional.of(entity.toTimeInterval()) } override fun add(timeInterval: TimeInterval): Optional<TimeInterval> { val id = timeIntervals.add(timeInterval.toEntity()) return findById(id) } override fun update(timeInterval: TimeInterval): Optional<TimeInterval> { val entity = timeInterval.toEntity() timeIntervals.update(listOf(entity)) return findById(entity.id) } override fun update(timeIntervals: List<TimeInterval>): List<TimeInterval> { val entities = timeIntervals.map { it.toEntity() }.toList() this.timeIntervals.update(entities) return timeIntervals.mapNotNull { it.id } .mapNotNull { this.timeIntervals.find(it) } .map { it.toTimeInterval() } .toList() } override fun remove(id: Long) { val entity = timeIntervals.find(id) ?: return timeIntervals.remove(listOf(entity)) } override fun remove(timeIntervals: List<TimeInterval>) { val entities = timeIntervals.map { it.toEntity() }.toList() this.timeIntervals.remove(entities) } }
gpl-2.0
86516dab416191d44bc78e0b4d5d76c2
35.759494
103
0.706267
4.624204
false
false
false
false
world-federation-of-advertisers/cross-media-measurement
src/test/kotlin/org/wfanet/measurement/kingdom/service/system/v1alpha/ComputationParticipantsServiceTest.kt
1
13840
// Copyright 2021 The Cross-Media Measurement 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.wfanet.measurement.kingdom.service.system.v1alpha import com.google.common.truth.Truth.assertThat import com.google.common.truth.extensions.proto.ProtoTruth.assertThat import com.google.protobuf.ByteString import com.google.protobuf.timestamp import io.grpc.Status import io.grpc.StatusRuntimeException import kotlinx.coroutines.runBlocking import org.junit.Assert import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.mockito.kotlin.any import org.mockito.kotlin.whenever import org.wfanet.measurement.common.grpc.testing.GrpcTestServerRule import org.wfanet.measurement.common.grpc.testing.mockService import org.wfanet.measurement.common.identity.DuchyIdentity import org.wfanet.measurement.common.identity.externalIdToApiId import org.wfanet.measurement.common.identity.testing.DuchyIdSetter import org.wfanet.measurement.common.testing.verifyProtoArgument import org.wfanet.measurement.internal.kingdom.CertificateKt as InternalCertificateKt import org.wfanet.measurement.internal.kingdom.ComputationParticipant as InternalComputationParticipant import org.wfanet.measurement.internal.kingdom.ComputationParticipantKt as InternalComputationParticipantKt import org.wfanet.measurement.internal.kingdom.ComputationParticipantsGrpcKt.ComputationParticipantsCoroutineImplBase as InternalComputationParticipantsCoroutineService import org.wfanet.measurement.internal.kingdom.ComputationParticipantsGrpcKt.ComputationParticipantsCoroutineStub as InternalComputationParticipantsCoroutineStub import org.wfanet.measurement.internal.kingdom.ConfirmComputationParticipantRequest as InternalConfirmComputationParticipantRequest import org.wfanet.measurement.internal.kingdom.DuchyMeasurementLogEntryKt import org.wfanet.measurement.internal.kingdom.FailComputationParticipantRequest as InternalFailComputationParticipantRequest import org.wfanet.measurement.internal.kingdom.MeasurementLogEntry import org.wfanet.measurement.internal.kingdom.MeasurementLogEntryKt import org.wfanet.measurement.internal.kingdom.SetParticipantRequisitionParamsRequest as InternalSetParticipantRequisitionParamsRequest import org.wfanet.measurement.internal.kingdom.certificate as internalCertificate import org.wfanet.measurement.internal.kingdom.copy import org.wfanet.measurement.internal.kingdom.duchyMeasurementLogEntry import org.wfanet.measurement.internal.kingdom.measurementLogEntry import org.wfanet.measurement.system.v1alpha.ComputationParticipant import org.wfanet.measurement.system.v1alpha.ComputationParticipantKt.RequisitionParamsKt.liquidLegionsV2 import org.wfanet.measurement.system.v1alpha.ComputationParticipantKt.requisitionParams import org.wfanet.measurement.system.v1alpha.ConfirmComputationParticipantRequest import org.wfanet.measurement.system.v1alpha.FailComputationParticipantRequest import org.wfanet.measurement.system.v1alpha.SetParticipantRequisitionParamsRequest import org.wfanet.measurement.system.v1alpha.computationParticipant private const val DUCHY_ID: String = "some-duchy-id" private const val MILL_ID: String = "some-mill-id" private const val STAGE_ATTEMPT_STAGE = 9 private const val STAGE_ATTEMPT_STAGE_NAME = "a stage" private const val STAGE_ATTEMPT_ATTEMPT_NUMBER = 1L private const val DUCHY_ERROR_MESSAGE = "something is wrong." private const val PUBLIC_API_VERSION = "v2alpha" private const val EXTERNAL_COMPUTATION_ID = 1L private const val EXTERNAL_DUCHY_CERTIFICATE_ID = 4L private val EXTERNAL_COMPUTATION_ID_STRING = externalIdToApiId(EXTERNAL_COMPUTATION_ID) private val EXTERNAL_DUCHY_CERTIFICATE_ID_STRING = externalIdToApiId(EXTERNAL_DUCHY_CERTIFICATE_ID) private val DUCHY_CERTIFICATE_PUBLIC_API_NAME = "duchies/$DUCHY_ID/certificates/$EXTERNAL_DUCHY_CERTIFICATE_ID_STRING" private val SYSTEM_COMPUTATION_PARTICIPANT_NAME = "computations/$EXTERNAL_COMPUTATION_ID_STRING/participants/$DUCHY_ID" private val DUCHY_CERTIFICATE_DER = ByteString.copyFromUtf8("an X.509 certificate") private val DUCHY_ELGAMAL_KEY = ByteString.copyFromUtf8("an elgamal key.") private val DUCHY_ELGAMAL_KEY_SIGNATURE = ByteString.copyFromUtf8("an elgamal key signature.") private val INTERNAL_COMPUTATION_PARTICIPANT = InternalComputationParticipant.newBuilder() .apply { externalDuchyId = DUCHY_ID externalComputationId = EXTERNAL_COMPUTATION_ID state = InternalComputationParticipant.State.CREATED updateTimeBuilder.apply { seconds = 123 nanos = 456 } apiVersion = PUBLIC_API_VERSION } .build() private val INTERNAL_COMPUTATION_PARTICIPANT_WITH_PARAMS = INTERNAL_COMPUTATION_PARTICIPANT.copy { state = InternalComputationParticipant.State.REQUISITION_PARAMS_SET details = InternalComputationParticipantKt.details { liquidLegionsV2 = InternalComputationParticipantKt.liquidLegionsV2Details { elGamalPublicKey = DUCHY_ELGAMAL_KEY elGamalPublicKeySignature = DUCHY_ELGAMAL_KEY_SIGNATURE } } duchyCertificate = internalCertificate { externalDuchyId = DUCHY_ID externalCertificateId = EXTERNAL_DUCHY_CERTIFICATE_ID details = InternalCertificateKt.details { x509Der = DUCHY_CERTIFICATE_DER } } } private val INTERNAL_COMPUTATION_PARTICIPANT_WITH_FAILURE = INTERNAL_COMPUTATION_PARTICIPANT.copy { state = InternalComputationParticipant.State.FAILED failureLogEntry = duchyMeasurementLogEntry { externalDuchyId = DUCHY_ID logEntry = measurementLogEntry { details = MeasurementLogEntryKt.details { logMessage = DUCHY_ERROR_MESSAGE error = MeasurementLogEntryKt.errorDetails { type = MeasurementLogEntry.ErrorDetails.Type.PERMANENT errorTime = timestamp { seconds = 1001 nanos = 2002 } } } } details = DuchyMeasurementLogEntryKt.details { duchyChildReferenceId = MILL_ID stageAttempt = DuchyMeasurementLogEntryKt.stageAttempt { stage = STAGE_ATTEMPT_STAGE stageName = STAGE_ATTEMPT_STAGE_NAME attemptNumber = STAGE_ATTEMPT_ATTEMPT_NUMBER stageStartTime = timestamp { seconds = 100 nanos = 200 } } } } } @RunWith(JUnit4::class) class ComputationParticipantsServiceTest { @get:Rule val duchyIdSetter = DuchyIdSetter(DUCHY_ID) private val duchyIdProvider = { DuchyIdentity(DUCHY_ID) } private val internalComputationParticipantsServiceMock: InternalComputationParticipantsCoroutineService = mockService() @get:Rule val grpcTestServerRule = GrpcTestServerRule { addService(internalComputationParticipantsServiceMock) } private val service = ComputationParticipantsService( InternalComputationParticipantsCoroutineStub(grpcTestServerRule.channel), duchyIdProvider ) @Test fun `SetParticipantRequisitionParams successfully`() = runBlocking { whenever(internalComputationParticipantsServiceMock.setParticipantRequisitionParams(any())) .thenReturn(INTERNAL_COMPUTATION_PARTICIPANT_WITH_PARAMS) val request = SetParticipantRequisitionParamsRequest.newBuilder() .apply { name = SYSTEM_COMPUTATION_PARTICIPANT_NAME requisitionParamsBuilder.apply { duchyCertificate = DUCHY_CERTIFICATE_PUBLIC_API_NAME liquidLegionsV2Builder.apply { elGamalPublicKey = DUCHY_ELGAMAL_KEY elGamalPublicKeySignature = DUCHY_ELGAMAL_KEY_SIGNATURE } } } .build() val response: ComputationParticipant = service.setParticipantRequisitionParams(request) assertThat(response) .isEqualTo( computationParticipant { name = SYSTEM_COMPUTATION_PARTICIPANT_NAME state = ComputationParticipant.State.REQUISITION_PARAMS_SET updateTime = INTERNAL_COMPUTATION_PARTICIPANT.updateTime requisitionParams = requisitionParams { duchyCertificate = DUCHY_CERTIFICATE_PUBLIC_API_NAME duchyCertificateDer = DUCHY_CERTIFICATE_DER liquidLegionsV2 = liquidLegionsV2 { elGamalPublicKey = DUCHY_ELGAMAL_KEY elGamalPublicKeySignature = DUCHY_ELGAMAL_KEY_SIGNATURE } } } ) verifyProtoArgument( internalComputationParticipantsServiceMock, InternalComputationParticipantsCoroutineService::setParticipantRequisitionParams ) .isEqualTo( InternalSetParticipantRequisitionParamsRequest.newBuilder() .apply { externalComputationId = EXTERNAL_COMPUTATION_ID externalDuchyId = DUCHY_ID externalDuchyCertificateId = EXTERNAL_DUCHY_CERTIFICATE_ID liquidLegionsV2 = INTERNAL_COMPUTATION_PARTICIPANT_WITH_PARAMS.details.liquidLegionsV2 } .build() ) } @Test fun `FailComputationParticipant successfully`() = runBlocking { whenever(internalComputationParticipantsServiceMock.failComputationParticipant(any())) .thenReturn(INTERNAL_COMPUTATION_PARTICIPANT_WITH_FAILURE) val failureLogEntry = INTERNAL_COMPUTATION_PARTICIPANT_WITH_FAILURE.failureLogEntry val request = FailComputationParticipantRequest.newBuilder() .apply { name = SYSTEM_COMPUTATION_PARTICIPANT_NAME failureBuilder.apply { participantChildReferenceId = MILL_ID errorMessage = DUCHY_ERROR_MESSAGE errorTimeBuilder.apply { seconds = 1001 nanos = 2002 } stageAttemptBuilder.apply { stage = STAGE_ATTEMPT_STAGE stageName = STAGE_ATTEMPT_STAGE_NAME attemptNumber = STAGE_ATTEMPT_ATTEMPT_NUMBER stageStartTimeBuilder.apply { seconds = 100 nanos = 200 } } } } .build() val response: ComputationParticipant = service.failComputationParticipant(request) assertThat(response.state).isEqualTo(ComputationParticipant.State.FAILED) assertThat(response.failure).isEqualTo(request.failure) verifyProtoArgument( internalComputationParticipantsServiceMock, InternalComputationParticipantsCoroutineService::failComputationParticipant ) .isEqualTo( InternalFailComputationParticipantRequest.newBuilder() .apply { externalComputationId = EXTERNAL_COMPUTATION_ID externalDuchyId = DUCHY_ID errorMessage = DUCHY_ERROR_MESSAGE duchyChildReferenceId = MILL_ID errorDetails = failureLogEntry.logEntry.details.error stageAttempt = failureLogEntry.details.stageAttempt } .build() ) } @Test fun `ConfirmComputationParticipant successfully`() = runBlocking { whenever(internalComputationParticipantsServiceMock.confirmComputationParticipant(any())) .thenReturn( INTERNAL_COMPUTATION_PARTICIPANT_WITH_PARAMS.copy { state = InternalComputationParticipant.State.READY } ) val request = ConfirmComputationParticipantRequest.newBuilder() .apply { name = SYSTEM_COMPUTATION_PARTICIPANT_NAME } .build() val response: ComputationParticipant = service.confirmComputationParticipant(request) assertThat(response.state).isEqualTo(ComputationParticipant.State.READY) verifyProtoArgument( internalComputationParticipantsServiceMock, InternalComputationParticipantsCoroutineService::confirmComputationParticipant ) .isEqualTo( InternalConfirmComputationParticipantRequest.newBuilder() .apply { externalComputationId = EXTERNAL_COMPUTATION_ID externalDuchyId = DUCHY_ID } .build() ) } @Test fun `missing resource name should throw`() { val e = Assert.assertThrows(StatusRuntimeException::class.java) { runBlocking { service.failComputationParticipant(FailComputationParticipantRequest.getDefaultInstance()) } } assertThat(e.status.code).isEqualTo(Status.Code.INVALID_ARGUMENT) assertThat(e.localizedMessage).contains("Resource name unspecified or invalid.") } @Test fun `missing protocol should throw`() { val e = Assert.assertThrows(StatusRuntimeException::class.java) { runBlocking { service.setParticipantRequisitionParams( SetParticipantRequisitionParamsRequest.newBuilder() .apply { name = SYSTEM_COMPUTATION_PARTICIPANT_NAME requisitionParamsBuilder.apply { duchyCertificate = DUCHY_CERTIFICATE_PUBLIC_API_NAME } } .build() ) } } assertThat(e.status.code).isEqualTo(Status.Code.INVALID_ARGUMENT) assertThat(e.localizedMessage).contains("protocol not set in the requisition_params") } }
apache-2.0
832df46ad9b02ef5d5d06437cf137d33
40.313433
168
0.731286
5.442391
false
true
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/editor/folding/LatexCustomFoldingBuilder.kt
1
2403
package nl.hannahsten.texifyidea.editor.folding import com.intellij.lang.ASTNode import com.intellij.lang.folding.FoldingBuilderEx import com.intellij.lang.folding.FoldingDescriptor import com.intellij.openapi.editor.Document import com.intellij.openapi.project.DumbAware import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import nl.hannahsten.texifyidea.psi.LatexMagicComment import nl.hannahsten.texifyidea.util.childrenOfType import nl.hannahsten.texifyidea.util.endOffset /** * Implements custom folding regions. * See https://blog.jetbrains.com/idea/2012/03/custom-code-folding-regions-in-intellij-idea-111/ * * Syntax: * %!<editor-fold desc="MyDescription"> * %!</editor-fold> * * %!region MyDescription * %!endregion * * @author Thomas */ class LatexCustomFoldingBuilder : FoldingBuilderEx(), DumbAware { private val startRegionRegex = """%!\s*(<editor-fold desc="|region ?)(?<description>.*?)(">)?\s*$""".toRegex() private val endRegionRegex = """%!\s*(</editor-fold>|endregion)""".toRegex() override fun isCollapsedByDefault(node: ASTNode) = false override fun getPlaceholderText(node: ASTNode) = "..." override fun buildFoldRegions(root: PsiElement, document: Document, quick: Boolean): Array<FoldingDescriptor> { val descriptors = ArrayList<FoldingDescriptor>() val magicComments = root.childrenOfType(LatexMagicComment::class) val startRegions = magicComments.filter { startRegionRegex.containsMatchIn(it.text) } .sortedBy { it.textOffset }.toMutableList() val endRegions = magicComments.filter { endRegionRegex.containsMatchIn(it.text) } .sortedBy { it.textOffset } // Now we need to match ends with starts for (end in endRegions) { // Match with the closest available start: it does not make sense to match that start with anything else, because ranges can be nested but not partially overlap val start = startRegions.lastOrNull { it.textOffset < end.textOffset } ?: continue val description = startRegionRegex.find(start.text)?.groups?.get("description")?.value?.ifBlank { "..." } ?: "..." startRegions.remove(start) descriptors.add(FoldingDescriptor(start.node, TextRange(start.textOffset, end.endOffset()), null, description)) } return descriptors.toTypedArray() } }
mit
da86068a6c609ce6659b78b0bdfee791
42.690909
172
0.716604
4.409174
false
false
false
false
pokk/mvp-magazine
app/src/main/kotlin/taiwan/no1/app/ui/fragments/TvEpisodeFragment.kt
1
7687
package taiwan.no1.app.ui.fragments import android.graphics.Bitmap import android.os.Bundle import android.support.annotation.LayoutRes import android.support.v4.view.ViewPager import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.View import android.view.ViewStub import android.widget.ImageView import android.widget.TextView import com.bumptech.glide.request.animation.GlideAnimation import com.bumptech.glide.request.target.BitmapImageViewTarget import kotterknife.bindView import taiwan.no1.app.R import taiwan.no1.app.internal.di.annotations.PerFragment import taiwan.no1.app.internal.di.components.FragmentComponent import taiwan.no1.app.mvp.contracts.fragment.TvEpisodeContract import taiwan.no1.app.mvp.models.FilmCastsModel import taiwan.no1.app.mvp.models.FilmVideoModel import taiwan.no1.app.mvp.models.IVisitable import taiwan.no1.app.mvp.models.tv.TvEpisodesModel import taiwan.no1.app.ui.BaseFragment import taiwan.no1.app.ui.adapter.BackdropPagerAdapter import taiwan.no1.app.ui.adapter.CommonRecyclerAdapter import taiwan.no1.app.ui.adapter.itemdecorator.MovieHorizontalItemDecorator import taiwan.no1.app.utilies.ImageLoader.IImageLoader import javax.inject.Inject /** * * @author Jieyi * @since 3/6/17 */ @PerFragment class TvEpisodeFragment : BaseFragment(), TvEpisodeContract.View { //region Static initialization companion object Factory { // The key name of the fragment initialization parameters. private const val ARG_PARAM_TV_ID: String = "param_tv_id" private const val ARG_PARAM_TV_FROM_FRAGMENT: String = "param_from_fragment" private const val ARG_PARAM_TV_EPISODE_INFO: String = "param_tv_episode_info" /** * Use this factory method to create a new instance of this fragment using the provided parameters. * * @return A new instance of [TvEpisodeFragment]. */ fun newInstance(episodeModel: TvEpisodesModel, from: Int): TvEpisodeFragment = TvEpisodeFragment().also { it.arguments = Bundle().also { it.putParcelable(ARG_PARAM_TV_EPISODE_INFO, episodeModel) it.putInt(ARG_PARAM_TV_ID, from) } } } //endregion @Inject lateinit var presenter: TvEpisodeContract.Presenter @Inject lateinit var imageLoader: IImageLoader //region View variables private val tvEpisodeTitle by bindView<TextView>(R.id.tv_episode_title) private val tvAirDate by bindView<TextView>(R.id.tv_air_date) private val tvOverview by bindView<TextView>(R.id.tv_overview) private val vp_drop_poster by bindView<ViewPager>(R.id.vp_drop_poster) private val stubCasts by bindView<ViewStub>(R.id.stub_casts) private val stubCrews by bindView<ViewStub>(R.id.stub_crews) private val stubTrailer by bindView<ViewStub>(R.id.stub_trailer) private val rvCasts by bindView<RecyclerView>(R.id.rv_casts) private val tvCastTitle by bindView<TextView>(R.id.tv_cast_title) private val rvCrews by bindView<RecyclerView>(R.id.rv_crews) private val tvCrewTitle by bindView<TextView>(R.id.tv_crew_title) private val rvTrailer by bindView<RecyclerView>(R.id.rv_trailer) private val tvTrailerTitle by bindView<TextView>(R.id.tv_trailer_title) //endregion // Get the arguments from the bundle here. private val argFromFragment: Int by lazy { this.arguments.getInt(ARG_PARAM_TV_FROM_FRAGMENT) } private val argEpisodeInfo: TvEpisodesModel by lazy { this.arguments.getParcelable<TvEpisodesModel>(ARG_PARAM_TV_EPISODE_INFO) } //region Fragment lifecycle override fun onResume() { super.onResume() this.presenter.resume() } override fun onPause() { super.onPause() this.presenter.pause() } override fun onDestroy() { // After super.onDestroy() is executed, the presenter will be destroy. So the presenter should be // executed before super.onDestroy(). this.presenter.destroy() super.onDestroy() } //endregion //region Initialization's order /** * Inject this fragment and [FragmentComponent]. */ override fun inject() { this.getComponent(FragmentComponent::class.java).inject(TvEpisodeFragment@ this) } /** * Set this fragment xml layout. * * @return [LayoutRes] xml layout. */ @LayoutRes override fun inflateView(): Int = R.layout.fragment_tv_episode_detail /** * Set the presenter initialization in [onCreateView]. */ override fun initPresenter() { this.presenter.init(TvEpisodeFragment@ this) } /** * Initialization of this fragment. Set the listeners or view components' attributions. * * @param savedInstanceState the previous fragment data status after the system calls [onPause]. */ override fun init(savedInstanceState: Bundle?) { this.showLoading() this.presenter.requestTvEpisodeDetail(argEpisodeInfo.tv_id, argEpisodeInfo.season_number, argEpisodeInfo.episode_number) } //endregion override fun showTvEpisodeInfo() { this.tvEpisodeTitle.text = argEpisodeInfo.name this.tvAirDate.text = argEpisodeInfo.air_date this.tvOverview.text = argEpisodeInfo.overview } override fun showTvEpisodeImages(list: List<View>) { this.vp_drop_poster.adapter = BackdropPagerAdapter(list) } override fun showTvEpisodes(episodes: List<TvEpisodesModel>) { } override fun showTvEpisodeCasts(casts: List<FilmCastsModel.CastBean>) { // Inflate the cast section. if (casts.isNotEmpty()) this.showViewStub(this.stubCasts, { this.showCardItems(this.rvCasts, casts) this.tvCastTitle.setTextColor(this.context.resources.getColor(R.color.recyclerview_dark_bg_title)) }) } override fun showTvEpisodeCrews(crews: List<FilmCastsModel.CrewBean>) { // Inflate the crew section. if (crews.isNotEmpty()) this.showViewStub(this.stubCrews, { this.showCardItems(this.rvCrews, crews) this.tvCrewTitle.setTextColor(this.context.resources.getColor(R.color.recyclerview_dark_bg_title)) }) } override fun showTvEpisodeTrailers(trailers: List<FilmVideoModel>) { // Inflate the trailer movieList section. if (trailers.isNotEmpty()) this.showViewStub(this.stubTrailer, { this.showCardItems(this.rvTrailer, trailers) this.tvTrailerTitle.setTextColor(this.context.resources.getColor(R.color.recyclerview_dark_bg_title)) }) } override fun showTvEpisodeBackDrop(uri: String, imageview: ImageView) { this.imageLoader.display(uri, listener = object : BitmapImageViewTarget(imageview) { override fun onResourceReady(resource: Bitmap, glideAnimation: GlideAnimation<in Bitmap>) { [email protected](imageview, [email protected]) super.onResourceReady(resource, glideAnimation) } }, isFitCenter = false) } private fun <T : IVisitable> showCardItems(recyclerView: RecyclerView, list: List<T>) { recyclerView.apply { this.layoutManager = LinearLayoutManager(this.context, LinearLayoutManager.HORIZONTAL, false) this.adapter = CommonRecyclerAdapter(list, argFromFragment) this.addItemDecoration(MovieHorizontalItemDecorator(30)) } } }
apache-2.0
0f28f2b7f440ef28898d0c9623077153
38.020305
118
0.700273
4.318539
false
false
false
false
sephiroth74/AndroidUIGestureRecognizer
app/src/main/java/it/sephiroth/android/library/uigestures/demo/MainActivity.kt
1
5465
package it.sephiroth.android.library.uigestures.demo import android.os.Bundle import android.os.Handler import android.view.View import android.widget.AdapterView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import it.sephiroth.android.library.uigestures.* import it.sephiroth.android.library.uigestures.demo.fragments.* import kotlinx.android.synthetic.main.activity_tap.* import timber.log.Timber import java.text.SimpleDateFormat import java.util.* import kotlin.reflect.full.primaryConstructor open class MainActivity : AppCompatActivity() { private var currentRecognizerClassName: String = "" private val handler = Handler() private val delegate = UIGestureRecognizerDelegate() private val dateFormat = SimpleDateFormat("HH:mm:ss.SSS", Locale.US) private lateinit var recognizer: UIGestureRecognizer private val clearTextRunnable: Runnable = Runnable { textState.text = "Test me!" } init { UIGestureRecognizer.logEnabled = true } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_tap) setSupportActionBar(toolbar) setupTouchListener() setupSpinner() } private fun setupTouchListener() { testView.setOnTouchListener { v, event -> v.onTouchEvent(event) delegate.onTouchEvent(v, event) } } @Suppress("RECEIVER_NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS") private fun setupContent(simpleClassName: String) { Timber.i("setupContent: $simpleClassName") val packageName = UIGestureRecognizer::class.java.`package`.name Timber.v("package: $packageName") val kClass = Class.forName("${packageName}.$simpleClassName").kotlin Timber.v("kClass: ${kClass.simpleName}") val newRecognizer = kClass.primaryConstructor?.call(this) as UIGestureRecognizer? newRecognizer?.let { rec -> var fragment: Fragment? = null when (kClass) { UITapGestureRecognizer::class -> fragment = UITapGestureRecognizerFragment.newInstance(rec) UIRotateGestureRecognizer::class -> fragment = UIRotateGestureRecognizerFragment.newInstance(rec) UIPinchGestureRecognizer::class -> fragment = UIPinchGestureRecognizerFragment.newInstance(rec) UIScreenEdgePanGestureRecognizer::class -> fragment = UIScreenEdgePanGestureRecognizerFragment.newInstance(rec) UIPanGestureRecognizer::class -> fragment = UIPanGestureRecognizerFragment.newInstance(rec) UISwipeGestureRecognizer::class -> fragment = UISwipeGestureRecognizerFragment.newInstance(rec) UILongPressGestureRecognizer::class -> fragment = UILongPressGestureRecognizerFragment.newInstance(rec) } fragment?.let { frag -> title = kClass.simpleName delegate.clear() recognizer = rec supportFragmentManager .beginTransaction() .replace(R.id.fragmentContainer, frag, simpleClassName) .commit() setupRecognizer(recognizer) currentRecognizerClassName = simpleClassName } ?: kotlin.run { } } ?: kotlin.run { Toast.makeText(this, "Unable to find ${kClass.simpleName}", Toast.LENGTH_SHORT).show() } } private fun setupSpinner() { recognizerSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>) {} override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { val selected = parent.selectedItem.toString() setupContent(selected) } } } private fun setupRecognizer(recognizer: UIGestureRecognizer) { recognizer.actionListener = { rec -> Timber.d("actionListener: ${rec.currentLocationX}, ${rec.currentLocationY}") testView.drawableHotspotChanged(rec.currentLocationX, rec.currentLocationY) testView.isPressed = true testView.performClick() testView.isPressed = false val dateTime = dateFormat.format(recognizer.lastEvent!!.eventTime) textState.append("[$dateTime] ${rec.javaClass.simpleName}: ${rec.state} \n") textState.append("[$dateTime] location: ${rec.currentLocationX.toInt()}, ${rec.currentLocationY.toInt()}\n") supportFragmentManager.findFragmentByTag(currentRecognizerClassName)?.let { frag -> val status = (frag as IRecognizerFragment<*>).getRecognizerStatus() status?.let { textState.append("[$dateTime] $it\n") } } textState.append("\n") handler.removeCallbacks(clearTextRunnable) handler.postDelayed(clearTextRunnable, 4000) } recognizer.stateListener = { it: UIGestureRecognizer, oldState: UIGestureRecognizer.State?, newState: UIGestureRecognizer.State? -> Timber.v("state changed: $oldState --> $newState") } delegate.addGestureRecognizer(recognizer) } }
mit
735e6ccf751262367f9b8646ebe751e1
36.431507
127
0.654712
5.454092
false
false
false
false
tasks/tasks
app/src/main/java/org/tasks/jobs/NotificationQueue.kt
1
2468
package org.tasks.jobs import com.google.common.collect.Ordering import com.google.common.collect.TreeMultimap import com.google.common.primitives.Ints import org.tasks.preferences.Preferences import org.tasks.time.DateTime import javax.inject.Inject import javax.inject.Singleton @Singleton class NotificationQueue @Inject constructor( private val preferences: Preferences, private val workManager: WorkManager ) { private val jobs = TreeMultimap.create<Long, AlarmEntry>(Ordering.natural()) { l, r -> Ints.compare(l.hashCode(), r.hashCode()) } @Synchronized fun add(entry: AlarmEntry) = add(listOf(entry)) @Synchronized fun add(entries: Iterable<AlarmEntry>) { val originalFirstTime = firstTime() entries.forEach { jobs.put(it.time, it) } if (originalFirstTime != firstTime()) { scheduleNext(true) } } @Synchronized fun clear() { jobs.clear() workManager.cancelNotifications() } fun cancelForTask(taskId: Long) { val firstTime = firstTime() jobs.values().filter { it.taskId == taskId }.forEach { remove(listOf(it)) } if (firstTime != firstTime()) { scheduleNext(true) } } @get:Synchronized val overdueJobs: List<AlarmEntry> get() = jobs.keySet() .headSet(DateTime().startOfMinute().plusMinutes(1).millis) .flatMap { jobs[it] } @Synchronized fun scheduleNext() = scheduleNext(false) private fun scheduleNext(cancelCurrent: Boolean) { if (jobs.isEmpty) { if (cancelCurrent) { workManager.cancelNotifications() } } else { workManager.scheduleNotification(nextScheduledTime()) } } private fun firstTime() = if (jobs.isEmpty) 0L else jobs.asMap().firstKey() fun nextScheduledTime(): Long { val next = firstTime() return if (next > 0) preferences.adjustForQuietHours(next) else 0 } fun size() = jobs.size() fun getJobs() = jobs.values().toList() fun isEmpty() = jobs.isEmpty @Synchronized fun remove(entries: List<AlarmEntry>): Boolean { var success = true for (entry in entries) { success = success and (!jobs.containsEntry(entry.time, entry) || jobs.remove( entry.time, entry )) } return success } }
gpl-3.0
b48fe8471d2bb12f6a3212ddbb35d4e0
26.433333
89
0.613857
4.422939
false
false
false
false
cwoolner/flex-poker
src/main/kotlin/com/flexpoker/table/query/handlers/PlayerCheckedEventHandler.kt
1
2132
package com.flexpoker.table.query.handlers import com.flexpoker.chat.service.ChatService import com.flexpoker.framework.event.EventHandler import com.flexpoker.framework.pushnotifier.PushNotificationPublisher import com.flexpoker.login.repository.LoginRepository import com.flexpoker.pushnotifications.TableUpdatedPushNotification import com.flexpoker.table.command.events.PlayerCheckedEvent import com.flexpoker.table.query.repository.TableRepository import org.springframework.stereotype.Component import javax.inject.Inject @Component class PlayerCheckedEventHandler @Inject constructor( private val loginRepository: LoginRepository, private val tableRepository: TableRepository, private val pushNotificationPublisher: PushNotificationPublisher, private val chatService: ChatService ) : EventHandler<PlayerCheckedEvent> { override fun handle(event: PlayerCheckedEvent) { handleUpdatingTable(event) handlePushNotifications(event) handleChat(event) } private fun handleUpdatingTable(event: PlayerCheckedEvent) { val tableDTO = tableRepository.fetchById(event.aggregateId) val username = loginRepository.fetchUsernameByAggregateId(event.playerId) val updatedSeats = tableDTO.seats!! .map { if (it.name == username) { it.copy(raiseTo = 0, callAmount = 0, isActionOn = false) } else { it } } val updatedTable = tableDTO.copy(version = event.version, seats = updatedSeats) tableRepository.save(updatedTable) } private fun handlePushNotifications(event: PlayerCheckedEvent) { val pushNotification = TableUpdatedPushNotification(event.gameId, event.aggregateId) pushNotificationPublisher.publish(pushNotification) } private fun handleChat(event: PlayerCheckedEvent) { val username = loginRepository.fetchUsernameByAggregateId(event.playerId) val message = "$username checks" chatService.saveAndPushSystemTableChatMessage(event.gameId, event.aggregateId, message) } }
gpl-2.0
d78c932d62ded13f7c63013c4f34dd0c
39.245283
95
0.739681
5.48072
false
false
false
false
wiltonlazary/kotlin-native
Interop/StubGenerator/src/main/kotlin/org/jetbrains/kotlin/native/interop/gen/StubIrElementBuilders.kt
1
34563
/* * Copyright 2010-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.kotlin.native.interop.gen import org.jetbrains.kotlin.native.interop.gen.jvm.GenerationMode import org.jetbrains.kotlin.native.interop.gen.jvm.KotlinPlatform import org.jetbrains.kotlin.native.interop.indexer.* internal class MacroConstantStubBuilder( override val context: StubsBuildingContext, private val constant: ConstantDef ) : StubElementBuilder { override fun build(): List<StubIrElement> { val kotlinName = constant.name val origin = StubOrigin.Constant(constant) val declaration = when (constant) { is IntegerConstantDef -> { val literal = context.tryCreateIntegralStub(constant.type, constant.value) ?: return emptyList() val kotlinType = context.mirror(constant.type).argType.toStubIrType() when (context.platform) { KotlinPlatform.NATIVE -> PropertyStub(kotlinName, kotlinType, PropertyStub.Kind.Constant(literal), origin = origin) // No reason to make it const val with backing field on Kotlin/JVM yet: KotlinPlatform.JVM -> { val getter = PropertyAccessor.Getter.SimpleGetter(constant = literal) PropertyStub(kotlinName, kotlinType, PropertyStub.Kind.Val(getter), origin = origin) } } } is FloatingConstantDef -> { val literal = context.tryCreateDoubleStub(constant.type, constant.value) ?: return emptyList() val kind = when (context.generationMode) { GenerationMode.SOURCE_CODE -> { PropertyStub.Kind.Val(PropertyAccessor.Getter.SimpleGetter(constant = literal)) } GenerationMode.METADATA -> { PropertyStub.Kind.Constant(literal) } } val kotlinType = context.mirror(constant.type).argType.toStubIrType() PropertyStub(kotlinName, kotlinType, kind, origin = origin) } is StringConstantDef -> { val literal = StringConstantStub(constant.value) val kind = when (context.generationMode) { GenerationMode.SOURCE_CODE -> { PropertyStub.Kind.Val(PropertyAccessor.Getter.SimpleGetter(constant = literal)) } GenerationMode.METADATA -> { PropertyStub.Kind.Constant(literal) } } PropertyStub(kotlinName, KotlinTypes.string.toStubIrType(), kind, origin = origin) } else -> return emptyList() } return listOf(declaration) } } internal class StructStubBuilder( override val context: StubsBuildingContext, private val decl: StructDecl ) : StubElementBuilder { override fun build(): List<StubIrElement> { val platform = context.platform val def = decl.def ?: return generateForwardStruct(decl) val structAnnotation: AnnotationStub? = if (platform == KotlinPlatform.JVM) { if (def.kind == StructDef.Kind.STRUCT && def.fieldsHaveDefaultAlignment()) { AnnotationStub.CNaturalStruct(def.members) } else { null } } else { tryRenderStructOrUnion(def)?.let { AnnotationStub.CStruct(it) } } val classifier = context.getKotlinClassForPointed(decl) val fields: List<PropertyStub?> = def.fields.map { field -> try { assert(field.name.isNotEmpty()) assert(field.offset % 8 == 0L) val offset = field.offset / 8 val fieldRefType = context.mirror(field.type) val unwrappedFieldType = field.type.unwrapTypedefs() val origin = StubOrigin.StructMember(field) val fieldName = mangleSimple(field.name) if (unwrappedFieldType is ArrayType) { val type = (fieldRefType as TypeMirror.ByValue).valueType val annotations = if (platform == KotlinPlatform.JVM) { val length = getArrayLength(unwrappedFieldType) // TODO: @CLength should probably be used on types instead of properties. listOf(AnnotationStub.CLength(length)) } else { emptyList() } val getter = when (context.generationMode) { GenerationMode.SOURCE_CODE -> PropertyAccessor.Getter.ArrayMemberAt(offset) GenerationMode.METADATA -> PropertyAccessor.Getter.ExternalGetter(listOf(AnnotationStub.CStruct.ArrayMemberAt(offset))) } val kind = PropertyStub.Kind.Val(getter) // TODO: Should receiver be added? PropertyStub(fieldName, type.toStubIrType(), kind, annotations = annotations, origin = origin) } else { val pointedType = fieldRefType.pointedType.toStubIrType() val pointedTypeArgument = TypeArgumentStub(pointedType) if (fieldRefType is TypeMirror.ByValue) { val getter: PropertyAccessor.Getter val setter: PropertyAccessor.Setter when (context.generationMode) { GenerationMode.SOURCE_CODE -> { getter = PropertyAccessor.Getter.MemberAt(offset, typeArguments = listOf(pointedTypeArgument), hasValueAccessor = true) setter = PropertyAccessor.Setter.MemberAt(offset, typeArguments = listOf(pointedTypeArgument)) } GenerationMode.METADATA -> { getter = PropertyAccessor.Getter.ExternalGetter(listOf(AnnotationStub.CStruct.MemberAt(offset))) setter = PropertyAccessor.Setter.ExternalSetter(listOf(AnnotationStub.CStruct.MemberAt(offset))) } } val kind = PropertyStub.Kind.Var(getter, setter) PropertyStub(fieldName, fieldRefType.argType.toStubIrType(), kind, origin = origin) } else { val accessor = when (context.generationMode) { GenerationMode.SOURCE_CODE -> PropertyAccessor.Getter.MemberAt(offset, hasValueAccessor = false) GenerationMode.METADATA -> PropertyAccessor.Getter.ExternalGetter(listOf(AnnotationStub.CStruct.MemberAt(offset))) } val kind = PropertyStub.Kind.Val(accessor) PropertyStub(fieldName, pointedType, kind, origin = origin) } } } catch (e: Throwable) { null } } val bitFields: List<PropertyStub> = def.bitFields.map { field -> val typeMirror = context.mirror(field.type) val typeInfo = typeMirror.info val kotlinType = typeMirror.argType val signed = field.type.isIntegerTypeSigned() val fieldName = mangleSimple(field.name) val kind = when (context.generationMode) { GenerationMode.SOURCE_CODE -> { val readBits = PropertyAccessor.Getter.ReadBits(field.offset, field.size, signed) val writeBits = PropertyAccessor.Setter.WriteBits(field.offset, field.size) context.bridgeComponentsBuilder.getterToBridgeInfo[readBits] = BridgeGenerationInfo("", typeInfo) context.bridgeComponentsBuilder.setterToBridgeInfo[writeBits] = BridgeGenerationInfo("", typeInfo) PropertyStub.Kind.Var(readBits, writeBits) } GenerationMode.METADATA -> { val readBits = PropertyAccessor.Getter.ExternalGetter(listOf(AnnotationStub.CStruct.BitField(field.offset, field.size))) val writeBits = PropertyAccessor.Setter.ExternalSetter(listOf(AnnotationStub.CStruct.BitField(field.offset, field.size))) PropertyStub.Kind.Var(readBits, writeBits) } } PropertyStub(fieldName, kotlinType.toStubIrType(), kind, origin = StubOrigin.StructMember(field)) } val superClass = context.platform.getRuntimeType("CStructVar") require(superClass is ClassifierStubType) val rawPtrConstructorParam = FunctionParameterStub("rawPtr", context.platform.getRuntimeType("NativePtr")) val origin = StubOrigin.Struct(decl) val primaryConstructor = ConstructorStub( parameters = listOf(rawPtrConstructorParam), isPrimary = true, annotations = emptyList(), origin = origin ) val superClassInit = SuperClassInit(superClass, listOf(GetConstructorParameter(rawPtrConstructorParam))) val companionSuper = superClass.nested("Type") val typeSize = listOf(IntegralConstantStub(def.size, 4, true), IntegralConstantStub(def.align.toLong(), 4, true)) val companionSuperInit = SuperClassInit(companionSuper, typeSize) val companionClassifier = classifier.nested("Companion") val annotation = AnnotationStub.CStruct.VarType(def.size, def.align).takeIf { context.generationMode == GenerationMode.METADATA } val companion = ClassStub.Companion(companionClassifier, superClassInit = companionSuperInit, annotations = listOfNotNull(annotation)) return listOf(ClassStub.Simple( classifier, origin = origin, properties = fields.filterNotNull() + if (platform == KotlinPlatform.NATIVE) bitFields else emptyList(), constructors = listOf(primaryConstructor), methods = emptyList(), modality = ClassStubModality.NONE, annotations = listOfNotNull(structAnnotation), superClassInit = superClassInit, companion = companion )) } private fun getArrayLength(type: ArrayType): Long { val unwrappedElementType = type.elemType.unwrapTypedefs() val elementLength = if (unwrappedElementType is ArrayType) { getArrayLength(unwrappedElementType) } else { 1L } val elementCount = when (type) { is ConstArrayType -> type.length is IncompleteArrayType -> 0L else -> TODO(type.toString()) } return elementLength * elementCount } private tailrec fun Type.isIntegerTypeSigned(): Boolean = when (this) { is IntegerType -> this.isSigned is BoolType -> false is EnumType -> this.def.baseType.isIntegerTypeSigned() is Typedef -> this.def.aliased.isIntegerTypeSigned() else -> error(this) } /** * Produces to [out] the definition of Kotlin class representing the reference to given forward (incomplete) struct. */ private fun generateForwardStruct(s: StructDecl): List<StubIrElement> = when (context.platform) { KotlinPlatform.JVM -> { val classifier = context.getKotlinClassForPointed(s) val superClass = context.platform.getRuntimeType("COpaque") val rawPtrConstructorParam = FunctionParameterStub("rawPtr", context.platform.getRuntimeType("NativePtr")) val superClassInit = SuperClassInit(superClass, listOf(GetConstructorParameter(rawPtrConstructorParam))) val origin = StubOrigin.Struct(s) val primaryConstructor = ConstructorStub(listOf(rawPtrConstructorParam), emptyList(), isPrimary = true, origin = origin) listOf(ClassStub.Simple( classifier, ClassStubModality.NONE, constructors = listOf(primaryConstructor), superClassInit = superClassInit, origin = origin)) } KotlinPlatform.NATIVE -> emptyList() } } internal class EnumStubBuilder( override val context: StubsBuildingContext, private val enumDef: EnumDef ) : StubElementBuilder { private val classifier = (context.mirror(EnumType(enumDef)) as TypeMirror.ByValue).valueType.classifier private val baseTypeMirror = context.mirror(enumDef.baseType) private val baseType = baseTypeMirror.argType.toStubIrType() override fun build(): List<StubIrElement> { if (!context.isStrictEnum(enumDef)) { return generateEnumAsConstants(enumDef) } val constructorParameter = FunctionParameterStub("value", baseType) val valueProperty = PropertyStub( name = "value", type = baseType, kind = PropertyStub.Kind.Val(PropertyAccessor.Getter.GetConstructorParameter(constructorParameter)), modality = MemberStubModality.OPEN, origin = StubOrigin.Synthetic.EnumValueField(enumDef), isOverride = true) val canonicalsByValue = enumDef.constants .groupingBy { it.value } .reduce { _, accumulator, element -> if (element.isMoreCanonicalThan(accumulator)) { element } else { accumulator } } val (canonicalConstants, aliasConstants) = enumDef.constants.partition { canonicalsByValue[it.value] == it } val canonicalEntriesWithAliases = canonicalConstants .sortedBy { it.value } // TODO: Is it stable enough? .mapIndexed { index, constant -> val literal = context.tryCreateIntegralStub(enumDef.baseType, constant.value) ?: error("Cannot create enum value ${constant.value} of type ${enumDef.baseType}") val entry = EnumEntryStub(mangleSimple(constant.name), literal, StubOrigin.EnumEntry(constant), index) val aliases = aliasConstants .filter { it.value == constant.value } .map { constructAliasProperty(it, entry) } entry to aliases } val origin = StubOrigin.Enum(enumDef) val primaryConstructor = ConstructorStub( parameters = listOf(constructorParameter), annotations = emptyList(), isPrimary = true, origin = origin, visibility = VisibilityModifier.PRIVATE ) val byValueFunction = FunctionStub( name = "byValue", returnType = ClassifierStubType(classifier), parameters = listOf(FunctionParameterStub("value", baseType)), origin = StubOrigin.Synthetic.EnumByValue(enumDef), receiver = null, modality = MemberStubModality.FINAL, annotations = emptyList() ) val companion = ClassStub.Companion( classifier = classifier.nested("Companion"), properties = canonicalEntriesWithAliases.flatMap { it.second }, methods = listOf(byValueFunction) ) val enumVarClass = constructEnumVarClass().takeIf { context.generationMode == GenerationMode.METADATA } val kotlinEnumType = ClassifierStubType(Classifier.topLevel("kotlin", "Enum"), listOf(TypeArgumentStub(ClassifierStubType(classifier)))) val enum = ClassStub.Enum( classifier = classifier, superClassInit = SuperClassInit(kotlinEnumType), entries = canonicalEntriesWithAliases.map { it.first }, companion = companion, constructors = listOf(primaryConstructor), properties = listOf(valueProperty), origin = origin, interfaces = listOf(context.platform.getRuntimeType("CEnum")), childrenClasses = listOfNotNull(enumVarClass) ) context.bridgeComponentsBuilder.enumToTypeMirror[enum] = baseTypeMirror return listOf(enum) } private fun constructAliasProperty(enumConstant: EnumConstant, entry: EnumEntryStub): PropertyStub { val aliasAnnotation = AnnotationStub.CEnumEntryAlias(entry.name) .takeIf { context.generationMode == GenerationMode.METADATA } return PropertyStub( enumConstant.name, ClassifierStubType(classifier), kind = PropertyStub.Kind.Val(PropertyAccessor.Getter.GetEnumEntry(entry)), origin = StubOrigin.EnumEntry(enumConstant), annotations = listOfNotNull(aliasAnnotation) ) } private fun constructEnumVarClass(): ClassStub.Simple { val enumVarClassifier = classifier.nested("Var") val rawPtrConstructorParam = FunctionParameterStub("rawPtr", context.platform.getRuntimeType("NativePtr")) val superClass = context.platform.getRuntimeType("CEnumVar") require(superClass is ClassifierStubType) val primaryConstructor = ConstructorStub( parameters = listOf(rawPtrConstructorParam), isPrimary = true, annotations = emptyList(), origin = StubOrigin.Synthetic.DefaultConstructor ) val superClassInit = SuperClassInit(superClass, listOf(GetConstructorParameter(rawPtrConstructorParam))) val baseIntegerTypeSize = when (val unwrappedType = enumDef.baseType.unwrapTypedefs()) { is IntegerType -> unwrappedType.size.toLong() CharType -> 1L else -> error("Incorrect base type for enum ${classifier.fqName}") } val typeSize = IntegralConstantStub(baseIntegerTypeSize, 4, true) val companionSuper = (context.platform.getRuntimeType("CPrimitiveVar") as ClassifierStubType).nested("Type") val varSizeAnnotation = AnnotationStub.CEnumVarTypeSize(baseIntegerTypeSize.toInt()) .takeIf { context.generationMode == GenerationMode.METADATA } val companion = ClassStub.Companion( classifier = enumVarClassifier.nested("Companion"), superClassInit = SuperClassInit(companionSuper, listOf(typeSize)), annotations = listOfNotNull(varSizeAnnotation) ) val valueProperty = PropertyStub( name = "value", type = ClassifierStubType(classifier), kind = PropertyStub.Kind.Var( PropertyAccessor.Getter.ExternalGetter(), PropertyAccessor.Setter.ExternalSetter() ), origin = StubOrigin.Synthetic.EnumVarValueField(enumDef) ) return ClassStub.Simple( classifier = enumVarClassifier, constructors = listOf(primaryConstructor), superClassInit = superClassInit, companion = companion, modality = ClassStubModality.NONE, origin = StubOrigin.VarOf(StubOrigin.Enum(enumDef)), properties = listOf(valueProperty) ) } private fun EnumConstant.isMoreCanonicalThan(other: EnumConstant): Boolean = with(other.name.toLowerCase()) { contains("min") || contains("max") || contains("first") || contains("last") || contains("begin") || contains("end") } /** * Produces to [out] the Kotlin definitions for given enum which shouldn't be represented as Kotlin enum. */ private fun generateEnumAsConstants(enumDef: EnumDef): List<StubIrElement> { // TODO: if this enum defines e.g. a type of struct field, then it should be generated inside the struct class // to prevent name clashing val entries = mutableListOf<PropertyStub>() val typealiases = mutableListOf<TypealiasStub>() val constants = enumDef.constants.filter { // Macro "overrides" the original enum constant. it.name !in context.macroConstantsByName } val kotlinType: KotlinType val baseKotlinType = context.mirror(enumDef.baseType).argType val meta = if (enumDef.isAnonymous) { kotlinType = baseKotlinType StubContainerMeta(textAtStart = if (constants.isNotEmpty()) "// ${enumDef.spelling}:" else "") } else { val typeMirror = context.mirror(EnumType(enumDef)) if (typeMirror !is TypeMirror.ByValue) { error("unexpected enum type mirror: $typeMirror") } val varTypeName = typeMirror.info.constructPointedType(typeMirror.valueType) val varTypeClassifier = typeMirror.pointedType.classifier val valueTypeClassifier = typeMirror.valueType.classifier val origin = StubOrigin.Enum(enumDef) typealiases += TypealiasStub(varTypeClassifier, varTypeName.toStubIrType(), StubOrigin.VarOf(origin)) typealiases += TypealiasStub(valueTypeClassifier, baseKotlinType.toStubIrType(), origin) kotlinType = typeMirror.valueType StubContainerMeta() } for (constant in constants) { val literal = context.tryCreateIntegralStub(enumDef.baseType, constant.value) ?: continue val kind = when (context.generationMode) { GenerationMode.SOURCE_CODE -> { val getter = PropertyAccessor.Getter.SimpleGetter(constant = literal) PropertyStub.Kind.Val(getter) } GenerationMode.METADATA -> { PropertyStub.Kind.Constant(literal) } } entries += PropertyStub( constant.name, kotlinType.toStubIrType(), kind, MemberStubModality.FINAL, null, origin = StubOrigin.EnumEntry(constant) ) } val container = SimpleStubContainer( meta, properties = entries.toList(), typealiases = typealiases.toList() ) return listOf(container) } } internal class FunctionStubBuilder( override val context: StubsBuildingContext, private val func: FunctionDecl, private val skipOverloads: Boolean = false ) : StubElementBuilder { override fun build(): List<StubIrElement> { val platform = context.platform val parameters = mutableListOf<FunctionParameterStub>() func.parameters.forEachIndexed { index, parameter -> val parameterName = parameter.name.let { if (it == null || it.isEmpty()) { "arg$index" } else { it } } val representAsValuesRef = representCFunctionParameterAsValuesRef(parameter.type) parameters += when { representCFunctionParameterAsString(func, parameter.type) -> { val annotations = when (platform) { KotlinPlatform.JVM -> emptyList() KotlinPlatform.NATIVE -> listOf(AnnotationStub.CCall.CString) } val type = KotlinTypes.string.makeNullable().toStubIrType() val functionParameterStub = FunctionParameterStub(parameterName, type, annotations) context.bridgeComponentsBuilder.cStringParameters += functionParameterStub functionParameterStub } representCFunctionParameterAsWString(func, parameter.type) -> { val annotations = when (platform) { KotlinPlatform.JVM -> emptyList() KotlinPlatform.NATIVE -> listOf(AnnotationStub.CCall.WCString) } val type = KotlinTypes.string.makeNullable().toStubIrType() val functionParameterStub = FunctionParameterStub(parameterName, type, annotations) context.bridgeComponentsBuilder.wCStringParameters += functionParameterStub functionParameterStub } representAsValuesRef != null -> { FunctionParameterStub(parameterName, representAsValuesRef.toStubIrType()) } else -> { val mirror = context.mirror(parameter.type) val type = mirror.argType.toStubIrType() FunctionParameterStub(parameterName, type) } } } val returnType = if (func.returnsVoid()) { KotlinTypes.unit } else { context.mirror(func.returnType).argType }.toStubIrType() if (skipOverloads && context.isOverloading(func)) return emptyList() val annotations: List<AnnotationStub> val mustBeExternal: Boolean if (platform == KotlinPlatform.JVM) { annotations = emptyList() mustBeExternal = false } else { if (func.isVararg) { val type = KotlinTypes.any.makeNullable().toStubIrType() parameters += FunctionParameterStub("variadicArguments", type, isVararg = true) } annotations = listOf(AnnotationStub.CCall.Symbol("${context.generateNextUniqueId("knifunptr_")}_${func.name}")) mustBeExternal = true } val functionStub = FunctionStub( func.name, returnType, parameters.toList(), StubOrigin.Function(func), annotations, mustBeExternal, null, MemberStubModality.FINAL ) return listOf(functionStub) } private fun FunctionDecl.returnsVoid(): Boolean = this.returnType.unwrapTypedefs() is VoidType private fun representCFunctionParameterAsValuesRef(type: Type): KotlinType? { val pointeeType = when (type) { is PointerType -> type.pointeeType is ArrayType -> type.elemType else -> return null } val unwrappedPointeeType = pointeeType.unwrapTypedefs() if (unwrappedPointeeType is VoidType) { // Represent `void*` as `CValuesRef<*>?`: return KotlinTypes.cValuesRef.typeWith(StarProjection).makeNullable() } if (unwrappedPointeeType is FunctionType) { // Don't represent function pointer as `CValuesRef<T>?` currently: return null } if (unwrappedPointeeType is ArrayType) { return representCFunctionParameterAsValuesRef(pointeeType) } return KotlinTypes.cValuesRef.typeWith(context.mirror(pointeeType).pointedType).makeNullable() } private val platformWStringTypes = setOf("LPCWSTR") private val noStringConversion: Set<String> get() = context.configuration.noStringConversion private fun Type.isAliasOf(names: Set<String>): Boolean { var type = this while (type is Typedef) { if (names.contains(type.def.name)) return true type = type.def.aliased } return false } private fun representCFunctionParameterAsString(function: FunctionDecl, type: Type): Boolean { val unwrappedType = type.unwrapTypedefs() return unwrappedType is PointerType && unwrappedType.pointeeIsConst && unwrappedType.pointeeType.unwrapTypedefs() == CharType && !noStringConversion.contains(function.name) } // We take this approach as generic 'const short*' shall not be used as String. private fun representCFunctionParameterAsWString(function: FunctionDecl, type: Type) = type.isAliasOf(platformWStringTypes) && !noStringConversion.contains(function.name) } internal class GlobalStubBuilder( override val context: StubsBuildingContext, private val global: GlobalDecl ) : StubElementBuilder { override fun build(): List<StubIrElement> { val mirror = context.mirror(global.type) val unwrappedType = global.type.unwrapTypedefs() val origin = StubOrigin.Global(global) val kotlinType: KotlinType val kind: PropertyStub.Kind if (unwrappedType is ArrayType) { kotlinType = (mirror as TypeMirror.ByValue).valueType val getter = when (context.platform) { KotlinPlatform.JVM -> { PropertyAccessor.Getter.SimpleGetter().also { val extra = BridgeGenerationInfo(global.name, mirror.info) context.bridgeComponentsBuilder.arrayGetterBridgeInfo[it] = extra } } KotlinPlatform.NATIVE -> { val cCallAnnotation = AnnotationStub.CCall.Symbol("${context.generateNextUniqueId("knifunptr_")}_${global.name}_getter") PropertyAccessor.Getter.ExternalGetter(listOf(cCallAnnotation)).also { context.wrapperComponentsBuilder.getterToWrapperInfo[it] = WrapperGenerationInfo(global) } } } kind = PropertyStub.Kind.Val(getter) } else { when (mirror) { is TypeMirror.ByValue -> { kotlinType = mirror.argType val getter = when (context.platform) { KotlinPlatform.JVM -> { PropertyAccessor.Getter.SimpleGetter().also { val getterExtra = BridgeGenerationInfo(global.name, mirror.info) context.bridgeComponentsBuilder.getterToBridgeInfo[it] = getterExtra } } KotlinPlatform.NATIVE -> { val cCallAnnotation = AnnotationStub.CCall.Symbol("${context.generateNextUniqueId("knifunptr_")}_${global.name}_getter") PropertyAccessor.Getter.ExternalGetter(listOf(cCallAnnotation)).also { context.wrapperComponentsBuilder.getterToWrapperInfo[it] = WrapperGenerationInfo(global) } } } kind = if (global.isConst) { PropertyStub.Kind.Val(getter) } else { val setter = when (context.platform) { KotlinPlatform.JVM -> { PropertyAccessor.Setter.SimpleSetter().also { val setterExtra = BridgeGenerationInfo(global.name, mirror.info) context.bridgeComponentsBuilder.setterToBridgeInfo[it] = setterExtra } } KotlinPlatform.NATIVE -> { val cCallAnnotation = AnnotationStub.CCall.Symbol("${context.generateNextUniqueId("knifunptr_")}_${global.name}_setter") PropertyAccessor.Setter.ExternalSetter(listOf(cCallAnnotation)).also { context.wrapperComponentsBuilder.setterToWrapperInfo[it] = WrapperGenerationInfo(global) } } } PropertyStub.Kind.Var(getter, setter) } } is TypeMirror.ByRef -> { kotlinType = mirror.pointedType val getter = when (context.generationMode) { GenerationMode.SOURCE_CODE -> { PropertyAccessor.Getter.InterpretPointed(global.name, kotlinType.toStubIrType()) } GenerationMode.METADATA -> { val cCallAnnotation = AnnotationStub.CCall.Symbol("${context.generateNextUniqueId("knifunptr_")}_${global.name}_getter") PropertyAccessor.Getter.ExternalGetter(listOf(cCallAnnotation)).also { context.wrapperComponentsBuilder.getterToWrapperInfo[it] = WrapperGenerationInfo(global, passViaPointer = true) } } } kind = PropertyStub.Kind.Val(getter) } } } return listOf(PropertyStub(global.name, kotlinType.toStubIrType(), kind, origin = origin)) } } internal class TypedefStubBuilder( override val context: StubsBuildingContext, private val typedefDef: TypedefDef ) : StubElementBuilder { override fun build(): List<StubIrElement> { val mirror = context.mirror(Typedef(typedefDef)) val baseMirror = context.mirror(typedefDef.aliased) val varType = mirror.pointedType.classifier val origin = StubOrigin.TypeDef(typedefDef) return when (baseMirror) { is TypeMirror.ByValue -> { val valueType = (mirror as TypeMirror.ByValue).valueType val varTypeAliasee = mirror.info.constructPointedType(valueType) val valueTypeAliasee = baseMirror.valueType listOf( TypealiasStub(varType, varTypeAliasee.toStubIrType(), StubOrigin.VarOf(origin)), TypealiasStub(valueType.classifier, valueTypeAliasee.toStubIrType(), origin) ) } is TypeMirror.ByRef -> { val varTypeAliasee = baseMirror.pointedType listOf(TypealiasStub(varType, varTypeAliasee.toStubIrType(), origin)) } } } }
apache-2.0
1673e94beb904a98d5ca1c6f9926f0a7
47.004167
152
0.586697
5.980793
false
false
false
false
goodwinnk/intellij-community
python/src/com/jetbrains/python/console/PythonConsoleRemoteProcessCreator.kt
1
4926
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.console import com.intellij.execution.ExecutionException import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.process.ProcessHandler import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.project.Project import com.intellij.openapi.util.Ref import com.intellij.remote.CredentialsType import com.intellij.remote.ext.CredentialsCase import com.jetbrains.python.remote.PyRemotePathMapper import com.jetbrains.python.remote.PyRemoteProcessHandlerBase import com.jetbrains.python.remote.PyRemoteSdkAdditionalDataBase import com.jetbrains.python.remote.PyRemoteSocketToLocalHostProvider interface PythonConsoleRemoteProcessCreator<T> { val credentialsType: CredentialsType<T> @Throws(ExecutionException::class) fun createRemoteConsoleProcess(commandLine: GeneralCommandLine, pathMapper: PyRemotePathMapper, project: Project, data: PyRemoteSdkAdditionalDataBase, runnerFileFromHelpers: String, credentials: T): RemoteConsoleProcessData companion object { val EP_NAME: ExtensionPointName<PythonConsoleRemoteProcessCreator<Any>> = ExtensionPointName.create<PythonConsoleRemoteProcessCreator<Any>>("Pythonid.remoteConsoleProcessCreator") } } data class RemoteConsoleProcessData(val remoteProcessHandlerBase: ProcessHandler, val pydevConsoleCommunication: PydevConsoleCommunication, val commandLine: String?, val process: Process, val socketProvider: PyRemoteSocketToLocalHostProvider) { constructor(remoteProcessHandlerBase: PyRemoteProcessHandlerBase, pydevConsoleCommunication: PydevConsoleCommunication) : this(remoteProcessHandlerBase = remoteProcessHandlerBase, pydevConsoleCommunication = pydevConsoleCommunication, commandLine = remoteProcessHandlerBase.commandLine, process = remoteProcessHandlerBase.process, socketProvider = remoteProcessHandlerBase.remoteSocketToLocalHostProvider) } @Throws(ExecutionException::class) fun createRemoteConsoleProcess(commandLine: GeneralCommandLine, pathMapper: PyRemotePathMapper, project: Project, data: PyRemoteSdkAdditionalDataBase, runnerFileFromHelpers: String): RemoteConsoleProcessData { val extensions = PythonConsoleRemoteProcessCreator.EP_NAME.extensions val result = Ref.create<RemoteConsoleProcessData>() val exception = Ref.create<ExecutionException>() val collectedCases = extensions.map { object : CredentialsCase<Any> { override fun getType(): CredentialsType<Any> = it.credentialsType override fun process(credentials: Any) { try { val remoteConsoleProcess = it.createRemoteConsoleProcess(commandLine = commandLine, pathMapper = pathMapper, project = project, data = data, runnerFileFromHelpers = runnerFileFromHelpers, credentials = credentials) result.set(remoteConsoleProcess) } catch (e: ExecutionException) { exception.set(e) } } } as CredentialsCase<Any> } data.switchOnConnectionType(*collectedCases.toTypedArray()) if (!exception.isNull) { throw exception.get() } else if (!result.isNull) { return result.get() } else { throw ExecutionException("Python console for ${data.remoteConnectionType.name} interpreter is not supported") } }
apache-2.0
d733ac317292231304598f4e68925f99
47.782178
183
0.626269
6.481579
false
false
false
false
FFlorien/AmpachePlayer
app/src/main/java/be/florien/anyflow/data/local/model/DbQueueOrder.kt
1
479
package be.florien.anyflow.data.local.model import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.PrimaryKey @Entity(tableName = "QueueOrder", foreignKeys = [ForeignKey( entity = DbSong::class, parentColumns = ["id"], childColumns = ["songId"], onDelete = ForeignKey.CASCADE)]) data class DbQueueOrder( @field:PrimaryKey val order: Int, val songId: Long)
gpl-3.0
f5e790b24d363a6f9015ef527fc0022a
29
48
0.622129
4.742574
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/platform/mixin/config/inspection/ConfigPropertyInspection.kt
1
1241
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.config.inspection import com.intellij.codeInspection.ProblemsHolder import com.intellij.json.psi.JsonElementVisitor import com.intellij.json.psi.JsonProperty import com.intellij.json.psi.JsonStringLiteral import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor abstract class ConfigPropertyInspection(private vararg val names: String) : MixinConfigInspection() { protected abstract fun visitValue(literal: JsonStringLiteral, holder: ProblemsHolder) protected open fun findProperty(literal: PsiElement) = (literal.parent as? JsonProperty)?.takeIf { it.value === literal } final override fun buildVisitor(holder: ProblemsHolder): PsiElementVisitor = Visitor(holder) private inner class Visitor(private val holder: ProblemsHolder) : JsonElementVisitor() { override fun visitStringLiteral(literal: JsonStringLiteral) { val property = findProperty(literal) ?: return if (property.name !in names) { return } visitValue(literal, holder) } } }
mit
94eeabbbffc18e3f05ba9789adb21d19
30.025
101
0.726833
4.791506
false
true
false
false
equeim/tremotesf-android
torrentfile/src/main/kotlin/org/equeim/tremotesf/torrentfile/TorrentFileParser.kt
1
4546
/* * Copyright (C) 2017-2022 Alexey Rochev <[email protected]> * * This file is part of Tremotesf. * * Tremotesf 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. * * Tremotesf is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.equeim.tremotesf.torrentfile import androidx.annotation.VisibleForTesting import kotlinx.coroutines.ensureActive import kotlinx.coroutines.withContext import kotlinx.serialization.Serializable import kotlinx.serialization.SerializationException import org.equeim.bencode.Bencode import org.equeim.tremotesf.common.DefaultTremotesfDispatchers import org.equeim.tremotesf.common.TremotesfDispatchers import timber.log.Timber import java.io.FileDescriptor import java.io.FileInputStream import java.io.IOException import java.io.InputStream class FileReadException(cause: Throwable) : Exception(cause) class FileIsTooLargeException : Exception() class FileParseException : Exception { constructor(cause: Throwable) : super(cause) constructor(message: String) : super(message) } object TorrentFileParser { suspend fun createFilesTree(fd: FileDescriptor): TorrentFilesTreeBuildResult { return createFilesTree(parseFd(fd)) } @VisibleForTesting internal suspend fun createFilesTree(torrentFile: TorrentFile, dispatchers: TremotesfDispatchers = DefaultTremotesfDispatchers) = withContext(dispatchers.Default) { buildTorrentFilesTree { val info = torrentFile.info if (info.files == null) { addFile( 0, listOf(info.name), info.length ?: throw FileParseException("Field 'length' must not be null for single-file torrent"), 0, TorrentFilesTree.Item.WantedState.Wanted, TorrentFilesTree.Item.Priority.Normal ) } else { val fullPath = mutableListOf(info.name) info.files.forEachIndexed { index, file -> ensureActive() if (fullPath.size > 1) fullPath.subList(1, fullPath.size).clear() fullPath.addAll(file.path) addFile( index, fullPath, file.length, 0, TorrentFilesTree.Item.WantedState.Wanted, TorrentFilesTree.Item.Priority.Normal ) } } } } @Serializable @VisibleForTesting internal data class TorrentFile(val info: Info) { @Serializable data class Info( val files: List<File>? = null, val length: Long? = null, val name: String ) @Serializable data class File(val length: Long, val path: List<String>) } private suspend fun parseFd(fd: FileDescriptor): TorrentFile = parseFile(FileInputStream(fd).buffered()) @VisibleForTesting internal suspend fun parseFile(inputStream: InputStream, dispatchers: TremotesfDispatchers = DefaultTremotesfDispatchers): TorrentFile = withContext(dispatchers.IO) { @Suppress("BlockingMethodInNonBlockingContext") if (inputStream.available() > MAX_FILE_SIZE) { Timber.e("File is too large") throw FileIsTooLargeException() } try { Bencode.decode(inputStream) } catch (error: IOException) { Timber.e(error, "Failed to read file") throw FileReadException(error) } catch (error: SerializationException) { Timber.e(error, "Failed to parse bencode structure") throw FileParseException(error) } } // 10 MiB private const val MAX_FILE_SIZE = 10 * 1024 * 1024 }
gpl-3.0
303190c2ec572532df0e92b2912b50de
35.95935
140
0.616146
5.219288
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/platform/mixin/inspection/injector/InvalidInjectorMethodSignatureInspection.kt
1
11049
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.inspection.injector import com.demonwav.mcdev.platform.mixin.handlers.InjectAnnotationHandler import com.demonwav.mcdev.platform.mixin.handlers.InjectorAnnotationHandler import com.demonwav.mcdev.platform.mixin.handlers.MixinAnnotationHandler import com.demonwav.mcdev.platform.mixin.inspection.MixinInspection import com.demonwav.mcdev.platform.mixin.reference.MethodReference import com.demonwav.mcdev.platform.mixin.util.MixinConstants import com.demonwav.mcdev.platform.mixin.util.hasAccess import com.demonwav.mcdev.platform.mixin.util.isConstructor import com.demonwav.mcdev.util.Parameter import com.demonwav.mcdev.util.fullQualifiedName import com.demonwav.mcdev.util.isErasureEquivalentTo import com.demonwav.mcdev.util.synchronize import com.intellij.codeInsight.intention.QuickFixFactory import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import com.intellij.psi.JavaElementVisitor import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiClassType import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiMethod import com.intellij.psi.PsiModifier import com.intellij.psi.PsiParameter import com.intellij.psi.PsiParameterList import com.intellij.psi.codeStyle.JavaCodeStyleManager import com.intellij.psi.codeStyle.VariableKind import org.objectweb.asm.Opcodes import org.objectweb.asm.tree.AbstractInsnNode import org.objectweb.asm.tree.InsnList import org.objectweb.asm.tree.MethodInsnNode class InvalidInjectorMethodSignatureInspection : MixinInspection() { override fun getStaticDescription() = "Reports problems related to the method signature of Mixin injectors" override fun buildVisitor(holder: ProblemsHolder): PsiElementVisitor = Visitor(holder) private class Visitor(private val holder: ProblemsHolder) : JavaElementVisitor() { override fun visitMethod(method: PsiMethod) { val identifier = method.nameIdentifier ?: return val modifiers = method.modifierList var reportedStatic = false var reportedSignature = false for (annotation in modifiers.annotations) { val qName = annotation.qualifiedName ?: continue val handler = MixinAnnotationHandler.forMixinAnnotation(qName) as? InjectorAnnotationHandler ?: continue val methodAttribute = annotation.findDeclaredAttributeValue("method") ?: continue val targetMethods = MethodReference.resolveAllIfNotAmbiguous(methodAttribute) ?: continue for (targetMethod in targetMethods) { if (!reportedStatic) { var shouldBeStatic = targetMethod.method.hasAccess(Opcodes.ACC_STATIC) if (!shouldBeStatic && targetMethod.method.isConstructor) { // before the superclass constructor call, everything must be static targetMethod.method.instructions?.let { methodInsns -> val superCtorCall = findSuperConstructorCall(methodInsns) val insns = handler.resolveInstructions( annotation, targetMethod.clazz, targetMethod.method ) shouldBeStatic = insns.any { methodInsns.indexOf(it.insn) <= methodInsns.indexOf(superCtorCall) } } } if (shouldBeStatic && !modifiers.hasModifierProperty(PsiModifier.STATIC)) { reportedStatic = true holder.registerProblem( identifier, "Method must be static", QuickFixFactory.getInstance().createModifierListFix( modifiers, PsiModifier.STATIC, true, false ) ) } } if (!reportedSignature) { // Check method parameters val parameters = method.parameterList val possibleSignatures = handler.expectedMethodSignature( annotation, targetMethod.clazz, targetMethod.method ) ?: continue val annotationName = annotation.nameReferenceElement?.referenceName if (possibleSignatures.isEmpty()) { reportedSignature = true holder.registerProblem( parameters, "There are no possible signatures for this injector" ) continue } var isValid = false for ((expectedParameters, expectedReturnType) in possibleSignatures) { if (checkParameters(parameters, expectedParameters)) { val methodReturnType = method.returnType if (methodReturnType != null && methodReturnType.isErasureEquivalentTo(expectedReturnType) ) { isValid = true break } } } if (!isValid) { val (expectedParameters, expectedReturnType) = possibleSignatures[0] if (!checkParameters(parameters, expectedParameters)) { reportedSignature = true holder.registerProblem( parameters, "Method parameters do not match expected parameters for $annotationName", ParametersQuickFix(expectedParameters, handler is InjectAnnotationHandler) ) } val methodReturnType = method.returnType if (methodReturnType == null || !methodReturnType.isErasureEquivalentTo(expectedReturnType) ) { reportedSignature = true holder.registerProblem( method.returnTypeElement ?: identifier, "Expected return type '${expectedReturnType.presentableText}' " + "for $annotationName method", QuickFixFactory.getInstance().createMethodReturnFix( method, expectedReturnType, false ) ) } } } } } } private fun findSuperConstructorCall(methodInsns: InsnList): AbstractInsnNode? { var superCtorCall = methodInsns.first var newCount = 0 while (superCtorCall != null) { if (superCtorCall.opcode == Opcodes.NEW) { newCount++ } else if (superCtorCall.opcode == Opcodes.INVOKESPECIAL) { val methodCall = superCtorCall as MethodInsnNode if (methodCall.name == "<init>") { if (newCount == 0) { return superCtorCall } else { newCount-- } } } superCtorCall = superCtorCall.next } return null } private fun checkParameters(parameterList: PsiParameterList, expected: List<ParameterGroup>): Boolean { val parameters = parameterList.parameters var pos = 0 for (group in expected) { // Check if parameter group matches if (group.match(parameters, pos)) { pos += group.size } else if (group.required) { return false } } return true } } private class ParametersQuickFix( private val expected: List<ParameterGroup>, isInject: Boolean ) : LocalQuickFix { private val fixName = if (isInject) { "Fix method parameters" } else { "Fix method parameters (won't keep captured locals)" } override fun getFamilyName() = fixName override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val parameters = descriptor.psiElement as PsiParameterList // We want to preserve captured locals val locals = parameters.parameters.dropWhile { val fqname = (it.type as? PsiClassType)?.fullQualifiedName ?: return@dropWhile true return@dropWhile fqname != MixinConstants.Classes.CALLBACK_INFO && fqname != MixinConstants.Classes.CALLBACK_INFO_RETURNABLE }.drop(1) // the first element in the list is the CallbackInfo but we don't want it val newParams = expected.flatMapTo(mutableListOf<PsiParameter>()) { if (it.default) { it.parameters?.mapIndexed { i: Int, p: Parameter -> JavaPsiFacade.getElementFactory(project).createParameter( p.name ?: JavaCodeStyleManager.getInstance(project) .suggestVariableName(VariableKind.PARAMETER, null, null, p.type).names .firstOrNull() ?: "var$i", p.type ) } ?: emptyList() } else { emptyList() } } // Restore the captured locals before applying the fix newParams.addAll(locals) parameters.synchronize(newParams) } } }
mit
1f172061601f23ffcf2e4c3cb6bb6a20
43.732794
120
0.523848
6.753667
false
false
false
false
CherepanovAleksei/BinarySearchTree
src/BTree/BTree.kt
1
5943
/** * * by Cherepanov Aleksei (PI-171) * * [email protected] * **/ package BTree import java.util.LinkedList class BTree<K: Comparable<K>> (val deg: Int): Iterable<BNode<K>> { var root: BNode<K>? = null fun insert(key: K) { if (root == null) root = BNode() if (root!!.keys.size == 2 * deg - 1) { val newNode: BNode<K> = BNode(false) newNode.children.add(root!!) newNode.splitChildren(deg, 0) root = newNode insertNonfull(key, newNode) } else { insertNonfull(key, root!!) } } private fun insertNonfull(key: K, node: BNode<K>) { var count = 0 while (count < node.keys.size && key > node.keys[count]) count++ if (node.isLeaf){ node.keys.add(count, key) } else { if (node.children[count].keys.size == 2 * deg - 1) { node.splitChildren(deg, count) if (key > node.keys[count]) count++ } insertNonfull(key, node.children[count]) } } fun delete(key: K) { if (search(key) == null) return if (root == null) return deleteRecursive(key, root!!) if (root!!.keys.size == 0) root = null } private fun deleteRecursive(key: K, node: BNode<K>) { var count = 0 while (count < node.keys.size && key > node.keys[count]) count++ if (node.keys.size > count && node.keys[count] == key) { if ((node.isLeaf)) { node.keys.removeAt(count) } else if (node.children[count].keys.size > deg - 1) { val prevNode = prev(key, node) node.keys[count] = prevNode.keys.last() deleteRecursive(prevNode.keys.last(), node.children[count]) } else if (node.children[count + 1].keys.size > deg - 1) { val nextNode = next(key, node) node.keys[count] = nextNode.keys.first() deleteRecursive(nextNode.keys.first(), node.children[count + 1]) } else { node.mergeChildren(count) if (node.keys.isEmpty()) root = node.children[count] deleteRecursive(key, node.children[count]) } } else { if (node.children[count].keys.size < deg) { when { node.children[count] != node.children.last() && node.children[count + 1].keys.size > deg - 1 -> { node.children[count].keys.add(node.keys[count]) node.keys[count] = node.children[count + 1].keys.first() node.children[count + 1].keys.removeAt(0) if (!node.children[count].isLeaf) { node.children[count].children.add(node.children[count + 1].children.first()) node.children[count + 1].children.removeAt(0) } } node.children[count] != node.children.first() && node.children[count - 1].keys.size > deg - 1 -> { node.children[count].keys.add(0, node.keys[count - 1]) node.keys[count - 1] = node.children[count - 1].keys.last() node.children[count - 1].keys.removeAt(node.children[count - 1].keys.size - 1) if (!node.children[count].isLeaf) { node.children[count].children.add(0, node.children[count - 1].children.last()) node.children[count - 1].children.removeAt(node.children[count - 1].children.size - 1) } } node.children[count] != node.children.last() -> { node.mergeChildren(count) if (node.keys.isEmpty()) root = node.children[count] } node.children[count] != node.children.first() -> { node.mergeChildren(count - 1) if (node.keys.isEmpty()) root = node.children[count - 1] count-- } } } deleteRecursive(key, node.children[count]) } } fun search(key: K): K? { var node: BNode<K>? = root ?: return null var count = 0 while (count < node!!.keys.size - 1 && key > node.keys[count]) count++ while (node!!.keys[count] != key) { if (node.isLeaf) return null when { key < node.keys[count] -> node = node.children[count] key > node.keys[count] -> node = node.children[count + 1] } count = 0 while (count < node.keys.size - 1 && key > node.keys[count]) count++ } return key } private fun prev(key: K, node: BNode<K>): BNode<K> { var current = node.children[node.keys.indexOf(key)] while (!current.isLeaf) current = current.children.last() return current } private fun next(key: K, node: BNode<K>): BNode<K> { var current = node.children[node.keys.indexOf(key) + 1] while (!current.isLeaf) current = current.children.first() return current } override fun iterator(): Iterator<BNode<K>> { return (object : Iterator<BNode<K>> { var NodeList = LinkedList<BNode<K>>() init { if (root != null && root!!.keys.isNotEmpty()) { NodeList.add(root!!) } } override fun hasNext() = NodeList.isNotEmpty() override fun next(): BNode<K> { val next = NodeList.remove() if (!next.isLeaf) { NodeList.addAll(next.children) } return next } }) } }
mit
fec2e4fe6800a2a53db29770e9b118a9
34.807229
118
0.486118
4.147244
false
false
false
false
niranjan94/show-java
app/src/main/kotlin/com/njlabs/showjava/activities/purchase/PurchaseActivity.kt
1
4483
/* * Show Java - A java/apk decompiler for android * Copyright (c) 2018 Niranjan Rajendran * * 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 <https://www.gnu.org/licenses/>. */ package com.njlabs.showjava.activities.purchase import android.content.Intent import android.os.Bundle import android.view.View import android.widget.Toast import com.google.firebase.analytics.FirebaseAnalytics import com.njlabs.showjava.R import com.njlabs.showjava.activities.BaseActivity import com.njlabs.showjava.utils.secure.PurchaseUtils import kotlinx.android.synthetic.main.activity_purchase.* import org.solovyev.android.checkout.* import timber.log.Timber class PurchaseActivity : BaseActivity() { private lateinit var purchaseUtils: PurchaseUtils private fun isLoading(loading: Boolean) { buttonProgressBar.visibility = if (!loading) View.GONE else View.VISIBLE buyButton.visibility = if (loading) View.GONE else View.VISIBLE } override fun init(savedInstanceState: Bundle?) { setupLayout(R.layout.activity_purchase, getString(R.string.appNameGetPro)) Timber.d("[pa] init") secureUtils.isSafeExtended( { // allow runOnUiThread { isLoading(false) purchaseUtils = PurchaseUtils(this, secureUtils) { isLoading(it) } purchaseUtils.doOnComplete { finish() } purchaseUtils.initializeCheckout(true) buyButton.setOnClickListener { isLoading(true) makePurchase() } } }, { err, app ->// Do not allow runOnUiThread { isLoading(false) buyButton.visibility = View.GONE if (app != null) { Toast.makeText( context, getString(R.string.deviceVerificationFailedPirateApp, "${app.name} (${app.packageName})"), Toast.LENGTH_LONG ).show() } else { Toast.makeText( context, getString(R.string.deviceVerificationFailed, err.name), Toast.LENGTH_SHORT ).show() } } }, { // On Error runOnUiThread { isLoading(false) buyButton.visibility = View.GONE Toast.makeText(context, R.string.purchaseInitError, Toast.LENGTH_SHORT).show() } } ) Timber.d("[pa] initComplete") } private fun makePurchase() { firebaseAnalytics.logEvent(FirebaseAnalytics.Event.BEGIN_CHECKOUT, null) purchaseUtils.checkout.whenReady(object : Checkout.EmptyListener() { override fun onReady(requests: BillingRequests) { firebaseAnalytics.logEvent(FirebaseAnalytics.Event.CHECKOUT_PROGRESS, null) requests.purchase( ProductTypes.IN_APP, secureUtils.iapProductId, null, purchaseUtils.checkout.purchaseFlow ) } }) } override fun onDestroy() { if (::purchaseUtils.isInitialized) { purchaseUtils.onDestroy() } super.onDestroy() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (::purchaseUtils.isInitialized) { purchaseUtils.checkout.onActivityResult(requestCode, resultCode, data) } } }
gpl-3.0
634e3059002173f62243437ddf26692f
35.16129
118
0.573277
5.311611
false
false
false
false
uchuhimo/kotlin-playground
kotlinx-bimap/src/main/kotlin/com/uchuhimo/collections/MutableBiMap.kt
1
7090
package com.uchuhimo.collections import com.google.common.collect.HashBiMap interface MutableBiMap<K, V> : MutableMap<K, V>, BiMap<K, V> { override val inverse: MutableBiMap<V, K> override val values: MutableSet<V> /** * Associates the specified [value] with the specified [key] in the bimap. * * The bimap throws [IllegalArgumentException] if the given value is already * bound to a different key in it. The bimap will remain unmodified in this * event. To avoid this exception, call [forcePut] instead. * * @return the previous value associated with the key, or `null` if the key * was not present in the bimap. */ override fun put(key: K, value: V): V? /** * An alternate form of [put] that silently removes any existing entry * with the value [value] before proceeding with the [put] operation. * * If the bimap previously contained the provided key-value * mapping, this method has no effect. * * Note that a successful call to this method could cause the size of the * bimap to increase by one, stay the same, or even decrease by one. * * **Warning**: If an existing entry with this value is removed, the key * for that entry is discarded and not returned. * * @param key the key with which the specified value is to be associated. * @param value the value to be associated with the specified key. * @return the value which was previously associated with the key, or `null` * if there was no previous entry. */ fun forcePut(key: K, value: V): V? } private class MutableBiMapImpl<K, V> private constructor(private val delegate: MutableMap<K, V>) : MutableBiMap<K, V>, Map<K, V> by delegate { constructor(forward: MutableMap<K, V>, backward: MutableMap<V, K>) : this(forward) { _inverse = MutableBiMapImpl(backward, this) } private constructor(backward: MutableMap<K, V>, forward: MutableBiMapImpl<V, K>) : this(backward) { _inverse = forward } private lateinit var _inverse: MutableBiMapImpl<V, K> private val inverseDelegate = inverse.delegate override val inverse: MutableBiMapImpl<V, K> get() = _inverse override fun containsValue(value: V): Boolean = inverseDelegate.containsKey(value) override val entries: MutableSet<MutableMap.MutableEntry<K, V>> = object : MutableSet<MutableMap.MutableEntry<K, V>> by delegate.entries { override fun clear() { [email protected]() } override fun iterator(): MutableIterator<MutableMap.MutableEntry<K, V>> = object : MutableIterator<MutableMap.MutableEntry<K, V>> { override fun remove() { TODO("not implemented") } override fun hasNext(): Boolean { TODO("not implemented") } override fun next(): MutableMap.MutableEntry<K, V> { TODO("not implemented") } } override fun remove(element: MutableMap.MutableEntry<K, V>): Boolean { inverseDelegate.remove(element.value, element.key) return delegate.remove(element.key, element.value) } } override val keys: MutableSet<K> get() = TODO("not implemented") override val values: MutableSet<V> get() = TODO("not implemented") override fun clear() { delegate.clear() inverseDelegate.clear() } override fun put(key: K, value: V): V? { inverseDelegate.put(value, key)?.also { oldKey -> delegate.remove(oldKey) } return delegate.put(key, value)?.also { oldValue -> inverseDelegate.remove(oldValue) } } override fun forcePut(key: K, value: V): V? { TODO("not implemented") } override fun putAll(from: Map<out K, V>) { from.forEach { key, value -> this[key] = value } } override fun remove(key: K): V? { return delegate.remove(key).also { value -> if (value != null) { inverseDelegate.remove(value) } } } } typealias GuavaBiMap<K, V> = com.google.common.collect.BiMap<K, V> class MutableBiMapWrapper<K, V>(internal val delegate: GuavaBiMap<K, V>) : MutableBiMap<K, V>, MutableMap<K, V> by delegate { override val inverse: MutableBiMap<V, K> = InverseWrapper(this) override val values: MutableSet<V> = delegate.values override fun forcePut(key: K, value: V): V? = delegate.forcePut(key, value) companion object { private class InverseWrapper<K, V>(private val wrapper: MutableBiMapWrapper<V, K>) : MutableBiMap<K, V>, MutableMap<K, V> by wrapper.delegate.inverse() { override val inverse: MutableBiMap<V, K> = wrapper override val values: MutableSet<V> = wrapper.delegate.inverse().values override fun forcePut(key: K, value: V): V? = wrapper.delegate.inverse().forcePut(key, value) } } } class GuavaBiMapWrapper<K, V>(internal val delegate: MutableBiMap<K, V>) : GuavaBiMap<K, V> { override fun putAll(from: Map<out K, V>) = delegate.putAll(from) override val size: Int get() = delegate.size override fun containsKey(key: K): Boolean = delegate.containsKey(key) override fun get(key: K): V? = delegate.get(key) override fun remove(key: K): V? = delegate.remove(key) override val values: MutableSet<V> get() = delegate.values override fun containsValue(value: V): Boolean = delegate.containsValue(value) override fun isEmpty(): Boolean = delegate.isEmpty() override fun forcePut(key: K?, value: V?): V? = delegate.forcePut(key!!, value!!) override val entries: MutableSet<MutableMap.MutableEntry<K, V>> get() = delegate.entries override val keys: MutableSet<K> get() = delegate.keys override fun put(key: K?, value: V?): V? = delegate.put(key!!, value!!) private val _inverse: GuavaBiMap<V, K> = delegate.inverse.asGuavaBiMap() override fun inverse(): GuavaBiMap<V, K> = _inverse override fun clear() = delegate.clear() } fun <K, V> MutableBiMap<K, V>.asGuavaBiMap(): GuavaBiMap<K, V> = if (this is MutableBiMapWrapper) { delegate } else { GuavaBiMapWrapper(this) } fun <K, V> GuavaBiMap<K, V>.asMutableBiMap(): MutableBiMap<K, V> = if (this is GuavaBiMapWrapper) { delegate } else { MutableBiMapWrapper(this) } @Suppress("NOTHING_TO_INLINE") inline fun <K, V> mutableBiMapOf(): MutableBiMap<K, V> = HashBiMap.create<K, V>().asMutableBiMap() fun <K, V> mutableBiMapOf(vararg pairs: Pair<K, V>): MutableBiMap<K, V> = HashBiMap.create<K, V>(pairs.size).asMutableBiMap().apply { putAll(pairs) }
apache-2.0
414466ce8efade1e039d3788cb2a43d5
35.546392
103
0.611566
4.278817
false
false
false
false
oldergod/red
app/src/main/java/com/benoitquenaudon/tvfoot/red/app/domain/matches/MatchesViewModel.kt
1
17513
package com.benoitquenaudon.tvfoot.red.app.domain.matches import com.benoitquenaudon.tvfoot.red.app.common.schedulers.BaseSchedulerProvider import com.benoitquenaudon.tvfoot.red.app.data.entity.FilterTeam import com.benoitquenaudon.tvfoot.red.app.data.source.BaseMatchesRepository import com.benoitquenaudon.tvfoot.red.app.data.source.BasePreferenceRepository import com.benoitquenaudon.tvfoot.red.app.data.source.BaseTeamRepository import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesAction.FilterAction.ClearFiltersAction import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesAction.FilterAction.ClearSearchInputAction import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesAction.FilterAction.LoadTagsAction import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesAction.FilterAction.SearchInputAction import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesAction.FilterAction.SearchInputAction.ClearSearchAction import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesAction.FilterAction.SearchInputAction.SearchTeamAction import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesAction.FilterAction.SearchedTeamSelectedAction import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesAction.FilterAction.ToggleFilterBroadcasterAction import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesAction.FilterAction.ToggleFilterCompetitionAction import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesAction.FilterAction.ToggleFilterTeamAction import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesAction.LoadNextPageAction import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesAction.RefreshAction import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesAction.RefreshNotificationStatusAction import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesIntent.FilterIntent.ClearFilters import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesIntent.FilterIntent.ClearSearchInputIntent import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesIntent.FilterIntent.FilterInitialIntent import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesIntent.FilterIntent.SearchInputIntent.ClearSearchIntent import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesIntent.FilterIntent.SearchInputIntent.SearchTeamIntent import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesIntent.FilterIntent.SearchedTeamSelectedIntent import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesIntent.FilterIntent.ToggleFilterIntent.ToggleFilterBroadcasterIntent import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesIntent.FilterIntent.ToggleFilterIntent.ToggleFilterCompetitionIntent import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesIntent.FilterIntent.ToggleFilterIntent.ToggleFilterTeamIntent import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesIntent.InitialIntent import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesIntent.LoadNextPageIntent import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesIntent.RefreshIntent import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesIntent.RefreshNotificationStatusIntent import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesResult.FilterResult.ClearFiltersResult import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesResult.FilterResult.ClearSearchInputResult import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesResult.FilterResult.LoadTagsResult import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesResult.FilterResult.SearchInputResult import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesResult.FilterResult.SearchInputResult.ClearSearchResult import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesResult.FilterResult.SearchInputResult.SearchTeamResult import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesResult.FilterResult.SearchedTeamSelectedResult import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesResult.FilterResult.SearchedTeamSelectedResult.TeamSearchFailure import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesResult.FilterResult.SearchedTeamSelectedResult.TeamSearchInFlight import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesResult.FilterResult.SearchedTeamSelectedResult.TeamSearchSuccess import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesResult.FilterResult.ToggleFilterBroadcasterResult import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesResult.FilterResult.ToggleFilterCompetitionResult import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesResult.FilterResult.ToggleFilterTeamResult import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesResult.LoadNextPageResult import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesResult.RefreshNotificationStatusResult import com.benoitquenaudon.tvfoot.red.app.domain.matches.MatchesResult.RefreshResult import com.benoitquenaudon.tvfoot.red.app.mvi.RedViewModel import com.benoitquenaudon.tvfoot.red.util.Quintuple import com.benoitquenaudon.tvfoot.red.util.logAction import com.benoitquenaudon.tvfoot.red.util.logIntent import com.benoitquenaudon.tvfoot.red.util.logResult import com.benoitquenaudon.tvfoot.red.util.logState import com.benoitquenaudon.tvfoot.red.util.notOfType import io.reactivex.Observable import io.reactivex.ObservableTransformer import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.Singles import io.reactivex.subjects.PublishSubject import java.util.concurrent.TimeUnit.MILLISECONDS import javax.inject.Inject import kotlin.LazyThreadSafetyMode.NONE class MatchesViewModel @Inject constructor( private val intentsSubject: PublishSubject<MatchesIntent>, private val matchesRepository: BaseMatchesRepository, private val teamRepository: BaseTeamRepository, private val preferenceRepository: BasePreferenceRepository, private val schedulerProvider: BaseSchedulerProvider ) : RedViewModel<MatchesIntent, MatchesViewState>() { private val disposables = CompositeDisposable() private val statesObservable: Observable<MatchesViewState> by lazy(NONE) { compose().skip(1) .replay(1) .autoConnect(0) } override fun states(): Observable<MatchesViewState> = statesObservable override fun processIntents(intents: Observable<MatchesIntent>) { disposables.add(intents.subscribe(intentsSubject::onNext, intentsSubject::onError)) } override fun onCleared() { disposables.dispose() super.onCleared() } private fun compose(): Observable<MatchesViewState> { return intentsSubject .publish { shared -> Observable.merge( shared.ofType(InitialIntent::class.java).take(1), shared.notOfType(InitialIntent::class.java) ) } .publish { shared -> Observable.merge( shared.ofType(FilterInitialIntent::class.java).take(1), shared.notOfType(FilterInitialIntent::class.java) ) } .doOnNext(this::logIntent) .map(this::actionFromIntent) .doOnNext(this::logAction) .compose<MatchesResult>(actionToResultTransformer) .doOnNext(this::logResult) .scan(MatchesViewState.idle(), MatchesViewStateMachine) .doOnNext(this::logState) } private fun actionFromIntent(intent: MatchesIntent): MatchesAction = when (intent) { InitialIntent -> RefreshAction RefreshIntent -> RefreshAction is LoadNextPageIntent -> LoadNextPageAction(intent.pageIndex) ClearFilters -> ClearFiltersAction is ToggleFilterCompetitionIntent -> ToggleFilterCompetitionAction(intent.tagName) is ToggleFilterBroadcasterIntent -> ToggleFilterBroadcasterAction(intent.tagName) is ToggleFilterTeamIntent -> ToggleFilterTeamAction(intent.teamCode) FilterInitialIntent -> LoadTagsAction is SearchTeamIntent -> SearchTeamAction(intent.input) ClearSearchIntent -> ClearSearchAction is SearchedTeamSelectedIntent -> SearchedTeamSelectedAction(intent.team) ClearSearchInputIntent -> ClearSearchInputAction is RefreshNotificationStatusIntent -> RefreshNotificationStatusAction(intent.matchId) } private val refreshTransformer: ObservableTransformer<RefreshAction, RefreshResult> get() = ObservableTransformer { actions: Observable<RefreshAction> -> actions.flatMap { matchesRepository.loadPageWithNotificationStatus(0) .toObservable() .map<RefreshResult> { RefreshResult.Success(it.first, it.second) } .onErrorReturn(RefreshResult::Failure) .subscribeOn(schedulerProvider.io()) .observeOn(schedulerProvider.ui()) .startWith(RefreshResult.InFlight) } } private val loadNextPageTransformer: ObservableTransformer<LoadNextPageAction, LoadNextPageResult> get() = ObservableTransformer { actions: Observable<LoadNextPageAction> -> actions.flatMap { (pageIndex) -> matchesRepository.loadPageWithNotificationStatus(pageIndex) .toObservable() .map<LoadNextPageResult> { (matches, notificationPairs) -> LoadNextPageResult.Success(pageIndex, matches, notificationPairs) } .onErrorReturn(LoadNextPageResult::Failure) .subscribeOn(schedulerProvider.io()) .observeOn(schedulerProvider.ui()) .startWith(LoadNextPageResult.InFlight) } } private val refreshNotificationStatusTransformer: ObservableTransformer<RefreshNotificationStatusAction, RefreshNotificationStatusResult> get() = ObservableTransformer { actions: Observable<RefreshNotificationStatusAction> -> actions .map(RefreshNotificationStatusAction::matchId) .flatMapSingle { matchId -> preferenceRepository .loadNotifyMatchStart(matchId) .map { RefreshNotificationStatusResult(matchId, it) } } } private val loadTagsTransformer: ObservableTransformer<LoadTagsAction, LoadTagsResult> get() = ObservableTransformer { actions: Observable<LoadTagsAction> -> actions.flatMap { Singles.zip( matchesRepository.loadTags(), preferenceRepository.loadFilteredCompetitionNames(), preferenceRepository.loadFilteredBroadcasterNames(), preferenceRepository.loadFilteredTeamCodes(), preferenceRepository.loadTeams(), ::Quintuple ) .toObservable() .map<LoadTagsResult> { LoadTagsResult.Success( tags = it.first, filteredCompetitionNames = it.second, filteredBroadcasterNames = it.third, filteredTeamNames = it.fourth, teams = it.fifth ) } .onErrorReturn(LoadTagsResult::Failure) .subscribeOn(schedulerProvider.io()) .observeOn(schedulerProvider.ui()) .startWith(LoadTagsResult.InFlight) } } private val searchInputTransformer: ObservableTransformer<SearchInputAction, SearchInputResult> get() = ObservableTransformer { actions: Observable<SearchInputAction> -> actions.switchMap { action -> when (action) { is SearchTeamAction -> { if (action.input.length > 2) { teamRepository.findTeams(action.input) .subscribeOn(schedulerProvider.io()) .delaySubscription(250, MILLISECONDS, schedulerProvider.ui()) .toObservable() .map<SearchTeamResult> { teams -> SearchTeamResult.Success(action.input, teams) } .onErrorReturn(SearchTeamResult::Failure) .observeOn(schedulerProvider.ui()) .startWith(SearchTeamResult.InFlight(action.input)) } else { Observable.just(SearchTeamResult.Success(action.input, emptyList())) } } ClearSearchAction -> Observable.just(ClearSearchResult) } } } private val clearFilterTransformer: ObservableTransformer<ClearFiltersAction, ClearFiltersResult> get() = ObservableTransformer { actions: Observable<ClearFiltersAction> -> actions.map { preferenceRepository.clearFilteredCompetitionNames() preferenceRepository.clearFilteredBroadcasterNames() preferenceRepository.clearFilteredTeamCodes() ClearFiltersResult } } private val toggleFilterCompetitionTransformer: ObservableTransformer<ToggleFilterCompetitionAction, ToggleFilterCompetitionResult> get() = ObservableTransformer { actions: Observable<ToggleFilterCompetitionAction> -> actions.map { preferenceRepository.toggleFilteredCompetitionName(it.tagName) ToggleFilterCompetitionResult(it.tagName) } } private val toggleFilterBroadcasterTransformer: ObservableTransformer<ToggleFilterBroadcasterAction, ToggleFilterBroadcasterResult> get() = ObservableTransformer { actions: Observable<ToggleFilterBroadcasterAction> -> actions.map { preferenceRepository.toggleFilteredBroadcasterName(it.tagName) ToggleFilterBroadcasterResult(it.tagName) } } private val toggleFilterTeamTransformer: ObservableTransformer<ToggleFilterTeamAction, ToggleFilterTeamResult> get() = ObservableTransformer { actions: Observable<ToggleFilterTeamAction> -> actions.map { preferenceRepository.toggleFilteredTeamCode(it.teamCode) ToggleFilterTeamResult(it.teamCode) } } private val clearSearchInputTransformer: ObservableTransformer<ClearSearchInputAction, ClearSearchInputResult> get() = ObservableTransformer { actions: Observable<ClearSearchInputAction> -> actions.map { ClearSearchInputResult } } private val searchedTeamSelectedTransformer: ObservableTransformer<SearchedTeamSelectedAction, SearchedTeamSelectedResult> get() = ObservableTransformer { actions: Observable<SearchedTeamSelectedAction> -> actions.flatMap { action -> preferenceRepository.addTeam(FilterTeam(action.team)) .flatMap { preferenceRepository.toggleFilteredTeamCode(action.team.code) } .flatMap { matchesRepository.searchTeamMatchesWithNotificationStatus(action.team.code) } .toObservable() .map<SearchedTeamSelectedResult> { TeamSearchSuccess(it.first, it.second) } .onErrorReturn(::TeamSearchFailure) .subscribeOn(schedulerProvider.io()) .observeOn(schedulerProvider.ui()) .startWith(TeamSearchInFlight(action.team)) } } private val actionToResultTransformer: ObservableTransformer<MatchesAction, MatchesResult> get() = ObservableTransformer { actions: Observable<MatchesAction> -> actions.publish { shared -> Observable.merge<MatchesResult>( shared.ofType(RefreshAction::class.java).compose(refreshTransformer), shared.ofType(LoadNextPageAction::class.java).compose(loadNextPageTransformer), shared.ofType(RefreshNotificationStatusAction::class.java) .compose(refreshNotificationStatusTransformer) ) .mergeWith( Observable.merge<MatchesResult>( shared.ofType(ToggleFilterBroadcasterAction::class.java) .compose(toggleFilterBroadcasterTransformer), shared.ofType(ToggleFilterCompetitionAction::class.java) .compose(toggleFilterCompetitionTransformer), shared.ofType(ToggleFilterTeamAction::class.java) .compose(toggleFilterTeamTransformer), shared.ofType(LoadTagsAction::class.java).compose(loadTagsTransformer) ) ) .mergeWith( Observable.merge<MatchesResult>( shared.ofType(ClearFiltersAction::class.java).compose(clearFilterTransformer), shared.ofType(SearchInputAction::class.java).compose(searchInputTransformer), shared.ofType(SearchedTeamSelectedAction::class.java) .compose(searchedTeamSelectedTransformer), shared.ofType(ClearSearchInputAction::class.java).compose( clearSearchInputTransformer ) ) ) .mergeWith( // Error for not implemented actions shared.filter { v -> v != RefreshAction && v !is LoadNextPageAction && v != ClearFiltersAction && v !is ToggleFilterCompetitionAction && v !is ToggleFilterBroadcasterAction && v !is ToggleFilterTeamAction && v != LoadTagsAction && v !is SearchTeamAction && v != ClearSearchAction && v !is SearchedTeamSelectedAction && v != ClearSearchInputAction && v !is RefreshNotificationStatusAction }.flatMap { w -> Observable.error<MatchesResult>( IllegalArgumentException("Unknown Action type: " + w) ) }) } } }
apache-2.0
57a65a523d45dd13a7dd84e2330ceb12
52.234043
139
0.736082
5.49169
false
false
false
false
Ribesg/anko
dsl/test/org/jetbrains/android/anko/compile/CompileTestFixture.kt
1
5711
/* * Copyright 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.android.anko.compile import org.jetbrains.android.anko.createTempTestFile import org.jetbrains.android.anko.utils.JarFileFilter import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import java.io.BufferedReader import java.io.File import java.io.InputStreamReader import java.util.logging.Logger open class CompileTestFixture { class ProcResult(val stdout: String, val stderr: String, val exitCode: Int) companion object { private val kotlincFilename = "lib/Kotlin/kotlinc/bin/kotlinc-jvm" + (if (isWindows()) ".bat" else "") private fun getAnkoJars(androidSdkVersion: Int): List<File> { val baseDir = File("workdir/zip") val files = listOf( File(baseDir, "anko-common.jar"), File(baseDir, "anko-sdk$androidSdkVersion.jar"), File(baseDir, "anko-support-v4.jar")) files.forEach { assertTrue("File $it does not exist", it.exists()) } return files } private fun getAnkoJars(artifactOriginalDir: File): List<File> { val androidSdkVer = File(artifactOriginalDir, "version.txt").readText().toInt() return getAnkoJars(androidSdkVer) } private val LOG = Logger.getLogger(CompileTestFixture::class.java.name) fun runProcess(args: Array<String>, compiler: Boolean): ProcResult { LOG.info("Exec process: ${args.joinToString(" ")}") val p = Runtime.getRuntime().exec(args) val brInput = BufferedReader(InputStreamReader(p.inputStream)) val brError = BufferedReader(InputStreamReader(p.errorStream)) val errors = StringBuilder() val output = StringBuilder() (brInput.lineSequence() + brError.lineSequence()).forEach { line -> if (compiler && line.startsWith("ERROR")) { errors.append(line).append("\n") } else { output.append(line).append("\n") } } p.waitFor() return ProcResult(output.toString(), errors.toString(), p.exitValue()) } private fun isWindows(): Boolean { val osName = System.getProperty("os.name").toLowerCase() return osName.contains("win") } } protected fun runCompileTest(testData: File, artifactOriginalDir: File) { assertTrue(testData.exists()) compile(testData, artifactOriginalDir).delete() } protected fun runRobolectricTest(testDataFile: File, artifactOriginalDir: File) { assertTrue(testDataFile.exists()) val lib = File("lib/") val robolectricDir = File(lib, "robolectric/") val robolectricJars = robolectricDir.listFiles { file -> file.extension == "jar" }?.toList() ?: listOf() val androidAllJars = File(lib, "androidall").listFiles { file -> file.extension == "jar" }?.toList() ?: listOf() val compiledJarFile = compile(testDataFile, artifactOriginalDir, robolectricJars) val classpath = (listOf( compiledJarFile, File(lib, "Kotlin/kotlinc/lib/kotlin-runtime.jar"), File(lib, "hamcrest-all-1.3.jar") ) + getAnkoJars(artifactOriginalDir) + robolectricJars + androidAllJars) .map { it.absolutePath } .joinToString(File.pathSeparator) val manifest = File("dsl/testData/robolectric/AndroidManifest.xml") val androidRes = File("dsl/testData/robolectric/res/") val androidAssets = File("dsl/testData/robolectric/assets/") val args = arrayOf("java", "-cp", classpath, "-Dapple.awt.UIElement=true", "-Drobolectric.offline=true", "-Drobolectric.dependency.dir=" + lib.absolutePath, "-Dandroid.manifest=" + manifest.absolutePath, "-Dandroid.resources=" + androidRes.absolutePath, "-Dandroid.assets=" + androidAssets.absolutePath, "org.junit.runner.JUnitCore", "test.RobolectricTest" ) val result = runProcess(args, false) assertTrue(result.stderr.isEmpty()) } private fun compile(testData: File, artifactOriginalDir: File, additionalJars: List<File> = emptyList()): File { val platformAndToolkitJars = artifactOriginalDir.listFiles(JarFileFilter()) val classpath = (platformAndToolkitJars + getAnkoJars(artifactOriginalDir) + additionalJars) .map { it.absolutePath } .joinToString(File.pathSeparator) val outputJar = createTempTestFile("compile", ".jar") val args = arrayOf( File(kotlincFilename).absolutePath, "-d", outputJar.absolutePath, "-classpath", classpath.toString(), testData.getPath()) val res = runProcess(args, compiler = true) assertEquals(res.stderr, "", res.stderr) assertEquals(res.stdout, 0, res.exitCode) return outputJar } }
apache-2.0
bb3d7c19378381d6715782d2d170fc87
38.393103
120
0.628086
4.712046
false
true
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/UserQrDialogFragment.kt
1
6698
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.fragment import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color import android.graphics.drawable.BitmapDrawable import android.os.Bundle import android.support.v7.graphics.Palette import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import com.bumptech.glide.Glide import com.bumptech.glide.load.resource.drawable.GlideDrawable import com.bumptech.glide.request.target.Target import io.nayuki.qrcodegen.QrCode import io.nayuki.qrcodegen.QrSegment import kotlinx.android.synthetic.main.fragment_user_qr.* import nl.komponents.kovenant.Promise import nl.komponents.kovenant.combine.and import nl.komponents.kovenant.task import nl.komponents.kovenant.then import nl.komponents.kovenant.ui.failUi import nl.komponents.kovenant.ui.promiseOnUi import nl.komponents.kovenant.ui.successUi import de.vanita5.twittnuker.R import de.vanita5.twittnuker.constant.IntentConstants.EXTRA_USER import de.vanita5.twittnuker.extension.loadOriginalProfileImage import de.vanita5.twittnuker.extension.loadProfileImage import de.vanita5.twittnuker.model.ParcelableUser import de.vanita5.twittnuker.util.LinkCreator import de.vanita5.twittnuker.util.TwidereColorUtils import de.vanita5.twittnuker.util.qr.QrCodeData import org.mariotaku.uniqr.AndroidPlatform import org.mariotaku.uniqr.UniqR import java.lang.ref.WeakReference import java.util.concurrent.ExecutionException /** * Display QR code to user */ class UserQrDialogFragment : BaseDialogFragment() { private val user: ParcelableUser get() = arguments.getParcelable(EXTRA_USER) init { setStyle(STYLE_NO_TITLE, 0) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { return inflater.inflate(R.layout.fragment_user_qr, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val weakThis = WeakReference(this) promiseOnUi { val fragment = weakThis.get()?.takeIf { it.view != null } ?: return@promiseOnUi fragment.qrView.visibility = View.INVISIBLE fragment.qrProgress.visibility = View.VISIBLE } and loadProfileImage().then { drawable -> val fragment = weakThis.get()?.takeIf { it.context != null } ?: throw InterruptedException() val background = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888) val canvas = Canvas(background) drawable.setBounds(0, 0, background.width, background.height) drawable.draw(canvas) val palette = Palette.from(background).generate() val link = LinkCreator.getUserWebLink(fragment.user) val segments = QrSegment.makeSegments(link.toString()) val qrCode = QrCode.encodeSegments(segments, QrCode.Ecc.HIGH, 5, 40, -1, true) val uniqr = UniqR(AndroidPlatform(), background, QrCodeData(qrCode)) uniqr.scale = 3 uniqr.dotSize = 1 uniqr.qrPatternColor = palette.patternColor val result = uniqr.build().produceResult() background.recycle() return@then result }.successUi { bitmap -> val fragment = weakThis.get()?.takeIf { it.context != null && it.view != null } ?: return@successUi fragment.qrView.visibility = View.VISIBLE fragment.qrProgress.visibility = View.GONE fragment.qrView.setImageDrawable(BitmapDrawable(fragment.resources, bitmap).apply { this.setAntiAlias(false) this.isFilterBitmap = false }) }.failUi { val fragment = weakThis.get()?.takeIf { it.dialog != null } ?: return@failUi Toast.makeText(fragment.context, R.string.message_toast_error_occurred, Toast.LENGTH_SHORT).show() fragment.dismiss() } } private fun loadProfileImage(): Promise<GlideDrawable, Exception> { if (context == null || isDetached || dialog == null || (activity?.isFinishing ?: true)) { return Promise.ofFail(InterruptedException()) } val profileImageSize = getString(R.string.profile_image_size) val context = context.applicationContext val requestManager = Glide.with(context) val user = this.user return task { try { return@task requestManager.loadOriginalProfileImage(context, user, 0) .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL).get() } catch (e: ExecutionException) { // Ignore } // Return fallback profile image return@task requestManager.loadProfileImage(context, user, 0, size = profileImageSize) .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL).get() } } companion object { private fun getOptimalPatternColor(color: Int): Int { val yiq = IntArray(3) TwidereColorUtils.colorToYIQ(color, yiq) if (yiq[0] > 96) { yiq[0] = 96 return TwidereColorUtils.YIQToColor(Color.alpha(color), yiq) } return color } private val Palette.patternColor: Int get() { var color = getDarkVibrantColor(0) if (color == 0) { color = getDominantColor(0) } if (color == 0) { color = getDarkMutedColor(0) } if (color == 0) { return Color.BLACK } return getOptimalPatternColor(color) } } }
gpl-3.0
c3bee66a2e7d828ea5109509beb7b623
39.6
115
0.673485
4.471295
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/task/AcceptFriendshipTask.kt
1
3354
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.task import android.content.Context import android.widget.Toast import de.vanita5.microblog.library.MicroBlog import de.vanita5.microblog.library.MicroBlogException import de.vanita5.microblog.library.mastodon.Mastodon import de.vanita5.twittnuker.R import de.vanita5.twittnuker.annotation.AccountType import de.vanita5.twittnuker.constant.nameFirstKey import de.vanita5.twittnuker.extension.model.api.mastodon.toParcelable import de.vanita5.twittnuker.extension.model.api.toParcelable import de.vanita5.twittnuker.extension.model.newMicroBlogInstance import de.vanita5.twittnuker.model.AccountDetails import de.vanita5.twittnuker.model.ParcelableUser import de.vanita5.twittnuker.model.event.FriendshipTaskEvent import de.vanita5.twittnuker.util.Utils class AcceptFriendshipTask(context: Context) : AbsFriendshipOperationTask(context, FriendshipTaskEvent.Action.ACCEPT) { @Throws(MicroBlogException::class) override fun perform(details: AccountDetails, args: Arguments): ParcelableUser { when (details.type) { AccountType.FANFOU -> { val fanfou = details.newMicroBlogInstance(context, MicroBlog::class.java) return fanfou.acceptFanfouFriendship(args.userKey.id).toParcelable(details, profileImageSize = profileImageSize) } AccountType.MASTODON -> { val mastodon = details.newMicroBlogInstance(context, Mastodon::class.java) mastodon.authorizeFollowRequest(args.userKey.id) return mastodon.getAccount(args.userKey.id).toParcelable(details) } else -> { val twitter = details.newMicroBlogInstance(context, MicroBlog::class.java) return twitter.acceptFriendship(args.userKey.id).toParcelable(details, profileImageSize = profileImageSize) } } } override fun succeededWorker(details: AccountDetails, args: Arguments, user: ParcelableUser) { Utils.setLastSeen(context, user.key, System.currentTimeMillis()) } override fun showSucceededMessage(params: AbsFriendshipOperationTask.Arguments, user: ParcelableUser) { val nameFirst = kPreferences[nameFirstKey] Toast.makeText(context, context.getString(R.string.message_toast_accepted_users_follow_request, manager.getDisplayName(user, nameFirst)), Toast.LENGTH_SHORT).show() } }
gpl-3.0
a997f2866e9169a26b3c78099563b5b8
44.337838
119
0.732856
4.557065
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/activity/shortcut/AbsUserListRelatedShortcutCreatorActivity.kt
1
2894
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.activity.shortcut import android.app.Activity import android.content.Intent import android.os.Bundle import org.mariotaku.ktextension.Bundle import org.mariotaku.ktextension.set import de.vanita5.twittnuker.TwittnukerConstants.* import de.vanita5.twittnuker.activity.UserListSelectorActivity import de.vanita5.twittnuker.model.ParcelableUserList import de.vanita5.twittnuker.model.UserKey abstract class AbsUserListRelatedShortcutCreatorActivity : AbsShortcutCreatorActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { when (requestCode) { REQUEST_SELECT_USER_LIST -> { if (resultCode != Activity.RESULT_OK || data == null) { setResult(Activity.RESULT_CANCELED) finish() return } val list = data.getParcelableExtra<ParcelableUserList>(EXTRA_USER_LIST) val extras = data.getBundleExtra(EXTRA_EXTRAS) val accountKey = extras.getParcelable<UserKey>(EXTRA_ACCOUNT_KEY) onUserListSelected(accountKey, list) } else -> { super.onActivityResult(requestCode, resultCode, data) } } } override final fun onAccountSelected(accountKey: UserKey, extras: Bundle?) { val selectUserListIntent = Intent(this, UserListSelectorActivity::class.java) selectUserListIntent.putExtra(EXTRA_ACCOUNT_KEY, accountKey) selectUserListIntent.putExtra(EXTRA_SHOW_MY_LISTS, true) selectUserListIntent.putExtra(EXTRA_EXTRAS, Bundle { this[EXTRA_ACCOUNT_KEY] = accountKey }) startActivityForResult(selectUserListIntent, REQUEST_SELECT_USER_LIST) } protected abstract fun onUserListSelected(accountKey: UserKey?, userList: ParcelableUserList) }
gpl-3.0
e081afdc1d35e2328d88933ca7ac90b5
39.208333
97
0.702488
4.698052
false
false
false
false
alexcustos/linkasanote
app/src/main/java/com/bytesforge/linkasanote/sync/operations/nextcloud/UploadFileOperation.kt
1
6182
/* * LaaNo Android application * * @author Aleksandr Borisenko <[email protected]> * Copyright (C) 2017 Aleksandr Borisenko * * 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.bytesforge.linkasanote.sync.operations.nextcloud import com.bytesforge.linkasanote.data.source.cloud.CloudDataSource import com.bytesforge.linkasanote.sync.files.JsonFile import com.owncloud.android.lib.common.OwnCloudClient import com.owncloud.android.lib.common.network.WebdavUtils import com.owncloud.android.lib.common.operations.RemoteOperation import com.owncloud.android.lib.common.operations.RemoteOperationResult import com.owncloud.android.lib.resources.files.CreateFolderRemoteOperation import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation import com.owncloud.android.lib.resources.files.ReadFileRemoteOperation import com.owncloud.android.lib.resources.files.UploadFileRemoteOperation import com.owncloud.android.lib.resources.files.model.RemoteFile import org.apache.commons.httpclient.Header import org.apache.commons.httpclient.methods.PutMethod import java.io.File class UploadFileOperation(private val file: JsonFile) : RemoteOperation() { override fun run(ocClient: OwnCloudClient): RemoteOperationResult { val localFile = File(file.localPath!!) if (!localFile.exists()) { return RemoteOperationResult(RemoteOperationResult.ResultCode.LOCAL_FILE_NOT_FOUND) } var result = createRemoteParent(file.remotePath!!, ocClient) if (!result.isSuccess) return result val uploadOperation = EnhancedUploadFileRemoteOperation( file.localPath, file.remotePath, file.mimeType ) result = uploadOperation.execute(ocClient) val data = ArrayList<Any>() data.add(file) result.data = data if (result.isSuccess) { val eTag = uploadOperation.getETag() file.eTag = eTag } else { file.eTag = null return RemoteOperationResult(RemoteOperationResult.ResultCode.SYNC_CONFLICT) } return result } private fun createRemoteParent( remotePath: String, ocClient: OwnCloudClient ): RemoteOperationResult { val remoteParent = File(remotePath).parent val existenceOperation = ExistenceCheckRemoteOperation(remoteParent, false) var result = existenceOperation.execute(ocClient) if (result.code == RemoteOperationResult.ResultCode.FILE_NOT_FOUND) { val createOperation = CreateFolderRemoteOperation(remoteParent, true) result = createOperation.execute(ocClient) } return result } private inner class EnhancedUploadFileRemoteOperation( localPath: String?, remotePath: String?, mimeType: String? ) : UploadFileRemoteOperation( localPath, remotePath, mimeType, java.lang.Long.toString( System.currentTimeMillis() / 1000 ) ) { private var ocClient: OwnCloudClient? = null private var fileId: String? = null private var eTag: String? = null fun getETag(): String? { if (eTag != null) return eTag requestNextcloudFileAttributes() return eTag } fun getFileId(): String? { if (fileId != null) return fileId requestNextcloudFileAttributes() return fileId } private fun requestNextcloudFileAttributes() { val operation = ReadFileRemoteOperation(remotePath) val result = CloudDataSource.executeRemoteOperation(operation, ocClient!!) .blockingGet() if (result.isSuccess) { val file = result.data[0] as RemoteFile fileId = file.remoteId eTag = file.etag } } override fun execute(ocClient: OwnCloudClient): RemoteOperationResult { this.ocClient = ocClient val result = super.execute(ocClient) // TODO: make sure this replacement of this.putMethod is working well val putMethod = PutMethod( ocClient.webdavUri.toString() + WebdavUtils.encodePath( remotePath ) ) val nextcloudHeaders = extractNextcloudResponseHeaders(putMethod.responseHeaders) if (nextcloudHeaders != null) { fileId = nextcloudHeaders[NEXTCLOUD_FILE_ID_HEADER] eTag = nextcloudHeaders[NEXTCLOUD_E_TAG_HEADER] } return result } private fun extractNextcloudResponseHeaders(headers: Array<Header>?): Map<String, String>? { if (headers == null) return null val nextcloudHeaders: MutableMap<String, String> = HashMap() for (header in headers) { val name = header.name.toLowerCase() if (name.startsWith(NEXTCLOUD_HEADER_PREFIX)) { val value = header.value.replace("^\"|\"$".toRegex(), "") nextcloudHeaders[name] = value } } return if (nextcloudHeaders.isEmpty()) null else nextcloudHeaders } } companion object { private val TAG = UploadFileOperation::class.java.simpleName private val NEXTCLOUD_HEADER_PREFIX = "OC-".toLowerCase() private val NEXTCLOUD_FILE_ID_HEADER = NEXTCLOUD_HEADER_PREFIX + "FileId".toLowerCase() private val NEXTCLOUD_E_TAG_HEADER = NEXTCLOUD_HEADER_PREFIX + "ETag".toLowerCase() } }
gpl-3.0
973a1d9db729ba5a57db614ab2c2451c
41.061224
100
0.666451
5.021933
false
false
false
false
AlexLandau/semlang
kotlin/semlang-test-utils/src/main/kotlin/moduleEquality.kt
1
6439
package net.semlang.internal.test import net.semlang.api.* import net.semlang.api.Function import org.junit.Assert fun assertModulesEqual(expected: ValidatedModule, actual: ValidatedModule) { // TODO: Check the upstream contexts Assert.assertEquals(expected.ownFunctions, actual.ownFunctions) Assert.assertEquals(expected.ownStructs, actual.ownStructs) Assert.assertEquals(expected.ownUnions, actual.ownUnions) // TODO: Maybe check more? } fun assertRawContextsEqual(expected: RawContext, actual: RawContext) { // TODO: Check the upstream contexts Assert.assertEquals(expected.functions.map(::stripLocations), actual.functions.map(::stripLocations)) Assert.assertEquals(expected.structs.map(::stripLocations), actual.structs.map(::stripLocations)) Assert.assertEquals(expected.unions.map(::stripLocations), actual.unions.map(::stripLocations)) } private fun stripLocations(function: Function): Function { val arguments = function.arguments.map(::stripLocations) val block = stripLocations(function.block) val returnType = stripLocations(function.returnType) return Function(function.id, function.typeParameters, arguments, returnType, block, function.annotations) } private fun stripLocations(type: UnvalidatedType): UnvalidatedType { return when (type) { is UnvalidatedType.FunctionType -> { val typeParameters = type.typeParameters val argTypes = type.argTypes.map(::stripLocations) val outputType = stripLocations(type.outputType) UnvalidatedType.FunctionType(type.isReference(), typeParameters, argTypes, outputType) } is UnvalidatedType.NamedType -> { val parameters = type.parameters.map(::stripLocations) UnvalidatedType.NamedType(type.ref, type.isReference(), parameters) } } } private fun stripLocations(block: Block): Block { val statements = block.statements.map(::stripLocations) return Block(statements) } private fun stripLocations(statement: Statement): Statement { return when (statement) { is Statement.Assignment -> { val type = statement.type?.let(::stripLocations) val expression = stripLocations(statement.expression) Statement.Assignment(statement.name, type, expression) } is Statement.Bare -> { Statement.Bare(stripLocations(statement.expression)) } } } private fun stripLocations(expression: Expression): Expression { return when (expression) { is Expression.Variable -> { Expression.Variable(expression.name) } is Expression.IfThen -> { val condition = stripLocations(expression.condition) val thenBlock = stripLocations(expression.thenBlock) val elseBlock = stripLocations(expression.elseBlock) Expression.IfThen(condition, thenBlock, elseBlock) } is Expression.NamedFunctionCall -> { val arguments = expression.arguments.map(::stripLocations) val chosenParameters = expression.chosenParameters.map(::stripLocations) Expression.NamedFunctionCall(expression.functionRef, arguments, chosenParameters) } is Expression.ExpressionFunctionCall -> { val functionExpression = stripLocations(expression.functionExpression) val arguments = expression.arguments.map(::stripLocations) val chosenParameters = expression.chosenParameters.map(::stripLocations) Expression.ExpressionFunctionCall(functionExpression, arguments, chosenParameters) } is Expression.Literal -> { val type = stripLocations(expression.type) Expression.Literal(type, expression.literal) } is Expression.ListLiteral -> { val contents = expression.contents.map(::stripLocations) val chosenParameter = stripLocations(expression.chosenParameter) Expression.ListLiteral(contents, chosenParameter) } is Expression.NamedFunctionBinding -> { val bindings = expression.bindings.map { if (it == null) null else stripLocations(it) } val chosenParameters = expression.chosenParameters.map { if (it == null) null else stripLocations(it) } Expression.NamedFunctionBinding(expression.functionRef, bindings, chosenParameters) } is Expression.ExpressionFunctionBinding -> { val functionExpression = stripLocations(expression.functionExpression) val bindings = expression.bindings.map { if (it == null) null else stripLocations(it) } val chosenParameters = expression.chosenParameters.map { if (it == null) null else stripLocations(it) } Expression.ExpressionFunctionBinding(functionExpression, bindings, chosenParameters) } is Expression.Follow -> { val structureExpression = stripLocations(expression.structureExpression) Expression.Follow(structureExpression, expression.name) } is Expression.InlineFunction -> { val arguments = expression.arguments.map(::stripLocations) val returnType = stripLocations(expression.returnType) val block = stripLocations(expression.block) Expression.InlineFunction(arguments, returnType, block) } } } private fun stripLocations(argument: UnvalidatedArgument): UnvalidatedArgument { val type = stripLocations(argument.type) return UnvalidatedArgument(argument.name, type) } private fun stripLocations(struct: UnvalidatedStruct): UnvalidatedStruct { val requires = struct.requires?.let(::stripLocations) val members = struct.members.map(::stripLocations) return UnvalidatedStruct(struct.id, struct.typeParameters, members, requires, struct.annotations) } private fun stripLocations(member: UnvalidatedMember): UnvalidatedMember { val type = stripLocations(member.type) return UnvalidatedMember(member.name, type) } private fun stripLocations(union: UnvalidatedUnion): UnvalidatedUnion { val options = union.options.map(::stripLocations) return UnvalidatedUnion(union.id, union.typeParameters, options, union.annotations) } private fun stripLocations(option: UnvalidatedOption): UnvalidatedOption { val type = option.type?.let(::stripLocations) return UnvalidatedOption(option.name, type) }
apache-2.0
6d18cd5b7e26abc52fb3a4b32ddda458
44.027972
115
0.707874
5.321488
false
false
false
false
AndroidX/androidx
work/work-runtime/src/main/java/androidx/work/impl/model/WorkSpecDao.kt
3
13649
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.work.impl.model import android.annotation.SuppressLint import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Transaction import androidx.room.Update import androidx.work.Data import androidx.work.WorkInfo import androidx.work.impl.model.WorkTypeConverters.StateIds.COMPLETED_STATES import androidx.work.impl.model.WorkTypeConverters.StateIds.ENQUEUED /** * The Data Access Object for [WorkSpec]s. */ @Dao @SuppressLint("UnknownNullness") interface WorkSpecDao { /** * Attempts to insert a [WorkSpec] into the database. * * @param workSpec The WorkSpec to insert. */ @Insert(onConflict = OnConflictStrategy.IGNORE) fun insertWorkSpec(workSpec: WorkSpec) /** * Deletes [WorkSpec]s from the database. * * @param id The WorkSpec id to delete. */ @Query("DELETE FROM workspec WHERE id=:id") fun delete(id: String) /** * @param id The identifier * @return The WorkSpec associated with that id */ @Query("SELECT * FROM workspec WHERE id=:id") fun getWorkSpec(id: String): WorkSpec? /** * * @param name The work graph name * @return The [WorkSpec]s labelled with the given name */ @Query( "SELECT id, state FROM workspec WHERE id IN " + "(SELECT work_spec_id FROM workname WHERE name=:name)" ) fun getWorkSpecIdAndStatesForName(name: String): List<WorkSpec.IdAndState> /** * @return All WorkSpec ids in the database. */ @Query("SELECT id FROM workspec") fun getAllWorkSpecIds(): List<String> /** * @return A [LiveData] list of all WorkSpec ids in the database. */ @Transaction @Query("SELECT id FROM workspec") fun getAllWorkSpecIdsLiveData(): LiveData<List<String>> /** * Updates the state of at least one [WorkSpec] by ID. * * @param state The new state * @param id The IDs for the [WorkSpec]s to update * @return The number of rows that were updated */ @Query("UPDATE workspec SET state=:state WHERE id=:id") fun setState(state: WorkInfo.State, id: String): Int /** * Increment periodic counter. */ @Query("UPDATE workspec SET period_count=period_count+1 WHERE id=:id") fun incrementPeriodCount(id: String) /** * Updates the output of a [WorkSpec]. * * @param id The [WorkSpec] identifier to update * @param output The [Data] to set as the output */ @Query("UPDATE workspec SET output=:output WHERE id=:id") fun setOutput(id: String, output: Data) /** * Updates the period start time of a [WorkSpec]. * * @param id The [WorkSpec] identifier to update * @param enqueueTime The time when the period started. */ @Query("UPDATE workspec SET last_enqueue_time=:enqueueTime WHERE id=:id") fun setLastEnqueuedTime(id: String, enqueueTime: Long) /** * Increment run attempt count of a [WorkSpec]. * * @param id The identifier for the [WorkSpec] * @return The number of rows that were updated (should be 0 or 1) */ @Query("UPDATE workspec SET run_attempt_count=run_attempt_count+1 WHERE id=:id") fun incrementWorkSpecRunAttemptCount(id: String): Int /** * Reset run attempt count of a [WorkSpec]. * * @param id The identifier for the [WorkSpec] * @return The number of rows that were updated (should be 0 or 1) */ @Query("UPDATE workspec SET run_attempt_count=0 WHERE id=:id") fun resetWorkSpecRunAttemptCount(id: String): Int /** * Retrieves the state of a [WorkSpec]. * * @param id The identifier for the [WorkSpec] * @return The state of the [WorkSpec] */ @Query("SELECT state FROM workspec WHERE id=:id") fun getState(id: String): WorkInfo.State? /** * For a [WorkSpec] identifier, retrieves its [WorkSpec.WorkInfoPojo]. * * @param id The identifier of the [WorkSpec] * @return A list of [WorkSpec.WorkInfoPojo] */ @Transaction @Query("SELECT id, state, output, run_attempt_count, generation FROM workspec WHERE id=:id") fun getWorkStatusPojoForId(id: String): WorkSpec.WorkInfoPojo? /** * For a list of [WorkSpec] identifiers, retrieves a [List] of their * [WorkSpec.WorkInfoPojo]. * * @param ids The identifier of the [WorkSpec]s * @return A [List] of [WorkSpec.WorkInfoPojo] */ @Transaction @Query("SELECT id, state, output, run_attempt_count, generation " + "FROM workspec WHERE id IN (:ids)") fun getWorkStatusPojoForIds(ids: List<String>): List<WorkSpec.WorkInfoPojo> /** * For a list of [WorkSpec] identifiers, retrieves a [LiveData] list of their * [WorkSpec.WorkInfoPojo]. * * @param ids The identifier of the [WorkSpec]s * @return A [LiveData] list of [WorkSpec.WorkInfoPojo] */ @Transaction @Query("SELECT id, state, output, run_attempt_count, generation " + "FROM workspec WHERE id IN (:ids)") fun getWorkStatusPojoLiveDataForIds(ids: List<String>): LiveData<List<WorkSpec.WorkInfoPojo>> /** * Retrieves a list of [WorkSpec.WorkInfoPojo] for all work with a given tag. * * @param tag The tag for the [WorkSpec]s * @return A list of [WorkSpec.WorkInfoPojo] */ @Transaction @Query( """SELECT id, state, output, run_attempt_count, generation FROM workspec WHERE id IN (SELECT work_spec_id FROM worktag WHERE tag=:tag)""" ) fun getWorkStatusPojoForTag(tag: String): List<WorkSpec.WorkInfoPojo> /** * Retrieves a [LiveData] list of [WorkSpec.WorkInfoPojo] for all work with a * given tag. * * @param tag The tag for the [WorkSpec]s * @return A [LiveData] list of [WorkSpec.WorkInfoPojo] */ @Transaction @Query( """SELECT id, state, output, run_attempt_count, generation FROM workspec WHERE id IN (SELECT work_spec_id FROM worktag WHERE tag=:tag)""" ) fun getWorkStatusPojoLiveDataForTag(tag: String): LiveData<List<WorkSpec.WorkInfoPojo>> /** * Retrieves a list of [WorkSpec.WorkInfoPojo] for all work with a given name. * * @param name The name of the [WorkSpec]s * @return A list of [WorkSpec.WorkInfoPojo] */ @Transaction @Query( "SELECT id, state, output, run_attempt_count, generation FROM workspec WHERE id IN " + "(SELECT work_spec_id FROM workname WHERE name=:name)" ) fun getWorkStatusPojoForName(name: String): List<WorkSpec.WorkInfoPojo> /** * Retrieves a [LiveData] list of [WorkSpec.WorkInfoPojo] for all work with a * given name. * * @param name The name for the [WorkSpec]s * @return A [LiveData] list of [WorkSpec.WorkInfoPojo] */ @Transaction @Query( "SELECT id, state, output, run_attempt_count, generation FROM workspec WHERE id IN " + "(SELECT work_spec_id FROM workname WHERE name=:name)" ) fun getWorkStatusPojoLiveDataForName(name: String): LiveData<List<WorkSpec.WorkInfoPojo>> /** * Gets all inputs coming from prerequisites for a particular [WorkSpec]. These are * [Data] set via `Worker#setOutputData()`. * * @param id The [WorkSpec] identifier * @return A list of all inputs coming from prerequisites for `id` */ @Query( """SELECT output FROM workspec WHERE id IN (SELECT prerequisite_id FROM dependency WHERE work_spec_id=:id)""" ) fun getInputsFromPrerequisites(id: String): List<Data> /** * Retrieves work ids for unfinished work with a given tag. * * @param tag The tag used to identify the work * @return A list of work ids */ @Query( "SELECT id FROM workspec WHERE state NOT IN " + COMPLETED_STATES + " AND id IN (SELECT work_spec_id FROM worktag WHERE tag=:tag)" ) fun getUnfinishedWorkWithTag(tag: String): List<String> /** * Retrieves work ids for unfinished work with a given name. * * @param name THe tag used to identify the work * @return A list of work ids */ @Query( "SELECT id FROM workspec WHERE state NOT IN " + COMPLETED_STATES + " AND id IN (SELECT work_spec_id FROM workname WHERE name=:name)" ) fun getUnfinishedWorkWithName(name: String): List<String> /** * Retrieves work ids for all unfinished work. * * @return A list of work ids */ @Query("SELECT id FROM workspec WHERE state NOT IN " + COMPLETED_STATES) fun getAllUnfinishedWork(): List<String> /** * @return `true` if there is pending work. */ @Query("SELECT COUNT(*) > 0 FROM workspec WHERE state NOT IN $COMPLETED_STATES LIMIT 1") fun hasUnfinishedWork(): Boolean /** * Marks a [WorkSpec] as scheduled. * * @param id The identifier for the [WorkSpec] * @param startTime The time at which the [WorkSpec] was scheduled. * @return The number of rows that were updated (should be 0 or 1) */ @Query("UPDATE workspec SET schedule_requested_at=:startTime WHERE id=:id") fun markWorkSpecScheduled(id: String, startTime: Long): Int /** * @return The time at which the [WorkSpec] was scheduled. */ @Query("SELECT schedule_requested_at FROM workspec WHERE id=:id") fun getScheduleRequestedAtLiveData(id: String): LiveData<Long> /** * Resets the scheduled state on the [WorkSpec]s that are not in a a completed state. * @return The number of rows that were updated */ @Query( "UPDATE workspec SET schedule_requested_at=" + WorkSpec.SCHEDULE_NOT_REQUESTED_YET + " WHERE state NOT IN " + COMPLETED_STATES ) fun resetScheduledState(): Int /** * @return The List of [WorkSpec]s that are eligible to be scheduled. */ @Query( "SELECT * FROM workspec WHERE " + "state=" + ENQUEUED + // We only want WorkSpecs which have not been previously scheduled. " AND schedule_requested_at=" + WorkSpec.SCHEDULE_NOT_REQUESTED_YET + // Order by period start time so we execute scheduled WorkSpecs in FIFO order " ORDER BY last_enqueue_time" + " LIMIT " + "(SELECT MAX(:schedulerLimit" + "-COUNT(*), 0) FROM workspec WHERE" + " schedule_requested_at<>" + WorkSpec.SCHEDULE_NOT_REQUESTED_YET + " AND state NOT IN " + COMPLETED_STATES + ")" ) fun getEligibleWorkForScheduling(schedulerLimit: Int): List<WorkSpec> /** * @return The List of [WorkSpec]s that can be scheduled irrespective of scheduling * limits. */ @Query( "SELECT * FROM workspec WHERE " + "state=$ENQUEUED" + // Order by period start time so we execute scheduled WorkSpecs in FIFO order " ORDER BY last_enqueue_time" + " LIMIT :maxLimit" ) fun getAllEligibleWorkSpecsForScheduling(maxLimit: Int): List<WorkSpec> // Unfinished work // We only want WorkSpecs which have been scheduled. /** * @return The List of [WorkSpec]s that are unfinished and scheduled. */ @Query( "SELECT * FROM workspec WHERE " + // Unfinished work "state=" + ENQUEUED + // We only want WorkSpecs which have been scheduled. " AND schedule_requested_at<>" + WorkSpec.SCHEDULE_NOT_REQUESTED_YET ) fun getScheduledWork(): List<WorkSpec> /** * @return The List of [WorkSpec]s that are running. */ @Query( "SELECT * FROM workspec WHERE " + // Unfinished work "state=" + WorkTypeConverters.StateIds.RUNNING ) fun getRunningWork(): List<WorkSpec> /** * @return The List of [WorkSpec] which completed recently. */ @Query( "SELECT * FROM workspec WHERE " + "last_enqueue_time >= :startingAt" + " AND state IN " + COMPLETED_STATES + " ORDER BY last_enqueue_time DESC" ) fun getRecentlyCompletedWork(startingAt: Long): List<WorkSpec> /** * Immediately prunes eligible work from the database meeting the following criteria: * - Is finished (succeeded, failed, or cancelled) * - Has zero unfinished dependents */ @Query( "DELETE FROM workspec WHERE " + "state IN " + COMPLETED_STATES + " AND (SELECT COUNT(*)=0 FROM dependency WHERE " + " prerequisite_id=id AND " + " work_spec_id NOT IN " + " (SELECT id FROM workspec WHERE state IN " + COMPLETED_STATES + "))" ) fun pruneFinishedWorkWithZeroDependentsIgnoringKeepForAtLeast() @Query("UPDATE workspec SET generation=generation+1 WHERE id=:id") fun incrementGeneration(id: String) @Update fun updateWorkSpec(workSpec: WorkSpec) }
apache-2.0
5b72fb5087caaad09580ad953e963e22
34
97
0.642391
4.270651
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/refactoring/inlineValue/RsInlineValueHandler.kt
2
5289
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.refactoring.inlineValue import com.intellij.codeInsight.TargetElementUtil import com.intellij.lang.Language import com.intellij.lang.refactoring.InlineActionHandler import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsContexts.DialogMessage import com.intellij.openapi.wm.WindowManager import com.intellij.psi.PsiElement import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.util.CommonRefactoringUtil import org.jetbrains.annotations.TestOnly import org.rust.lang.RsLanguage import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.RsNameIdentifierOwner import org.rust.lang.core.psi.ext.ancestorOrSelf import org.rust.lang.core.resolve.ref.RsReference import org.rust.openapiext.isUnitTestMode class RsInlineValueHandler : InlineActionHandler() { override fun isEnabledForLanguage(language: Language): Boolean = language is RsLanguage override fun inlineElement(project: Project, editor: Editor, element: PsiElement) { var reference = TargetElementUtil.findReference(editor, editor.caretModel.offset) as? RsReference // if invoked directly on the target value, ignore the reference if (reference?.element == element) { reference = null } val context = getContext(project, editor, element, reference) ?: return val dialog = RsInlineValueDialog(context) if (!isUnitTestMode) { dialog.show() if (!dialog.isOK) { val statusBar = WindowManager.getInstance().getStatusBar(project) statusBar?.info = RefactoringBundle.message("press.escape.to.remove.the.highlighting") } } else { val processor = getProcessor(project, context) processor.setPreviewUsages(false) processor.run() } } override fun canInlineElement(element: PsiElement): Boolean { return (element is RsConstant && element.navigationElement is RsConstant) || (element is RsPatBinding && element.navigationElement is RsPatBinding) } } private var MOCK: InlineValueMode? = null @TestOnly fun withMockInlineValueMode(mock: InlineValueMode, action: () -> Unit) { MOCK = mock try { action() } finally { MOCK = null } } private fun getProcessor(project: Project, context: InlineValueContext): RsInlineValueProcessor { val mode = if (isUnitTestMode && MOCK != null) { MOCK!! } else { InlineValueMode.InlineAllAndRemoveOriginal } return RsInlineValueProcessor( project, context, mode ) } private fun getContext( project: Project, editor: Editor, element: PsiElement, reference: RsReference? ): InlineValueContext? = getVariableDeclContext(project, editor, element, reference) ?: getConstantContext(project, editor, element, reference) private fun getConstantContext( project: Project, editor: Editor, element: PsiElement, reference: RsReference? ): InlineValueContext? { val const = element as? RsConstant ?: return null val expr = const.expr if (expr == null) { showErrorHint(project, editor, "cannot inline constant without an expression") return null } return InlineValueContext.Constant(const, expr, reference) } private fun getVariableDeclContext( project: Project, editor: Editor, element: PsiElement, reference: RsReference? ): InlineValueContext? { val binding = element as? RsPatBinding ?: return null val decl = binding.ancestorOrSelf<RsLetDecl>() val expr = decl?.expr if (expr == null) { showErrorHint(project, editor, "cannot inline variable without an expression") return null } if (decl.pat !is RsPatIdent) { showErrorHint(project, editor, "cannot inline variable without an identifier") return null } return InlineValueContext.Variable(binding, decl, expr, reference) } sealed class InlineValueContext(val element: RsNameIdentifierOwner, val expr: RsExpr, val reference: RsReference?) { abstract fun delete() class Constant(constant: RsConstant, expr: RsExpr, reference: RsReference? = null) : InlineValueContext(constant, expr, reference) { override fun delete() { element.delete() } } class Variable(variable: RsPatBinding, private val decl: RsLetDecl, expr: RsExpr, reference: RsReference? = null) : InlineValueContext(variable, expr, reference) { override fun delete() { decl.delete() } } } sealed class InlineValueMode { object InlineThisOnly : InlineValueMode() object InlineAllAndKeepOriginal : InlineValueMode() object InlineAllAndRemoveOriginal : InlineValueMode() } private fun showErrorHint(project: Project, editor: Editor, @Suppress("UnstableApiUsage") @DialogMessage message: String) { CommonRefactoringUtil.showErrorHint( project, editor, message, RefactoringBundle.message("inline.variable.title"), "refactoring.inline" ) }
mit
c00e2aba07c4d49c59ec00f8fd13c4fc
32.05625
123
0.699187
4.777778
false
false
false
false
TeamWizardry/LibrarianLib
modules/core/src/main/kotlin/com/teamwizardry/librarianlib/math/BlockPos.kt
1
1334
package com.teamwizardry.librarianlib.math import com.teamwizardry.librarianlib.core.util.block import net.minecraft.util.math.BlockPos @JvmSynthetic public operator fun BlockPos.plus(other: BlockPos): BlockPos = block(this.x + other.x, this.y + other.y, this.z + other.z) @JvmSynthetic public operator fun BlockPos.minus(other: BlockPos): BlockPos = block(this.x - other.x, this.y - other.y, this.z - other.z) @JvmSynthetic public operator fun BlockPos.times(other: BlockPos): BlockPos = block(this.x * other.x, this.y * other.y, this.z * other.z) @JvmSynthetic public operator fun BlockPos.div(other: BlockPos): BlockPos = block(this.x / other.x, this.y / other.y, this.z / other.z) @JvmSynthetic public operator fun BlockPos.div(other: Int): BlockPos = block(this.x / other, this.y / other, this.z / other) @JvmSynthetic public operator fun BlockPos.times(other: Int): BlockPos = block(this.x * other, this.y * other, this.z * other) @JvmSynthetic public operator fun BlockPos.unaryMinus(): BlockPos = this * -1 @JvmSynthetic public infix fun BlockPos.cross(other: BlockPos): BlockPos = this.crossProduct(other) @JvmSynthetic public operator fun BlockPos.component1(): Int = this.x @JvmSynthetic public operator fun BlockPos.component2(): Int = this.y @JvmSynthetic public operator fun BlockPos.component3(): Int = this.z
lgpl-3.0
d3ecb6e57bb61316176cb59b11888ee2
38.235294
123
0.756372
3.519789
false
false
false
false
dizitart/nitrite-database
potassium-nitrite/src/main/kotlin/org/dizitart/kno2/Builder.kt
1
5515
/* * * Copyright 2017-2018 Nitrite 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.dizitart.kno2 import com.fasterxml.jackson.databind.Module import org.dizitart.no2.Nitrite import org.dizitart.no2.NitriteBuilder import org.dizitart.no2.fulltext.TextIndexingService import org.dizitart.no2.fulltext.TextTokenizer import org.dizitart.no2.mapper.NitriteMapper import java.io.File /** * A builder to create a nitrite database. * * @since 2.1.0 * @author Anindya Chatterjee */ class Builder internal constructor() { private val jacksonModules = mutableSetOf<Module>() /** * Path for the file based store. */ var path: String? = null /** * [File] for the file based store. */ var file: File? = null /** * The size of the write buffer, in KB disk space (for file-based * stores). Unless auto-commit is disabled, changes are automatically * saved if there are more than this amount of changes. * * When the values is set to 0 or lower, it will assume the default value * - 1024 KB. */ var autoCommitBufferSize: Int = 0 /** * Opens the file in read-only mode. In this case, a shared lock will be * acquired to ensure the file is not concurrently opened in write mode. * * If this option is not used, the file is locked exclusively. */ var readOnly: Boolean = false /** * Compresses data before writing using the LZF algorithm. This will save * about 50% of the disk space, but will slow down read and write * operations slightly. */ var compress: Boolean = false /** * Enables auto commit. If disabled, unsaved changes will not be written * into disk until {@link Nitrite#commit()} is called. */ var autoCommit = true /** * Enables auto compact before close. If disabled, compaction will not * be performed. Disabling would increase close performance. */ var autoCompact = true /** * Specifies a custom [TextIndexingService] implementation to be used * during full text indexing and full text search. If not set, the default * text indexer will be used. */ var textIndexingService: TextIndexingService? = null /** * Specifies a custom [TextTokenizer] for the in-built [TextIndexingService]. * If not set, a default text tokenizer [org.dizitart.no2.fulltext.EnglishTextTokenizer] * is used. The default tokenizer works on english language only. */ var textTokenizer: TextTokenizer? = null /** * Specifies a custom [NitriteMapper] implementation. If not set, a default * jackson based mapper [KNO2JacksonMapper] will be used. */ var nitriteMapper: NitriteMapper? = null /** * Disables JVM shutdown hook for closing the database gracefully. * */ var disableShutdownHook: Boolean = false /** * Registers a jackson [Module] to the [KNO2JacksonFacade] * * @param [module] jackson [Module] to register * */ fun registerModule(module: Module) { jacksonModules.add(module) } internal fun createNitriteBuilder() : NitriteBuilder { val builder = Nitrite.builder() if (file != null) { builder.filePath(file) } else { builder.filePath(path) } builder.autoCommitBufferSize(autoCommitBufferSize) builder.textIndexingService(textIndexingService) builder.textTokenizer(textTokenizer) if (nitriteMapper == null) { nitriteMapper = if (jacksonModules.isEmpty()) { KNO2JacksonMapper() } else { KNO2JacksonMapper(jacksonModules) } } builder.nitriteMapper(nitriteMapper) if (readOnly) builder.readOnly() if (compress) builder.compressed() if (!autoCommit) builder.disableAutoCommit() if (!autoCompact) builder.disableAutoCompact() if (disableShutdownHook) builder.disableShutdownHook() if (jacksonModules.isNotEmpty()) { jacksonModules.forEach { builder.registerModule(it) } } return builder } } /** * Opens or creates a new database. If it is an in-memory store, then it * will create a new one. If it is a file based store, and if the file does not * exists, then it will create a new file store and open; otherwise it will * open the existing file store. * * @param [userId] the user id * @param [password] the password * @return the nitrite database instance. */ fun nitrite(userId: String? = null, password: String? = null, op: (Builder.() -> Unit)? = null) : Nitrite { val builder = Builder() op?.invoke(builder) val nitriteBuilder = builder.createNitriteBuilder() return if (userId.isNullOrEmpty() && password.isNullOrEmpty()) { nitriteBuilder.openOrCreate() } else { nitriteBuilder.openOrCreate(userId, password) } }
apache-2.0
8780c3cbf498350a95f5b7d0e000cde9
31.069767
92
0.662738
4.373513
false
false
false
false
androidx/androidx
work/work-lint/src/main/java/androidx/work/lint/WorkManagerIssueRegistry.kt
3
1736
/* * 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. */ @file:Suppress("UnstableApiUsage") package androidx.work.lint import com.android.tools.lint.client.api.IssueRegistry import com.android.tools.lint.client.api.Vendor import com.android.tools.lint.detector.api.CURRENT_API import com.android.tools.lint.detector.api.Issue class WorkManagerIssueRegistry : IssueRegistry() { override val minApi = CURRENT_API override val api = 13 override val issues: List<Issue> = listOf( BadConfigurationProviderIssueDetector.ISSUE, IdleBatteryChargingConstraintsDetector.ISSUE, InvalidPeriodicWorkRequestIntervalDetector.ISSUE, PeriodicEnqueueIssueDetector.ISSUE, RemoveWorkManagerInitializerDetector.ISSUE, RxWorkerSetProgressDetector.ISSUE, SpecifyForegroundServiceTypeIssueDetector.ISSUE, SpecifyJobSchedulerIdRangeIssueDetector.ISSUE, WorkerHasPublicModifierDetector.ISSUE ) override val vendor = Vendor( feedbackUrl = "https://issuetracker.google.com/issues/new?component=409906", identifier = "androidx.work", vendorName = "Android Open Source Project", ) }
apache-2.0
48f41ae56ee760d3284f7e73ceb7b46e
37.577778
84
0.75
4.520833
false
false
false
false
cat-in-the-dark/GamesServer
lib-shared/src/main/kotlin/org/catinthedark/shared/route_machine/RouteMachine.kt
1
1221
package org.catinthedark.shared.route_machine import org.slf4j.LoggerFactory class RouteMachine { private val log = LoggerFactory.getLogger(RouteMachine::class.java) private val routes: MutableMap<YieldUnit<*, *>, (Any) -> YieldUnit<Any, *>> = hashMapOf() private lateinit var current: YieldUnit<*, *> fun <T> start(unit: YieldUnit<T, Any>, data: T) { current = unit unit.onActivate(data) } /** * Stops current unit */ fun exit() { current.onExit() } fun run(delta: Float) { val data = current.run(delta) if (data != null) { doRoute(data) } } @Suppress("UNCHECKED_CAST") fun <T> addRoute(from: YieldUnit<*, T>, routeFn: (T) -> YieldUnit<T, *>) { routes.put(from as YieldUnit<*, *>, routeFn as (Any) -> YieldUnit<Any, *>) } private fun doRoute(data: Any) { val from = current log.info("Begin transition from $from") from.onExit() val routeFn = routes[from] ?: throw Exception("Could not find route function from $from") val to = routeFn(data) to.onActivate(data) log.info("End transition to $to") current = to } }
mit
556a95b6c58d6de1a02f488492ac5f4b
26.772727
97
0.58231
3.888535
false
false
false
false
inorichi/tachiyomi-extensions
multisrc/overrides/foolslide/hniscantrad/src/HNIScantradFactory.kt
1
2272
package eu.kanade.tachiyomi.extension.all.hniscantrad import eu.kanade.tachiyomi.multisrc.foolslide.FoolSlide import eu.kanade.tachiyomi.source.Source import eu.kanade.tachiyomi.source.SourceFactory import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Element class HNIScantradFactory : SourceFactory { override fun createSources(): List<Source> = listOf( HNIScantradFR(), HNIScantradEN(), ) } class HNIScantradFR : FoolSlide("HNI-Scantrad", "https://hni-scantrad.com", "fr", "/lel") class HNIScantradEN : FoolSlide("HNI-Scantrad", "https://hni-scantrad.com", "en", "/eng/lel") { override val supportsLatest = false override fun popularMangaRequest(page: Int) = GET(baseUrl + urlModifier, headers) override fun popularMangaSelector() = "div.listed" override fun popularMangaFromElement(element: Element): SManga { return SManga.create().apply { element.select("a:has(h3)").let { title = it.text() setUrlWithoutDomain(it.attr("abs:href")) } thumbnail_url = element.select("img").attr("abs:src") } } override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request = GET("$baseUrl$urlModifier/?manga=${query.replace(" ", "+")}") override fun searchMangaSelector(): String = popularMangaSelector() override fun searchMangaFromElement(element: Element): SManga = popularMangaFromElement(element) override fun chapterListSelector() = "div.theList > a" override fun chapterFromElement(element: Element): SChapter { return SChapter.create().apply { name = element.select("div.chapter b").text() setUrlWithoutDomain(element.attr("abs:href")) } } override fun pageListParse(response: Response): List<Page> { return Regex("""imageArray\[\d+]='(.*)'""").findAll(response.body!!.string()).toList().mapIndexed { i, mr -> Page(i, "", "$baseUrl$urlModifier/${mr.groupValues[1]}") } } }
apache-2.0
e264abc9b77a8e159c7dccf36b136b73
44.44
155
0.689261
4.19963
false
false
false
false
elect86/jAssimp
src/main/kotlin/assimp/sceneCombiner.kt
2
36182
/* Open Asset Import Library (assimp) ---------------------------------------------------------------------- Copyright (c) 2006-2017, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------- */ package assimp import gli_.Texture import gli_.has import kotlin.reflect.KMutableProperty0 import assimp.AI_INT_MERGE_SCENE as Ms /** @brief Helper data structure for SceneCombiner. * * Describes to which node a scene must be attached to. */ class AttachmentInfo(var scene: AiScene? = null, var attachToNode: AiNode? = null) class NodeAttachmentInfo(var node: AiNode? = null, var attachToNode: AiNode? = null, var srcIdx: Int = Int.MAX_VALUE) { var resolved = false } object AI_INT_MERGE_SCENE { object GEN { /** @def AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES * Generate unique names for all named scene items */ val UNIQUE_NAMES = 0x1 /** @def AI_INT_MERGE_SCENE_GEN_UNIQUE_MATNAMES * Generate unique names for materials, too. * This is not absolutely required to pass the validation. */ val UNIQUE_MATNAMES = 0x2 /** @def AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY * Can be combined with AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES. * Unique names are generated, but only if this is absolutely required to avoid name conflicts. */ val UNIQUE_NAMES_IF_NECESSARY = 0x10 } /** @def AI_INT_MERGE_SCENE_DUPLICATES_DEEP_CPY * Use deep copies of duplicate scenes */ val DUPLICATES_DEEP_CPY = 0x4 /** @def AI_INT_MERGE_SCENE_RESOLVE_CROSS_ATTACHMENTS * If attachment nodes are not found in the given master scene, search the other imported scenes for them in an any order. */ val RESOLVE_CROSS_ATTACHMENTS = 0x8 } // typedef std::pair<aiBone*,unsigned int> BoneSrcIndex; /** @brief Helper data structure for SceneCombiner::MergeBones. */ class BoneWithHash(var first: Int = 0, var second: String = "") { val srcBones = ArrayList<Pair<AiBone, Int>>() } /** @brief Utility for SceneCombiner */ class SceneHelper( /** scene we're working on */ var scene: AiScene? = null) { /** prefix to be added to all identifiers in the scene ... */ var id = "" /** hash table to quickly check whether a name is contained in the scene */ val hashes = hashSetOf<Int>() operator fun invoke() = scene!! } /** @brief Static helper class providing various utilities to merge two scenes. It is intended as internal utility and * NOT for use by applications. * * The class is currently being used by various postprocessing steps and loaders (ie. LWS). */ object SceneCombiner { /** Merges two or more scenes. * * @return Receives a pointer to the destination scene. If the pointer doesn't point to null when the function * is called, the existing scene is cleared and refilled. * @param src Non-empty list of scenes to be merged. The function deletes the input scenes afterwards. There may be * duplicate scenes. * @param flags Combination of the AI_INT_MERGE_SCENE flags defined above */ fun mergeScenes(src: ArrayList<AiScene>, flags: Int = 0): AiScene { val dest = AiScene() // Create a dummy scene to serve as master for the others val master = AiScene().apply { rootNode = AiNode().apply { name = "<MergeRoot>" } } val srcList = List(src.size, { AttachmentInfo(src[it], master.rootNode) }) // 'master' will be deleted afterwards return mergeScenes(master, srcList, flags) } /** Merges two or more scenes and attaches all scenes to a specific position in the node graph of the master scene. * * @return Receives a pointer to the destination scene. If the pointer doesn't point to NULL when the function * is called, the existing scene is cleared and refilled. * @param master Master scene. It will be deleted afterwards. All other scenes will be inserted in its node graph. * @param src Non-empty list of scenes to be merged along with their corresponding attachment points in the master * scene. The function deletes the input scenes afterwards. There may be duplicate scenes. * @param flags Combination of the AI_INT_MERGE_SCENE flags defined above */ fun mergeScenes(master: AiScene, srcList: List<AttachmentInfo>, flags: Int = 0): AiScene { val dest = AiScene() val src = Array(srcList.size + 1, { SceneHelper(if (it == 0) master else srcList[it - 1].scene) }) // this helper array specifies which scenes are duplicates of others val duplicates = IntArray(src.size, { Int.MAX_VALUE }) // this helper array is used as lookup table several times val offset = IntArray(src.size) // Find duplicate scenes for (i in 0 until src.size) { if (duplicates[i] != i && duplicates[i] != Int.MAX_VALUE) continue duplicates[i] = i for (a in i + 1 until src.size) if (src[i]() === src[a]()) duplicates[a] = i } // Generate unique names for all named stuff? if (flags has Ms.GEN.UNIQUE_NAMES) for (i in 1 until src.size) { src[i].id = "$%.6X\$_".format(i) if (flags has Ms.GEN.UNIQUE_NAMES_IF_NECESSARY) { /* Compute hashes for all identifiers in this scene and store them in a sorted table. We hash just the node and animation channel names, all identifiers except the material names should be caught by doing this. */ addNodeHashes(src[i]().rootNode, src[i].hashes) for (a in 0 until src[i]().numAnimations) src[i].hashes.add(superFastHash(src[i]().animations[a].name)) } } var cnt = 0 // First find out how large the respective output arrays must be for (n in 0 until src.size) { val cur = src[n] if (n == duplicates[n] || flags has Ms.DUPLICATES_DEEP_CPY) { dest.numTextures += cur().numTextures dest.numMaterials += cur().numMaterials dest.numMeshes += cur().numMeshes } dest.numLights += cur().numLights dest.numCameras += cur().numCameras dest.numAnimations += cur().numAnimations // Combine the flags of all scenes // We need to process them flag-by-flag here to get correct results // dest->mFlags ; //|= (*cur)->mFlags; if (cur().flags has AI_SCENE_FLAGS_NON_VERBOSE_FORMAT) dest.flags = dest.flags or AI_SCENE_FLAGS_NON_VERBOSE_FORMAT } // generate the output texture list + an offset table for all texture indices if (dest.numTextures != 0) { cnt = 0 for (n in 0 until src.size) { val cur = src[n] for (entry in cur().textures) if (n != duplicates[n]) { if (flags has Ms.DUPLICATES_DEEP_CPY) dest.textures[entry.key] = Texture(entry.value) else continue } else dest.textures[entry.key] = entry.value offset[n] = cnt cnt = dest.textures.size } } // generate the output material list + an offset table for all material indices if (dest.numMaterials != 0) { cnt = 0 for (n in 0 until src.size) { val cur = src[n] for (i in 0 until cur().numMaterials) { if (n != duplicates[n]) { if (flags has Ms.DUPLICATES_DEEP_CPY) dest.materials.add(AiMaterial(cur().materials[i])) else continue } else dest.materials.add(cur().materials[i]) // JVM, we dont need that because of our texture saved in hashMap with "tex.file" property.. // if (cur().numTextures != dest.numTextures) { // // We need to update all texture indices of the mesh. So we need to search for a material property called '$tex.file' // // for (unsigned int a = 0; a < ( * pip)->mNumProperties;++a) // { // aiMaterialProperty * prop = ( * pip)->mProperties[a] // if (!strncmp(prop->mKey.data, "$tex.file", 9)) // { // // Check whether this texture is an embedded texture. // // In this case the property looks like this: *<n>, // // where n is the index of the texture. // aiString& s = *((aiString*)prop->mData) // if ('*' == s.data[0]) { // // Offset the index and write it back .. // const unsigned int idx = strtoul10 (&s.data[1])+offset[n] // ASSIMP_itoa10(& s . data [1], sizeof(s.data)-1, idx) // } // } // // // Need to generate new, unique material names? // else if (!::strcmp(prop->mKey.data, "$mat.name") && flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_MATNAMES) // { // aiString * pcSrc = (aiString *) prop->mData // PrefixString(*pcSrc, ( * cur).id, (*cur).idlen) // } // } // } // ++pip } offset[n] = cnt cnt = dest.materials.size } } // generate the output mesh list + again an offset table for all mesh indices if (dest.numMeshes != 0) { cnt = 0 for (n in 0 until src.size) { val cur = src[n] for (i in 0 until cur().numMeshes) { if (n != duplicates[n]) { if (flags has Ms.DUPLICATES_DEEP_CPY) dest.meshes.add(AiMesh(cur().meshes[i])) else continue } else dest.meshes.add(cur().meshes[i]) // update the material index of the mesh dest.meshes.last().materialIndex += offset[n] } // reuse the offset array - store now the mesh offset in it offset[n] = cnt cnt = dest.meshes.size } } val nodes = ArrayList<NodeAttachmentInfo>(srcList.size) /* ---------------------------------------------------------------------------- Now generate the output node graph. We need to make those names in the graph that are referenced by anims or lights or cameras unique. So we add a prefix to them ... $<rand>_ We could also use a counter, but using a random value allows us to use just one prefix if we are joining multiple scene hierarchies recursively. Chances are quite good we don't collide, so we try that ... ---------------------------------------------------------------------------- */ var n = src.lastIndex while (n >= 0) { /* !!! important !!! */ val cur = src[n] var node: AiNode? // To offset or not to offset, this is the question if (n != duplicates[n]) { // Get full scene-graph copy node = AiNode(cur().rootNode) offsetNodeMeshIndices(node, offset[duplicates[n]]) if (flags has Ms.DUPLICATES_DEEP_CPY) // (note:) they are already 'offseted' by offset[duplicates[n]] offsetNodeMeshIndices(node, offset[n] - offset[duplicates[n]]) } else { // if (n == duplicates[n]) node = cur().rootNode offsetNodeMeshIndices(node, offset[n]) } if (n != 0) // src[0] is the master node nodes.add(NodeAttachmentInfo(node, srcList[n - 1].attachToNode, n)) // add name prefixes? if (flags has Ms.GEN.UNIQUE_NAMES) { // or the whole scenegraph if (flags has Ms.GEN.UNIQUE_NAMES_IF_NECESSARY) addNodePrefixesChecked(node, cur.id, src, n) else addNodePrefixes(node, cur.id) // meshes for (i in 0 until cur().numMeshes) { val mesh = cur().meshes[i] // rename all bones for (a in 0 until mesh.numBones) { if (flags has Ms.GEN.UNIQUE_NAMES_IF_NECESSARY) if (!findNameMatch(mesh.bones[a].name, src, n)) continue prefixString(mesh.bones[a]::name, cur.id) } } } // -------------------------------------------------------------------- // Copy light sources for (i in 0 until cur().numLights) { if (n != duplicates[n]) // duplicate scene? dest.lights.add(AiLight(cur().lights[i])) else dest.lights[i] = cur().lights[i] // Add name prefixes? if (flags has Ms.GEN.UNIQUE_NAMES) { if (flags has Ms.GEN.UNIQUE_NAMES_IF_NECESSARY) if (!findNameMatch(dest.lights.last().name, src, n)) continue prefixString(dest.lights.last()::name, cur.id) } } // -------------------------------------------------------------------- // Copy cameras for (i in 0 until cur().numCameras) { if (n != duplicates[n]) // duplicate scene? dest.cameras.add(AiCamera(cur().cameras[i])) else dest.cameras.add(cur().cameras[i]) // Add name prefixes? if (flags has Ms.GEN.UNIQUE_NAMES) { if (flags has Ms.GEN.UNIQUE_NAMES_IF_NECESSARY) if (!findNameMatch(dest.cameras.last().name, src, n)) continue prefixString(dest.cameras.last()::name, cur.id) } } // -------------------------------------------------------------------- // Copy animations for (i in 0 until cur().numAnimations) { if (n != duplicates[n]) // duplicate scene? dest.animations.add(AiAnimation(cur().animations[i])) else dest.animations.add(cur().animations[i]) // Add name prefixes? if (flags has Ms.GEN.UNIQUE_NAMES) { val last = dest.animations.last() if (flags has Ms.GEN.UNIQUE_NAMES_IF_NECESSARY) if (!findNameMatch(last.name, src, n)) continue prefixString(last::name, cur.id) // don't forget to update all node animation channels for (a in 0 until last.numChannels) { if (flags has Ms.GEN.UNIQUE_NAMES_IF_NECESSARY) if (!findNameMatch(last.channels[a]!!.nodeName, src, n)) continue prefixString(last.channels[a]!!::nodeName, cur.id) } } } --n } // Now build the output graph attachToGraph(master, nodes) dest.rootNode = master.rootNode // Check whether we succeeded at building the output graph nodes.filter { !it.resolved }.forEach { if (flags has Ms.RESOLVE_CROSS_ATTACHMENTS) { // search for this attachment point in all other imported scenes, too. for (n in 0 until src.size) { if (n != it.srcIdx) { attachToGraph(src[n].scene!!, nodes) if (it.resolved) break } } } if (!it.resolved) logger.error { "SceneCombiner: Failed to resolve attachment ${it.node!!.name} ${it.attachToNode!!.name}" } } // now delete all input scenes. JVM -> GC // Check flags if (dest.numMeshes == 0 || dest.numMaterials == 0) dest.flags = dest.flags or AI_SCENE_FLAGS_INCOMPLETE // We're finished return dest } /** Merges two or more meshes * * The meshes should have equal vertex formats. Only components that are provided by ALL meshes will be present in * the output mesh. * An exception is made for VColors - they are set to black. The meshes should have the same material indices, too. * The output material index is always the material index of the first mesh. * * @param dest Destination mesh. Must be empty. * @param flags Currently no parameters * @param begin First mesh to be processed * @param end Points to the mesh after the last mesh to be processed */ fun mergeMeshes(dest: ArrayList<AiMesh>, flags: Int, meshes: ArrayList<AiMesh>, begin: Int, end: Int) { if (begin == end) return // no meshes ... // Allocate the output mesh val out = AiMesh() dest.add(out) out.materialIndex = meshes[begin].materialIndex // Find out how much output storage we'll need for (i in begin until end) { val it = meshes[i] out.numVertices += it.numVertices out.numFaces += it.numFaces out.numBones += it.numBones // combine primitive type flags out.primitiveTypes = out.primitiveTypes or it.primitiveTypes } if (out.numVertices != 0) { // copy vertex positions if (meshes[begin].hasPositions) for (i in begin until end) { val it = meshes[i] if (it.vertices.isNotEmpty()) for (j in 0 until it.numVertices) out.vertices.add(it.vertices[j]) else logger.warn { "JoinMeshes: Positions expected but input mesh contains no positions" } } // copy normals if (meshes[begin].hasNormals) for (i in begin until end) { val it = meshes[i] if (it.normals.isNotEmpty()) for (j in 0 until it.numVertices) out.normals.add(it.normals[j]) else logger.warn { "JoinMeshes: Normals expected but input mesh contains no normals" } } // copy tangents and bitangents if (meshes[begin].hasTangentsAndBitangents) for (i in begin until end) { val it = meshes[i] if (it.tangents.isNotEmpty()) for (j in 0 until it.numVertices) { out.tangents.add(it.tangents[j]) out.bitangents.add(it.bitangents[j]) } else logger.warn { "JoinMeshes: Tangents expected but input mesh contains no tangents" } } // copy texture coordinates var n = 0 while (meshes[begin].hasTextureCoords(n)) { for (i in begin until end) { val it = meshes[i] if (it.textureCoords[n].isNotEmpty()) for (j in 0 until it.textureCoords[n].size) out.textureCoords[n][j] = it.textureCoords[n][j].clone() else logger.warn { "JoinMeshes: UVs expected but input mesh contains no UVs" } } ++n } // copy vertex colors n = 0 while (meshes[begin].hasVertexColors(n)) { for (i in begin until end) { val it = meshes[i] if (it.colors[n].isNotEmpty()) for (j in 0 until it.colors[n].size) out.colors[n].add(it.colors[n][j]) else logger.warn { "JoinMeshes: VCs expected but input mesh contains no VCs" } } ++n } } if (out.numFaces != 0) { // just for safety // copy faces var ofs = 0 for (i in begin until end) { val it = meshes[i] for (m in 0 until it.numFaces) { val face = it.faces[m] out.faces.add(face) if (ofs != 0) // add the offset to the vertex for (q in 0 until face.size) face[q] += ofs } ofs += it.numVertices } } // bones - as this is quite lengthy, I moved the code to a separate function if (out.numBones != 0) mergeBones(out, meshes, begin, end) } /** Merges two or more bones * * @param out Mesh to receive the output bone list * @param flags Currently no parameters * @param begin First mesh to be processed * @param end Points to the mesh after the last mesh to be processed */ fun mergeBones(out: AiMesh, meshes: ArrayList<AiMesh>, begin: Int, end: Int) { assert(out.numBones == 0) /* find we need to build an unique list of all bones. we work with hashes to make the comparisons MUCH faster, at least if we have many bones. */ val asBones = ArrayList<BoneWithHash>() buildUniqueBoneList(asBones, meshes, begin, end) // now create the output bones out.numBones = 0 asBones.forEach { // Allocate a bone and setup it's name out.bones.add(AiBone()) out.numBones++ val pc = out.bones.last().apply { name = it.second } val wend = it.srcBones.size // Loop through all bones to be joined for this bone var wmit = 0 while (wmit != wend) { pc.numWeights += it.srcBones[wmit].first.numWeights // NOTE: different offset matrices for bones with equal names are - at the moment - not handled correctly. TODO jvm? if (wmit != 0 && pc.offsetMatrix != it.srcBones[wmit].first.offsetMatrix) { logger.warn { "Bones with equal names but different offset matrices can't be joined at the moment" } continue } pc.offsetMatrix = it.srcBones[wmit].first.offsetMatrix ++wmit } var avw = 0 // And copy the final weights - adjust the vertex IDs by the face index offset of the corresponding mesh. wmit = 0 while (wmit != wend) { val pip = it.srcBones[wmit].first for (mp in 0 until pip.numWeights) { val vfi = pip.weights[mp] with(pc.weights[avw]) { weight = vfi.weight vertexId = vfi.vertexId + it.srcBones[wmit].second } ++avw } ++wmit } } } /** Merges two or more materials * * The materials should be complementary as much as possible. In case * of a property present in different materials, the first occurrence * is used. * * @param dest Destination material. Must be empty. * @param begin First material to be processed * @param end Points to the material after the last material to be processed */ fun mergeMaterials(dest: AiMaterial, materials: ArrayList<AiMaterial>, begin: Int, end: Int) { if (begin == end) return // no materials ... // Get the maximal number of properties for (i in begin until end) { val m = materials[i] with(dest) { // Test if we already have a matching property and if not, we add it to the new material if (name == null) m.name?.let { name = m.name } if (shadingModel == null) m.shadingModel?.let { shadingModel = m.shadingModel } if (wireframe == null) m.wireframe?.let { wireframe = m.wireframe } if (blendFunc == null) m.blendFunc?.let { blendFunc = m.blendFunc } if (opacity == null) m.opacity?.let { opacity = m.opacity } if (bumpScaling == null) m.bumpScaling?.let { bumpScaling = m.bumpScaling } if (shininess == null) m.shininess?.let { shininess = m.shininess } if (reflectivity == null) m.reflectivity?.let { reflectivity = m.reflectivity } if (shininessStrength == null) m.shininessStrength?.let { shininessStrength = m.shininessStrength } if (color == null) m.color?.let { color = AiMaterial.Color(it) } m.textures.filter { t -> !textures.any { it.file == t.file } }.toCollection(textures) } } } /** Builds a list of uniquely named bones in a mesh list * * @param asBones Receives the output list * @param it First mesh to be processed * @param end Last mesh to be processed */ fun buildUniqueBoneList(asBones: ArrayList<BoneWithHash>, meshes: ArrayList<AiMesh>, begin: Int, end: Int) { var iOffset = 0 var i = begin while (i != end) { val it = meshes[i] for (l in 0 until it.numBones) { val p = it.bones[l] val itml = superFastHash(p.name) val end2 = asBones.size var j = 0 while (j != end2) { val it2 = asBones[j] if (it2.first == itml) { it2.srcBones.add(p to iOffset) break } j++ } if (end2 == j) { // need to begin a new bone entry asBones.add(BoneWithHash()) val btz = asBones.last() // setup members btz.first = itml btz.second = p.name btz.srcBones.add(p to iOffset) } } iOffset += it.numVertices i++ } } /** Add a name prefix to all nodes in a scene. * * @param Current node. This function is called recursively. * @param prefix Prefix to be added to all nodes */ fun addNodePrefixes(node: AiNode, prefix: String) { assert(prefix.isNotEmpty()) prefixString(node::name, prefix) // Process all children recursively for (i in 0 until node.numChildren) addNodePrefixes(node.children[i], prefix) } /** Add an offset to all mesh indices in a node graph * * @param Current node. This function is called recursively. * @param offset Offset to be added to all mesh indices */ fun offsetNodeMeshIndices(node: AiNode, offset: Int) { for (i in 0 until node.numMeshes) node.meshes[i] += offset for (i in 0 until node.numChildren) offsetNodeMeshIndices(node.children[i], offset) } /** Attach a list of node graphs to well-defined nodes in a master graph. This is a helper for MergeScenes() * * @param master Master scene * @param srcList List of source scenes along with their attachment points. If an attachment point is null (or does * not exist in the master graph), a scene is attached to the root of the master graph (as an additional child * node) * @duplicates List of duplicates. If elem[n] == n the scene is not a duplicate. Otherwise elem[n] links scene n to * its first occurrence. */ fun attachToGraph(master: AiScene, srcList: ArrayList<NodeAttachmentInfo>) = attachToGraph(master.rootNode, srcList) fun attachToGraph(attach: AiNode, srcList: ArrayList<NodeAttachmentInfo>) { for (cnt in 0 until attach.numChildren) attachToGraph(attach.children[cnt], srcList) var cnt = 0 srcList.filter { it.attachToNode === attach && !it.resolved }.map { ++cnt } if (cnt != 0) { val n = ArrayList<AiNode>(cnt + attach.numChildren) if (attach.numChildren != 0) for (i in 0 until attach.numChildren) n.add(attach.children[i]) // TODO addAll? attach.children = n attach.numChildren += cnt for (att in srcList) { if (att.attachToNode === attach && !att.resolved) { n.add(att.node!!.apply { parent = attach }) att.resolved = true // mark this attachment as resolved } } } } // ------------------------------------------------------------------- /** Get a deep copy of a scene * * @param dest Receives a pointer to the destination scene * @param src Source scene - remains unmodified. */ // static void CopyScene(aiScene * * dest, const aiScene * source, bool allocate = true) // // //// ------------------------------------------------------------------- // /** Get a flat copy of a scene // * // * Only the first hierarchy layer is copied. All pointer members of // * aiScene are shared by source and destination scene. If the // * pointer doesn't point to NULL when the function is called, the // * existing scene is cleared and refilled. // * @param dest Receives a pointer to the destination scene // * @param src Source scene - remains unmodified. // */ // static void CopySceneFlat(aiScene * * dest, const aiScene * source) // // // use Mesh constructor /** Get a deep copy of a mesh * * @param dest Receives a pointer to the destination mesh * @param src Source mesh - remains unmodified. */ // fun copy(dest: AiMesh, src: AiMesh?) { // // if (null == src) return // // // get a flat copy // ::memcpy(dest, src, sizeof(aiMesh)); // // // and reallocate all arrays // GetArrayCopy(dest->mVertices, dest->mNumVertices); // GetArrayCopy(dest->mNormals, dest->mNumVertices); // GetArrayCopy(dest->mTangents, dest->mNumVertices); // GetArrayCopy(dest->mBitangents, dest->mNumVertices); // // unsigned int n = 0; // while (dest->HasTextureCoords(n)) // GetArrayCopy(dest->mTextureCoords[n++], dest->mNumVertices); // // n = 0; // while (dest->HasVertexColors(n)) // GetArrayCopy(dest->mColors[n++], dest->mNumVertices); // // // make a deep copy of all bones // CopyPtrArray(dest->mBones, dest->mBones, dest->mNumBones); // // // make a deep copy of all faces // GetArrayCopy(dest->mFaces, dest->mNumFaces); // for (unsigned int i = 0; i < dest->mNumFaces;++i) { // aiFace& f = dest->mFaces[i]; // GetArrayCopy(f.mIndices, f.mNumIndices); // } // } //// similar to Copy(): // static void Copy(aiMaterial * * dest, const aiMaterial * src) // static void Copy(aiTexture * * dest, const aiTexture * src) // static void Copy(aiAnimation * * dest, const aiAnimation * src) // static void Copy(aiCamera * * dest, const aiCamera * src) // static void Copy(aiBone * * dest, const aiBone * src) // static void Copy(aiLight * * dest, const aiLight * src) // static void Copy(aiNodeAnim * * dest, const aiNodeAnim * src) // static void Copy(aiMetadata * * dest, const aiMetadata * src) // //// recursive, of course // static void Copy(aiNode * * dest, const aiNode * src) /** Same as AddNodePrefixes, but with an additional check * Add a name prefix to all nodes in a hierarchy if a hash match is found */ fun addNodePrefixesChecked(node: AiNode, prefix: String, input: Array<SceneHelper>, cur: Int) { assert(prefix.isNotEmpty()) val hash = superFastHash(node.name) // Check whether we find a positive match in one of the given sets for (i in 0 until input.size) if (cur != i && input[i].hashes.contains(hash)) { prefixString(node::name, prefix) break } // Process all children recursively for (i in 0 until node.numChildren) addNodePrefixesChecked(node.children[i], prefix, input, cur) } /** Add node identifiers to a hashing set */ fun addNodeHashes(node: AiNode, hashes: HashSet<Int>) { /* Add node name to hashing set if it is non-empty - empty nodes are allowed and they can't have any anims assigned so its absolutely safe to duplicate them. */ if (node.name.isNotEmpty()) hashes.add(superFastHash(node.name)) // Process all children recursively for (i in 0 until node.numChildren) addNodeHashes(node.children[i], hashes) } /** Search for duplicate names */ fun findNameMatch(name: String, input: Array<SceneHelper>, cur: Int): Boolean { val hash = superFastHash(name) // Check whether we find a positive match in one of the given sets for (i in 0 until input.size) if (cur != i && input[i].hashes.contains(hash)) return true return false } /** Add a prefix to a string */ fun prefixString(string: KMutableProperty0<String>, prefix: String) { // If the string is already prefixed, we won't prefix it a second time if (string().isNotEmpty() && string()[0] == '$') return if (prefix.length + string().length >= MAXLEN - 1) { logger.debug { "Can't add an unique prefix because the string is too long" } assert(false) return } // Add the prefix string.set("$prefix${string()}") } }
mit
c903f53f81b56ad71cb558833ce87dc3
44.059776
143
0.537643
4.57132
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/domain/course/interactor/CourseBillingInteractor.kt
1
6180
package org.stepik.android.domain.course.interactor import com.google.gson.Gson import io.reactivex.Completable import io.reactivex.Scheduler import io.reactivex.Single import io.reactivex.rxkotlin.Maybes.zip import io.reactivex.subjects.PublishSubject import okhttp3.ResponseBody import org.solovyev.android.checkout.ProductTypes import org.solovyev.android.checkout.Purchase import org.solovyev.android.checkout.Sku import org.solovyev.android.checkout.UiCheckout import org.stepic.droid.di.qualifiers.BackgroundScheduler import org.stepic.droid.di.qualifiers.MainScheduler import org.stepic.droid.preferences.SharedPreferenceHelper import org.stepic.droid.util.toObject import org.stepik.android.domain.base.DataSourceType import org.stepik.android.domain.billing.exception.NoPurchasesToRestoreException import org.stepik.android.domain.billing.extension.startPurchaseFlowRx import org.stepik.android.domain.billing.repository.BillingRepository import org.stepik.android.domain.course.model.CoursePurchasePayload import org.stepik.android.domain.course.repository.CourseRepository import org.stepik.android.domain.course_payments.exception.CourseAlreadyOwnedException import org.stepik.android.domain.course_payments.exception.CoursePurchaseVerificationException import org.stepik.android.domain.course_payments.model.CoursePayment import org.stepik.android.domain.course_payments.repository.CoursePaymentsRepository import org.stepik.android.domain.lesson.repository.LessonRepository import org.stepik.android.domain.mobile_tiers.model.LightSku import org.stepik.android.domain.user_courses.interactor.UserCoursesInteractor import org.stepik.android.model.Course import org.stepik.android.view.injection.course.EnrollmentCourseUpdates import retrofit2.HttpException import retrofit2.Response import ru.nobird.android.domain.rx.maybeFirst import java.net.HttpURLConnection import javax.inject.Inject class CourseBillingInteractor @Inject constructor( private val billingRepository: BillingRepository, private val coursePaymentsRepository: CoursePaymentsRepository, private val sharedPreferenceHelper: SharedPreferenceHelper, private val courseRepository: CourseRepository, private val lessonRepository: LessonRepository, @EnrollmentCourseUpdates private val enrollmentSubject: PublishSubject<Course>, @BackgroundScheduler private val backgroundScheduler: Scheduler, @MainScheduler private val mainScheduler: Scheduler, private val userCoursesInteractor: UserCoursesInteractor ) { private val gson = Gson() companion object { private val UNAUTHORIZED_EXCEPTION_STUB = HttpException(Response.error<Nothing>(HttpURLConnection.HTTP_UNAUTHORIZED, ResponseBody.create(null, ""))) } fun purchaseCourse(checkout: UiCheckout, courseId: Long, sku: LightSku): Completable = billingRepository .getInventory(ProductTypes.IN_APP, sku.id) .flatMapCompletable { purchaseCourse(checkout, courseId, it) } fun purchaseCourse(checkout: UiCheckout, courseId: Long, sku: Sku): Completable = coursePaymentsRepository .getCoursePaymentsByCourseId(courseId, CoursePayment.Status.SUCCESS, sourceType = DataSourceType.REMOTE) .flatMapCompletable { payments -> if (payments.isEmpty()) { purchaseCourseAfterCheck(checkout, courseId, sku) } else { Completable.error(CourseAlreadyOwnedException(courseId)) } } private fun purchaseCourseAfterCheck(checkout: UiCheckout, courseId: Long, sku: Sku): Completable = getCurrentProfileId() .map { profileId -> gson.toJson(CoursePurchasePayload(profileId, courseId)) } .observeOn(mainScheduler) .flatMap { payload -> checkout.startPurchaseFlowRx(sku, payload) } .observeOn(backgroundScheduler) .flatMapCompletable { purchase -> completePurchase(courseId, sku, purchase) } fun restorePurchase(sku: Sku): Completable = zip( getCurrentProfileId() .toMaybe(), billingRepository .getAllPurchases(ProductTypes.IN_APP, listOf(sku.id.code)) .observeOn(backgroundScheduler) .maybeFirst() ) .map { (profileId, purchase) -> Triple(profileId, purchase, purchase.payload.toObject<CoursePurchasePayload>(gson)) } .filter { (profileId, _, payload) -> profileId == payload.profileId } .switchIfEmpty(Single.error(NoPurchasesToRestoreException())) .flatMapCompletable { (_, purchase, payload) -> completePurchase(payload.courseId, sku, purchase) } private fun completePurchase(courseId: Long, sku: Sku, purchase: Purchase): Completable = coursePaymentsRepository .createCoursePayment(courseId, sku, purchase) .flatMapCompletable { payment -> if (payment.status == CoursePayment.Status.SUCCESS) { Completable.complete() } else { Completable.error(CoursePurchaseVerificationException()) } } .andThen(updateCourseAfterEnrollment(courseId)) .andThen(billingRepository.consumePurchase(purchase)) private fun updateCourseAfterEnrollment(courseId: Long): Completable = userCoursesInteractor.addUserCourse(courseId) .andThen(lessonRepository.removeCachedLessons(courseId)) .andThen(courseRepository.getCourse(courseId, sourceType = DataSourceType.REMOTE, allowFallback = false).toSingle()) .doOnSuccess(enrollmentSubject::onNext) // notify everyone about changes .ignoreElement() private fun getCurrentProfileId(): Single<Long> = Single.fromCallable { sharedPreferenceHelper .profile ?.id ?: throw UNAUTHORIZED_EXCEPTION_STUB } }
apache-2.0
21b97d98c060b6bc3258bf448161da65
41.923611
128
0.7089
5.210793
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/course_list/delegate/CourseCollectionSimilarCoursesListAdapterDelegate.kt
1
2963
package org.stepik.android.view.course_list.delegate import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import kotlinx.android.extensions.LayoutContainer import kotlinx.android.synthetic.main.item_collection_horizontal_list.* import org.stepic.droid.R import org.stepic.droid.ui.util.CoursesSnapHelper import org.stepik.android.domain.catalog.model.CatalogCourseList import org.stepik.android.domain.course_list.model.CourseListItem import org.stepik.android.view.base.ui.adapter.layoutmanager.TableLayoutManager import org.stepik.android.view.catalog.mapper.CourseCountMapper import org.stepik.android.view.catalog.ui.adapter.delegate.SimpleCourseListDefaultAdapterDelegate import ru.nobird.android.ui.adapterdelegates.AdapterDelegate import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder import ru.nobird.android.ui.adapters.DefaultDelegateAdapter class CourseCollectionSimilarCoursesListAdapterDelegate( private val courseCountMapper: CourseCountMapper, private val onCourseListClicked: (CatalogCourseList) -> Unit ) : AdapterDelegate<CourseListItem, DelegateViewHolder<CourseListItem>>() { private val sharedViewPool = RecyclerView.RecycledViewPool() override fun isForViewType(position: Int, data: CourseListItem): Boolean = data is CourseListItem.SimilarCourses override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<CourseListItem> = ViewHolder(createView(parent, R.layout.item_collection_horizontal_list)) private inner class ViewHolder( override val containerView: View ) : DelegateViewHolder<CourseListItem>(containerView), LayoutContainer { private val adapter = DefaultDelegateAdapter<CatalogCourseList>() .also { it += SimpleCourseListDefaultAdapterDelegate(courseCountMapper, onCourseListClicked) } init { val rowCount = 1 horizontalListRecycler.layoutManager = TableLayoutManager( context, horizontalSpanCount = context.resources.getInteger(R.integer.simple_course_lists_default_columns), verticalSpanCount = rowCount, orientation = LinearLayoutManager.HORIZONTAL, reverseLayout = false ) horizontalListRecycler.setRecycledViewPool(sharedViewPool) horizontalListRecycler.setHasFixedSize(true) horizontalListRecycler.adapter = adapter val snapHelper = CoursesSnapHelper(rowCount) snapHelper.attachToRecyclerView(horizontalListRecycler) } override fun onBind(data: CourseListItem) { data as CourseListItem.SimilarCourses containerTitle.setText(R.string.similar_courses_title) adapter.items = data.similarCourses } } }
apache-2.0
165804640f32c1a5eff7042352edf5e5
43.909091
118
0.743503
5.416819
false
false
false
false
pambrose/prometheus-proxy
src/main/kotlin/io/prometheus/agent/SslSettings.kt
1
1919
/* * Copyright © 2022 Paul Ambrose ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prometheus.agent import java.io.FileInputStream import java.security.KeyStore import javax.net.ssl.SSLContext import javax.net.ssl.TrustManagerFactory import javax.net.ssl.X509TrustManager // https://github.com/Hakky54/mutual-tls-ssl/blob/master/client/src/main/java/nl/altindag/client/service/KtorCIOHttpClientService.kt object SslSettings { fun getKeyStore(fileName: String, password: String): KeyStore = KeyStore.getInstance(KeyStore.getDefaultType()) .apply { val keyStoreFile = FileInputStream(fileName) val keyStorePassword = password.toCharArray() load(keyStoreFile, keyStorePassword) } fun getTrustManagerFactory(fileName: String, password: String): TrustManagerFactory? = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()) .apply { init(getKeyStore(fileName, password)) } fun getSslContext(fileName: String, password: String): SSLContext? = SSLContext.getInstance("TLS") .apply { init(null, getTrustManagerFactory(fileName, password)?.trustManagers, null) } fun getTrustManager(fileName: String, password: String): X509TrustManager = getTrustManagerFactory(fileName, password)?.trustManagers?.first { it is X509TrustManager } as X509TrustManager }
apache-2.0
26a51c2255a5a5a9b5098e563781743c
37.36
132
0.748175
4.369021
false
false
false
false
MaTriXy/material-dialogs
color/src/main/java/com/afollestad/materialdialogs/color/view/WrapContentViewPager.kt
2
2013
/** * Designed and developed by Aidan Follestad (@afollestad) * * 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.afollestad.materialdialogs.color.view import android.content.Context import android.util.AttributeSet import android.view.View import android.view.View.MeasureSpec.EXACTLY import android.view.View.MeasureSpec.UNSPECIFIED import android.view.View.MeasureSpec.makeMeasureSpec import androidx.viewpager.widget.ViewPager import com.afollestad.materialdialogs.utils.MDUtil.ifNotZero internal class WrapContentViewPager( context: Context, attrs: AttributeSet? = null ) : ViewPager(context, attrs) { override fun onMeasure( widthMeasureSpec: Int, heightMeasureSpec: Int ) { var newHeightSpec = heightMeasureSpec var maxChildHeight = 0 forEachChild { child -> child.measure( widthMeasureSpec, makeMeasureSpec(0, UNSPECIFIED) ) val h = child.measuredHeight if (h > maxChildHeight) { maxChildHeight = h } } val maxAllowedHeightFromParent = MeasureSpec.getSize(heightMeasureSpec) if (maxChildHeight > maxAllowedHeightFromParent) { maxChildHeight = maxAllowedHeightFromParent } maxChildHeight.ifNotZero { newHeightSpec = makeMeasureSpec(it, EXACTLY) } super.onMeasure(widthMeasureSpec, newHeightSpec) } private fun forEachChild(each: (View) -> Unit) { for (i in 0 until childCount) { val child = getChildAt(i) each(child) } } }
apache-2.0
58465d496f042593023c835f421c1d6a
28.602941
75
0.726776
4.554299
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/completion/contributors/FirKeywordCompletionContributor.kt
3
4395
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.completion.contributors import com.intellij.codeInsight.lookup.LookupElement import com.intellij.openapi.module.Module import com.intellij.psi.PsiElement import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.completion.KeywordCompletion import org.jetbrains.kotlin.idea.completion.context.* import org.jetbrains.kotlin.idea.completion.contributors.keywords.OverrideKeywordHandler import org.jetbrains.kotlin.idea.completion.contributors.keywords.ReturnKeywordHandler import org.jetbrains.kotlin.idea.completion.contributors.keywords.SuperKeywordHandler import org.jetbrains.kotlin.idea.completion.contributors.keywords.ThisKeywordHandler import org.jetbrains.kotlin.idea.completion.keywords.CompletionKeywordHandlerProvider import org.jetbrains.kotlin.idea.completion.keywords.CompletionKeywordHandlers import org.jetbrains.kotlin.idea.completion.keywords.DefaultCompletionKeywordHandlerProvider import org.jetbrains.kotlin.idea.completion.keywords.createLookups import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtExpressionWithLabel import org.jetbrains.kotlin.psi.KtLabelReferenceExpression internal class FirKeywordCompletionContributor(basicContext: FirBasicCompletionContext, priority: Int) : FirCompletionContributorBase<FirRawPositionCompletionContext>(basicContext, priority) { private val keywordCompletion = KeywordCompletion(object : KeywordCompletion.LanguageVersionSettingProvider { override fun getLanguageVersionSetting(element: PsiElement) = element.languageVersionSettings override fun getLanguageVersionSetting(module: Module) = module.languageVersionSettings }) private val resolveDependentCompletionKeywordHandlers = ResolveDependentCompletionKeywordHandlerProvider(basicContext) override fun KtAnalysisSession.complete(positionContext: FirRawPositionCompletionContext) { val expression = when (positionContext) { is FirNameReferencePositionContext -> { val reference = positionContext.reference when (reference.expression) { is KtLabelReferenceExpression -> reference.expression.parent.parent as? KtExpressionWithLabel else -> reference.expression } } is FirTypeConstraintNameInWhereClausePositionContext, is FirIncorrectPositionContext, is FirClassifierNamePositionContext -> { error("keyword completion should not be called for ${positionContext::class.simpleName}") } is FirValueParameterPositionContext, is FirUnknownPositionContext -> null } completeWithResolve(expression ?: positionContext.position, expression) } fun KtAnalysisSession.completeWithResolve(position: PsiElement, expression: KtExpression?) { complete(position) { lookupElement, keyword -> val lookups = DefaultCompletionKeywordHandlerProvider.getHandlerForKeyword(keyword) ?.createLookups(parameters, expression, lookupElement, project) ?: resolveDependentCompletionKeywordHandlers.getHandlerForKeyword(keyword)?.run { createLookups(parameters, expression, lookupElement, project) } ?: listOf(lookupElement) sink.addAllElements(lookups) } } private inline fun complete(position: PsiElement, crossinline complete: (LookupElement, String) -> Unit) { keywordCompletion.complete(position, prefixMatcher, targetPlatform.isJvm()) { lookupElement -> val keyword = lookupElement.lookupString complete(lookupElement, keyword) } } } private class ResolveDependentCompletionKeywordHandlerProvider( basicContext: FirBasicCompletionContext ) : CompletionKeywordHandlerProvider<KtAnalysisSession>() { override val handlers = CompletionKeywordHandlers( ReturnKeywordHandler, OverrideKeywordHandler(basicContext), ThisKeywordHandler(basicContext), SuperKeywordHandler, ) }
apache-2.0
7954d5d967c0a02f44cbc25ba91eee1b
53.271605
158
0.770648
5.598726
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AbstractChangeFeatureSupportLevelFix.kt
2
3892
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.module.Module import com.intellij.psi.PsiElement import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.configuration.BuildSystemType import org.jetbrains.kotlin.idea.configuration.buildSystemType import org.jetbrains.kotlin.idea.facet.KotlinFacet abstract class AbstractChangeFeatureSupportLevelFix( element: PsiElement, protected val feature: LanguageFeature, protected val featureSupport: LanguageFeature.State, private val featureShortName: String = feature.presentableName ) : KotlinQuickFixAction<PsiElement>(element) { protected val featureSupportEnabled: Boolean get() = featureSupport == LanguageFeature.State.ENABLED || featureSupport == LanguageFeature.State.ENABLED_WITH_WARNING final override fun getFamilyName() = KotlinBundle.message("fix.change.feature.support.family", featureShortName) override fun getText(): String = getFixText(featureSupport, featureShortName) companion object { @Nls fun getFixText(state: LanguageFeature.State, featureShortName: String): String { return when (state) { LanguageFeature.State.ENABLED -> { KotlinBundle.message("fix.change.feature.support.enabled", featureShortName) } LanguageFeature.State.ENABLED_WITH_WARNING -> { KotlinBundle.message("fix.change.feature.support.enabled.warning", featureShortName) } LanguageFeature.State.ENABLED_WITH_ERROR, LanguageFeature.State.DISABLED -> { KotlinBundle.message("fix.change.feature.support.disabled", featureShortName) } } } } abstract class FeatureSupportIntentionActionsFactory : KotlinIntentionActionsFactory() { protected fun shouldConfigureInProject(module: Module): Boolean { val facetSettings = KotlinFacet.get(module)?.configuration?.settings return (facetSettings == null || facetSettings.useProjectSettings) && module.buildSystemType == BuildSystemType.JPS } protected fun doCreateActions( diagnostic: Diagnostic, feature: LanguageFeature, allowWarningAndErrorMode: Boolean, quickFixConstructor: (PsiElement, LanguageFeature, LanguageFeature.State) -> IntentionAction ): List<IntentionAction> { val newFeatureSupports = when (diagnostic.factory) { Errors.EXPERIMENTAL_FEATURE_ERROR -> { if (Errors.EXPERIMENTAL_FEATURE_ERROR.cast(diagnostic).a.first != feature) return emptyList() if (!allowWarningAndErrorMode) listOf(LanguageFeature.State.ENABLED) else listOf(LanguageFeature.State.ENABLED_WITH_WARNING, LanguageFeature.State.ENABLED) } Errors.EXPERIMENTAL_FEATURE_WARNING -> { if (Errors.EXPERIMENTAL_FEATURE_WARNING.cast(diagnostic).a.first != feature) return emptyList() if (!allowWarningAndErrorMode) listOf(LanguageFeature.State.ENABLED) else listOf(LanguageFeature.State.ENABLED, LanguageFeature.State.ENABLED_WITH_ERROR) } else -> return emptyList() } return newFeatureSupports.map { quickFixConstructor(diagnostic.psiElement, feature, it) } } } }
apache-2.0
370433fdee7ff4bddb7a3fa30897f37b
49.545455
158
0.692189
5.383126
false
true
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/action/motion/scroll/CtrlUpDownAction.kt
1
1784
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.action.motion.scroll import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.command.Command import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.handler.VimActionHandler /** * @author Alex Plate */ // FIXME: 2019-07-05 Workaround to make jump through methods work class CtrlDownAction : VimActionHandler.SingleExecution() { private val keySet = parseKeysSet("<C-Down>") override val type: Command.Type = Command.Type.OTHER_READONLY override fun execute( editor: VimEditor, context: ExecutionContext, cmd: Command, operatorArguments: OperatorArguments, ): Boolean { val keyStroke = keySet.first().first() val actions = injector.keyGroup.getKeymapConflicts(keyStroke) for (action in actions) { if (injector.actionExecutor.executeAction(action, context)) break } return true } } class CtrlUpAction : VimActionHandler.SingleExecution() { private val keySet = parseKeysSet("<C-Up>") override val type: Command.Type = Command.Type.OTHER_READONLY override fun execute( editor: VimEditor, context: ExecutionContext, cmd: Command, operatorArguments: OperatorArguments, ): Boolean { val keyStroke = keySet.first().first() val actions = injector.keyGroup.getKeymapConflicts(keyStroke) for (action in actions) { if (injector.actionExecutor.executeAction(action, context)) break } return true } }
mit
5252fad6e3cd8ac67d0039d06a7e3159
27.774194
71
0.737108
4.187793
false
false
false
false
Hexworks/zircon
zircon.jvm.examples/src/main/kotlin/org/hexworks/zircon/examples/other/MultiTileExample.kt
1
2220
@file:Suppress("UNCHECKED_CAST") package org.hexworks.zircon.examples.other import org.hexworks.zircon.api.CP437TilesetResources import org.hexworks.zircon.api.ColorThemes import org.hexworks.zircon.api.ComponentDecorations.box import org.hexworks.zircon.api.Components import org.hexworks.zircon.api.SwingApplications import org.hexworks.zircon.api.application.AppConfig import org.hexworks.zircon.api.data.Size import org.hexworks.zircon.api.screen.Screen object MultiTileExample { private val theme = ColorThemes.arc() private val tileset = CP437TilesetResources.rexPaint20x20() @JvmStatic fun main(args: Array<String>) { val tileGrid = SwingApplications.startTileGrid( AppConfig.newBuilder() .withDefaultTileset(tileset) .withSize(Size.create(60, 30)) .build() ) val screen = Screen.create(tileGrid) screen.display() screen.theme = theme val label = Components.label() .withText("Rexpaint 20x20") .withPosition(1, 1) .build() screen.addComponent(label) label.tileset = CP437TilesetResources.rexPaint20x20() val label2 = Components.label() .withText("Yobbo 20x20") .withPosition(1, 3) .build() screen.addComponent(label2) label2.tileset = CP437TilesetResources.yobbo20x20() val panel = Components.panel() .withDecorations(box(title = "Anikki 20x20")) .withPosition(1, 5) .withPreferredSize(17, 2) .build() screen.addComponent(panel) panel.tileset = CP437TilesetResources.anikki20x20() val container = Components.panel() .withPosition(1, 8) .withPreferredSize(17, 3) .withDecorations(box(title = "Bisasam 20x20")) .build() val label3 = Components.label() .withText("Oreslam 20x20") .build() container.addComponent(label3) screen.addComponent(container) container.tileset = CP437TilesetResources.bisasam20x20() label3.tileset = CP437TilesetResources.oreslam20x20() } }
apache-2.0
924a7f8a5bdb1db8b3d530851869596f
28.6
64
0.638739
4.220532
false
false
false
false
JetBrains/ideavim
src/main/java/com/maddyhome/idea/vim/newapi/IjVimEditor.kt
1
15684
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.newapi import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorModificationUtil import com.intellij.openapi.editor.LogicalPosition import com.intellij.openapi.editor.VisualPosition import com.intellij.openapi.editor.event.CaretEvent import com.intellij.openapi.editor.event.CaretListener import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.editor.ex.util.EditorUtil import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.vfs.VirtualFileManager import com.maddyhome.idea.vim.api.BufferPosition import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.LineDeleteShift import com.maddyhome.idea.vim.api.MutableLinearEditor import com.maddyhome.idea.vim.api.VimCaret import com.maddyhome.idea.vim.api.VimCaretListener import com.maddyhome.idea.vim.api.VimDocument import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimSelectionModel import com.maddyhome.idea.vim.api.VimVisualPosition import com.maddyhome.idea.vim.api.VirtualFile import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.command.SelectionType import com.maddyhome.idea.vim.command.VimStateMachine import com.maddyhome.idea.vim.common.EditorLine import com.maddyhome.idea.vim.common.IndentConfig import com.maddyhome.idea.vim.common.LiveRange import com.maddyhome.idea.vim.common.Offset import com.maddyhome.idea.vim.common.TextRange import com.maddyhome.idea.vim.common.offset import com.maddyhome.idea.vim.group.visual.vimSetSystemBlockSelectionSilently import com.maddyhome.idea.vim.helper.EditorHelper import com.maddyhome.idea.vim.helper.exitInsertMode import com.maddyhome.idea.vim.helper.exitSelectMode import com.maddyhome.idea.vim.helper.fileSize import com.maddyhome.idea.vim.helper.getTopLevelEditor import com.maddyhome.idea.vim.helper.inBlockSubMode import com.maddyhome.idea.vim.helper.isTemplateActive import com.maddyhome.idea.vim.helper.updateCaretsVisualAttributes import com.maddyhome.idea.vim.helper.updateCaretsVisualPosition import com.maddyhome.idea.vim.helper.vimChangeActionSwitchMode import com.maddyhome.idea.vim.helper.vimKeepingVisualOperatorAction import com.maddyhome.idea.vim.helper.vimLastSelectionType import com.maddyhome.idea.vim.options.helpers.StrictMode import org.jetbrains.annotations.ApiStatus @ApiStatus.Internal class IjVimEditor(editor: Editor) : MutableLinearEditor() { // All the editor actions should be performed with top level editor!!! // Be careful: all the EditorActionHandler implementation should correctly process InjectedEditors // TBH, I don't like the names. Need to think a bit more about this val editor = editor.getTopLevelEditor() val originalEditor = editor override val lfMakesNewLine: Boolean = true override var vimChangeActionSwitchMode: VimStateMachine.Mode? get() = editor.vimChangeActionSwitchMode set(value) { editor.vimChangeActionSwitchMode = value } override var vimKeepingVisualOperatorAction: Boolean get() = editor.vimKeepingVisualOperatorAction set(value) { editor.vimKeepingVisualOperatorAction = value } override fun fileSize(): Long = editor.fileSize.toLong() override fun text(): CharSequence { return editor.document.charsSequence } override fun nativeLineCount(): Int { return editor.document.lineCount } override fun deleteRange(leftOffset: Offset, rightOffset: Offset) { editor.document.deleteString(leftOffset.point, rightOffset.point) } override fun addLine(atPosition: EditorLine.Offset): EditorLine.Pointer { val offset: Int = if (atPosition.line < lineCount()) { // The new line character is inserted before the new line char of the previous line. So it works line an enter // on a line end. I believe that the correct implementation would be to insert the new line char after the // \n of the previous line, however at the moment this won't update the mark on this line. // https://youtrack.jetbrains.com/issue/IDEA-286587 val lineStart = (editor.document.getLineStartOffset(atPosition.line) - 1).coerceAtLeast(0) val guard = editor.document.getOffsetGuard(lineStart) if (guard != null && guard.endOffset == lineStart + 1) { // Dancing around guarded blocks. It may happen that this concrete position is locked, but the next // (after the new line character) is not. In this case we can actually insert the line after this // new line char // Such thing is often used in pycharm notebooks. lineStart + 1 } else { lineStart } } else { fileSize().toInt() } editor.document.insertString(offset, "\n") return EditorLine.Pointer.init(atPosition.line, this) } override fun insertText(atPosition: Offset, text: CharSequence) { editor.document.insertString(atPosition.point, text) } override fun replaceString(start: Int, end: Int, newString: String) { editor.document.replaceString(start, end, newString) } // TODO: 30.12.2021 Is end offset inclusive? override fun getLineRange(line: EditorLine.Pointer): Pair<Offset, Offset> { // TODO: 30.12.2021 getLineEndOffset returns the same value for "xyz" and "xyz\n" return editor.document.getLineStartOffset(line.line).offset to editor.document.getLineEndOffset(line.line).offset } override fun getLine(offset: Offset): EditorLine.Pointer { return EditorLine.Pointer.init(editor.offsetToLogicalPosition(offset.point).line, this) } override fun carets(): List<VimCaret> { return if (editor.inBlockSubMode) { listOf(IjVimCaret(editor.caretModel.primaryCaret)) } else { editor.caretModel.allCarets.map { IjVimCaret(it) } } } override fun nativeCarets(): List<VimCaret> { return editor.caretModel.allCarets.map { IjVimCaret(it) } } @Suppress("ideavimRunForEachCaret") override fun forEachCaret(action: (VimCaret) -> Unit) { forEachCaret(action, false) } override fun forEachCaret(action: (VimCaret) -> Unit, reverse: Boolean) { if (editor.inBlockSubMode) { action(IjVimCaret(editor.caretModel.primaryCaret)) } else { editor.caretModel.runForEachCaret({ action(IjVimCaret(it)) }, reverse) } } override fun forEachNativeCaret(action: (VimCaret) -> Unit) { forEachNativeCaret(action, false) } override fun forEachNativeCaret(action: (VimCaret) -> Unit, reverse: Boolean) { editor.caretModel.runForEachCaret({ action(IjVimCaret(it)) }, reverse) } override fun primaryCaret(): VimCaret { return IjVimCaret(editor.caretModel.primaryCaret) } override fun currentCaret(): VimCaret { return IjVimCaret(editor.caretModel.currentCaret) } override fun isWritable(): Boolean { val modificationAllowed = EditorModificationUtil.checkModificationAllowed(editor) val writeRequested = EditorModificationUtil.requestWriting(editor) return modificationAllowed && writeRequested } override fun isDocumentWritable(): Boolean { return editor.document.isWritable } override fun isOneLineMode(): Boolean { return editor.isOneLineMode } override fun getText(left: Offset, right: Offset): CharSequence { return editor.document.charsSequence.subSequence(left.point, right.point) } override fun search(pair: Pair<Offset, Offset>, editor: VimEditor, shiftType: LineDeleteShift): Pair<Pair<Offset, Offset>, LineDeleteShift>? { val ijEditor = (editor as IjVimEditor).editor return when (shiftType) { LineDeleteShift.NO_NL -> if (pair.noGuard(ijEditor)) return pair to shiftType else null LineDeleteShift.NL_ON_END -> { if (pair.noGuard(ijEditor)) return pair to shiftType pair.shift(-1, -1) { if (this.noGuard(ijEditor)) return this to LineDeleteShift.NL_ON_START } pair.shift(shiftEnd = -1) { if (this.noGuard(ijEditor)) return this to LineDeleteShift.NO_NL } null } LineDeleteShift.NL_ON_START -> { if (pair.noGuard(ijEditor)) return pair to shiftType pair.shift(shiftStart = 1) { if (this.noGuard(ijEditor)) return this to LineDeleteShift.NO_NL } null } } } override fun updateCaretsVisualAttributes() { editor.updateCaretsVisualAttributes() } override fun updateCaretsVisualPosition() { editor.updateCaretsVisualPosition() } override fun offsetToVisualPosition(offset: Int): VimVisualPosition { return editor.offsetToVisualPosition(offset).let { VimVisualPosition(it.line, it.column, it.leansRight) } } override fun offsetToBufferPosition(offset: Int): BufferPosition { return editor.offsetToLogicalPosition(offset).let { BufferPosition(it.line, it.column, it.leansForward) } } override fun bufferPositionToOffset(position: BufferPosition): Int { val logicalPosition = LogicalPosition(position.line, position.column, position.leansForward) return editor.logicalPositionToOffset(logicalPosition) } override fun getVirtualFile(): VirtualFile? { val vf = EditorHelper.getVirtualFile(editor) return vf?.let { object : VirtualFile { override val path = vf.path } } } override fun deleteString(range: TextRange) { editor.document.deleteString(range.startOffset, range.endOffset) } override fun getSelectionModel(): VimSelectionModel { return object : VimSelectionModel { private val sm = editor.selectionModel override val selectionStart = sm.selectionStart override val selectionEnd = sm.selectionEnd override fun hasSelection(): Boolean { return sm.hasSelection() } } } override fun removeCaret(caret: VimCaret) { editor.caretModel.removeCaret((caret as IjVimCaret).caret) } override fun removeSecondaryCarets() { editor.caretModel.removeSecondaryCarets() } override fun vimSetSystemBlockSelectionSilently(start: BufferPosition, end: BufferPosition) { val startPosition = LogicalPosition(start.line, start.column, start.leansForward) val endPosition = LogicalPosition(end.line, end.column, end.leansForward) editor.selectionModel.vimSetSystemBlockSelectionSilently(startPosition, endPosition) } override fun getLineStartOffset(line: Int): Int { return if (line < 0) { StrictMode.fail("Incorrect line: $line") 0 } else if (line >= this.lineCount()) { if (lineCount() != 0) { StrictMode.fail("Incorrect line: $line") } editor.fileSize } else { editor.document.getLineStartOffset(line) } } override fun getLineEndOffset(line: Int): Int { return editor.document.getLineEndOffset(line) } val listenersMap: MutableMap<VimCaretListener, CaretListener> = mutableMapOf() override fun addCaretListener(listener: VimCaretListener) { val caretListener = object : CaretListener { override fun caretRemoved(event: CaretEvent) { listener.caretRemoved(event.caret?.vim) } } listenersMap[listener] = caretListener editor.caretModel.addCaretListener(caretListener) } override fun removeCaretListener(listener: VimCaretListener) { val caretListener = listenersMap.remove(listener) ?: error("Existing listener expected") editor.caretModel.removeCaretListener(caretListener) } override fun isDisposed(): Boolean { return editor.isDisposed } override fun removeSelection() { editor.selectionModel.removeSelection() } override fun getPath(): String? { return EditorHelper.getVirtualFile(editor)?.path } override fun extractProtocol(): String? { return EditorHelper.getVirtualFile(editor)?.getUrl()?.let { VirtualFileManager.extractProtocol(it) } } override fun visualPositionToOffset(position: VimVisualPosition): Offset { return editor.visualPositionToOffset(VisualPosition(position.line, position.column, position.leansRight)).offset } override fun exitInsertMode(context: ExecutionContext, operatorArguments: OperatorArguments) { editor.exitInsertMode(context.ij, operatorArguments) } override fun exitSelectModeNative(adjustCaret: Boolean) { this.exitSelectMode(adjustCaret) } override fun startGuardedBlockChecking() { val doc = editor.document doc.startGuardedBlockChecking() } override fun stopGuardedBlockChecking() { val doc = editor.document doc.stopGuardedBlockChecking() } override var vimLastSelectionType: SelectionType? get() = editor.vimLastSelectionType set(value) { editor.vimLastSelectionType = value } override fun isTemplateActive(): Boolean { return editor.isTemplateActive() } override fun hasUnsavedChanges(): Boolean { return EditorHelper.hasUnsavedChanges(this.editor) } override fun getLastVisualLineColumnNumber(line: Int): Int { return EditorUtil.getLastVisualLineColumnNumber(this.ij, line) } override fun visualPositionToBufferPosition(visualPosition: VimVisualPosition): BufferPosition { val logPosition = editor.visualToLogicalPosition( VisualPosition( visualPosition.line, visualPosition.column, visualPosition.leansRight ) ) return BufferPosition(logPosition.line, logPosition.column, logPosition.leansForward) } override fun bufferPositionToVisualPosition(position: BufferPosition): VimVisualPosition { val visualPosition = editor.logicalToVisualPosition(position.run { LogicalPosition(line, column, leansForward) }) return visualPosition.run { VimVisualPosition(line, column, leansRight) } } override fun createLiveMarker(start: Offset, end: Offset): LiveRange { return editor.document.createRangeMarker(start.point, end.point).vim } /** * Converts a logical line number to a visual line number. Several logical lines can map to the same * visual line when there are collapsed fold regions. */ override fun bufferLineToVisualLine(line: Int): Int { if (editor is EditorImpl) { // This is faster than simply calling Editor#logicalToVisualPosition return editor.offsetToVisualLine(editor.document.getLineStartOffset(line)) } return super.bufferLineToVisualLine(line) } override var insertMode: Boolean get() = (editor as? EditorEx)?.isInsertMode ?: false set(value) { (editor as? EditorEx)?.isInsertMode = value } override val document: VimDocument get() = IjVimDocument(editor.document) override fun createIndentBySize(size: Int): String { return IndentConfig.create(editor).createIndentBySize(size) } private fun Pair<Offset, Offset>.noGuard(editor: Editor): Boolean { return editor.document.getRangeGuard(this.first.point, this.second.point) == null } private inline fun Pair<Offset, Offset>.shift( shiftStart: Int = 0, shiftEnd: Int = 0, action: Pair<Offset, Offset>.() -> Unit, ) { val data = (this.first.point + shiftStart).coerceAtLeast(0).offset to (this.second.point + shiftEnd).coerceAtLeast(0).offset data.action() } override fun equals(other: Any?): Boolean { error("equals and hashCode should not be used with IjVimEditor") } override fun hashCode(): Int { error("equals and hashCode should not be used with IjVimEditor") } } val Editor.vim: IjVimEditor get() = IjVimEditor(this) val VimEditor.ij: Editor get() = (this as IjVimEditor).editor
mit
60d4663a832973162745fb1d8434ebcb
34.165919
144
0.740436
4.491409
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/viewmodel/pages/PageListDialogHelper.kt
1
6209
package org.wordpress.android.viewmodel.pages import org.wordpress.android.R import org.wordpress.android.analytics.AnalyticsTracker.Stat.UNPUBLISHED_REVISION_DIALOG_LOAD_LOCAL_VERSION_CLICKED import org.wordpress.android.analytics.AnalyticsTracker.Stat.UNPUBLISHED_REVISION_DIALOG_LOAD_UNPUBLISHED_VERSION_CLICKED import org.wordpress.android.analytics.AnalyticsTracker.Stat.UNPUBLISHED_REVISION_DIALOG_SHOWN import org.wordpress.android.fluxc.model.LocalOrRemoteId.RemoteId import org.wordpress.android.fluxc.model.PostModel import org.wordpress.android.ui.posts.PostUtils import org.wordpress.android.ui.utils.UiString.UiStringRes import org.wordpress.android.ui.utils.UiString.UiStringResWithParams import org.wordpress.android.ui.utils.UiString.UiStringText import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper import org.wordpress.android.viewmodel.helpers.DialogHolder import java.lang.NullPointerException private const val CONFIRM_ON_AUTOSAVE_REVISION_DIALOG_TAG = "CONFIRM_ON_AUTOSAVE_REVISION_DIALOG_TAG" private const val CONFIRM_DELETE_PAGE_DIALOG_TAG = "CONFIRM_DELETE_PAGE_DIALOG_TAG" private const val CONFIRM_COPY_CONFLICT_DIALOG_TAG = "CONFIRM_COPY_CONFLICT_DIALOG_TAG" private const val POST_TYPE = "post_type" class PageListDialogHelper( private val showDialog: (DialogHolder) -> Unit, private val analyticsTracker: AnalyticsTrackerWrapper ) { private var pageIdForAutosaveRevisionResolutionDialog: RemoteId? = null private var pageIdForDeleteDialog: RemoteId? = null private var pageIdForCopyDialog: RemoteId? = null fun showAutoSaveRevisionDialog(page: PostModel) { analyticsTracker.track(UNPUBLISHED_REVISION_DIALOG_SHOWN, mapOf(POST_TYPE to "page")) val dialogHolder = DialogHolder( tag = CONFIRM_ON_AUTOSAVE_REVISION_DIALOG_TAG, title = UiStringRes(R.string.dialog_confirm_autosave_title), message = PostUtils.getCustomStringForAutosaveRevisionDialog(page), positiveButton = UiStringRes(R.string.dialog_confirm_autosave_restore_button), negativeButton = UiStringRes(R.string.dialog_confirm_autosave_dont_restore_button) ) pageIdForAutosaveRevisionResolutionDialog = RemoteId(page.remotePostId) showDialog.invoke(dialogHolder) } fun showDeletePageConfirmationDialog(pageId: RemoteId, pageTitle: String) { val dialogHolder = DialogHolder( tag = CONFIRM_DELETE_PAGE_DIALOG_TAG, title = UiStringRes(R.string.delete_page), message = UiStringResWithParams( R.string.page_delete_dialog_message, listOf(UiStringText(pageTitle)) ), positiveButton = UiStringRes(R.string.delete), negativeButton = UiStringRes(R.string.cancel) ) pageIdForDeleteDialog = pageId showDialog.invoke(dialogHolder) } fun showCopyConflictDialog(page: PostModel) { val dialogHolder = DialogHolder( tag = CONFIRM_COPY_CONFLICT_DIALOG_TAG, title = UiStringRes(R.string.dialog_confirm_copy_local_title), message = UiStringRes(R.string.dialog_confirm_copy_local_message), positiveButton = UiStringRes(R.string.dialog_confirm_copy_local_edit_button), negativeButton = UiStringRes(R.string.dialog_confirm_copy_local_copy_button) ) pageIdForCopyDialog = RemoteId(page.remotePostId) showDialog.invoke(dialogHolder) } fun onPositiveClickedForBasicDialog( instanceTag: String, deletePage: (RemoteId) -> Unit, editPage: (RemoteId, LoadAutoSaveRevision) -> Unit, editPageFirst: (RemoteId) -> Unit ) { when (instanceTag) { CONFIRM_DELETE_PAGE_DIALOG_TAG -> pageIdForDeleteDialog?.let { pageIdForDeleteDialog = null deletePage(it) } ?: throw NullPointerException("pageIdForDeleteDialog shouldn't be null.") CONFIRM_ON_AUTOSAVE_REVISION_DIALOG_TAG -> pageIdForAutosaveRevisionResolutionDialog?.let { // open the editor with the restored auto save pageIdForAutosaveRevisionResolutionDialog = null editPage(it, true) analyticsTracker.track( UNPUBLISHED_REVISION_DIALOG_LOAD_UNPUBLISHED_VERSION_CLICKED, mapOf(POST_TYPE to "page") ) } ?: throw NullPointerException("pageIdForAutosaveRevisionResolutionDialog shouldn't be null.") CONFIRM_COPY_CONFLICT_DIALOG_TAG -> pageIdForCopyDialog?.let { pageIdForCopyDialog = null editPageFirst(it) } ?: throw NullPointerException("pageIdForCopyDialog shouldn't be null.") else -> throw IllegalArgumentException("Dialog's positive button click is not handled: $instanceTag") } } fun onNegativeClickedForBasicDialog( instanceTag: String, editPage: (RemoteId, LoadAutoSaveRevision) -> Unit, copyPage: (RemoteId) -> Unit ) { when (instanceTag) { CONFIRM_DELETE_PAGE_DIALOG_TAG -> pageIdForDeleteDialog = null CONFIRM_ON_AUTOSAVE_REVISION_DIALOG_TAG -> pageIdForAutosaveRevisionResolutionDialog?.let { // open the editor with the local page (don't use the auto save version) editPage(it, false) analyticsTracker.track( UNPUBLISHED_REVISION_DIALOG_LOAD_LOCAL_VERSION_CLICKED, mapOf(POST_TYPE to "page") ) } ?: throw NullPointerException("pageIdForAutosaveRevisionResolutionDialog shouldn't be null.") CONFIRM_COPY_CONFLICT_DIALOG_TAG -> pageIdForCopyDialog?.let { pageIdForCopyDialog = null copyPage(it) } ?: throw NullPointerException("pageIdForCopyDialog shouldn't be null.") else -> throw IllegalArgumentException("Dialog's negative button click is not handled: $instanceTag") } } }
gpl-2.0
034c1ea00c1f77ac67a7e7ef2a6ce3dd
49.893443
121
0.675793
5.122937
false
false
false
false
squanchy-dev/squanchy-android
app/src/main/java/net/squanchy/tweets/service/TweetModelConverter.kt
1
5405
package net.squanchy.tweets.service import net.squanchy.service.firebase.model.twitter.FirestoreTweet import net.squanchy.service.firebase.model.twitter.FirestoreTwitterHashtag import net.squanchy.service.firebase.model.twitter.FirestoreTwitterMedia import net.squanchy.service.firebase.model.twitter.FirestoreTwitterMention import net.squanchy.service.firebase.model.twitter.FirestoreTwitterUrl import net.squanchy.tweets.domain.TweetLinkInfo import net.squanchy.tweets.domain.view.TweetViewModel import net.squanchy.tweets.domain.view.User import net.squanchy.tweets.view.TweetUrlSpanFactory private const val MEDIA_TYPE_PHOTO = "photo" fun mapToViewModel(factory: TweetUrlSpanFactory, tweet: FirestoreTweet): TweetViewModel { val user = User(name = tweet.user.name, screenName = tweet.user.screenName, photoUrl = tweet.user.profileImageUrl) val emojiIndices = findEmojiIndices(tweet.text) val displayTextRange = Range.from(tweet.displayTextRange, tweet.text.length, emojiIndices.size) val hashtags = adjustHashtag(onlyHashtagsInRange(tweet.entities.hashtags, displayTextRange), emojiIndices) val mentions = adjustMentions(onlyMentionsInRange(tweet.entities.userMentions, displayTextRange), emojiIndices) val urls = adjustUrls(onlyUrlsInRange(tweet.entities.urls, displayTextRange), emojiIndices) val photoUrls = onlyPhotoUrls(tweet.entities.media) val unresolvedPhotoUrl = tweet.entities.media.map { it.url } val displayableText = displayableTextFor(tweet.text, displayTextRange, unresolvedPhotoUrl) return TweetViewModel( id = tweet.id.toLong(), text = displayableText, spannedText = factory.applySpansToTweet(displayableText, displayTextRange.start(), hashtags, mentions, urls), user = user, createdAt = tweet.createdAt, photoUrl = photoUrlMaybeFrom(photoUrls), linkInfo = TweetLinkInfo(tweet) ) } private fun findEmojiIndices(text: String): List<Int> { val emojiIndices = mutableListOf<Int>() text.forEachIndexed { index, char -> if (Character.isHighSurrogate(char) && Character.isLowSurrogate(text[index + 1])) { emojiIndices.add(index) } } return emojiIndices } private fun onlyHashtagsInRange(entities: List<FirestoreTwitterHashtag>, displayTextRange: Range): List<FirestoreTwitterHashtag> = entities.filter { displayTextRange.contains(it.start, it.end) } private fun onlyMentionsInRange(entities: List<FirestoreTwitterMention>, displayTextRange: Range): List<FirestoreTwitterMention> = entities.filter { displayTextRange.contains(it.start, it.end) } private fun onlyUrlsInRange(entities: List<FirestoreTwitterUrl>, displayTextRange: Range): List<FirestoreTwitterUrl> = entities.filter { displayTextRange.contains(it.start, it.end) } private fun adjustHashtag(entities: List<FirestoreTwitterHashtag>, indices: List<Int>): List<FirestoreTwitterHashtag> { for (hashtag in entities) { val offset = offsetFrom(hashtag.start, indices) hashtag.start = hashtag.start + offset hashtag.end = hashtag.end + offset } return entities } private fun adjustMentions(entities: List<FirestoreTwitterMention>, indices: List<Int>): List<FirestoreTwitterMention> { for (mention in entities) { val offset = offsetFrom(mention.start, indices) mention.start = mention.start + offset mention.end = mention.end + offset } return entities } private fun adjustUrls(entities: List<FirestoreTwitterUrl>, indices: List<Int>): List<FirestoreTwitterUrl> { for (url in entities) { val offset = offsetFrom(url.start, indices) url.start = url.start + offset url.end = url.end + offset } return entities } private fun offsetFrom(start: Int, indices: List<Int>): Int { var offset = 0 indices.takeWhile { it - offset <= start } .forEach { offset += 1 } return offset } private fun onlyPhotoUrls(media: List<FirestoreTwitterMedia>): List<String> { return media.filter { it.type == MEDIA_TYPE_PHOTO } .map { it.mediaUrl } } private fun displayableTextFor(text: String, displayTextRange: Range, photoUrls: List<String>): String { val beginIndex = displayTextRange.start() val endIndex = displayTextRange.end() val displayableText = text.substring(beginIndex, endIndex) return removeLastPhotoUrl(displayableText, photoUrls) } private fun removeLastPhotoUrl(content: String, photoUrls: List<String>): String { if (photoUrls.isEmpty()) { return content } val lastUrl = photoUrls[photoUrls.size - 1] return if (content.endsWith(lastUrl)) { content.replace(lastUrl, "") .trim { it <= ' ' } } else { content } } private fun photoUrlMaybeFrom(urls: List<String>): String? = if (urls.isEmpty()) null else urls[0] private class Range(private val start: Int, private val end: Int) { internal fun start() = start internal fun end() = end internal fun contains(start: Int, end: Int): Boolean = start() <= start && end <= end() companion object { internal fun from(positions: List<Int>, textLength: Int, offset: Int): Range { return if (positions.size != 2) { Range(0, textLength - 1) } else { Range(positions[0], positions[1] + offset) } } } }
apache-2.0
e9ee706a2612c253ff63fe5ccfedb920
37.884892
130
0.715449
4.362389
false
false
false
false
GunoH/intellij-community
plugins/github/src/org/jetbrains/plugins/github/authentication/accounts/GithubProjectDefaultAccountHolder.kt
7
1668
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.github.authentication.accounts import com.intellij.collaboration.auth.PersistentDefaultAccountHolder import com.intellij.notification.NotificationType import com.intellij.openapi.application.runInEdt import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.components.StoragePathMacros import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.VcsNotifier import org.jetbrains.plugins.github.i18n.GithubBundle import org.jetbrains.plugins.github.util.GithubNotificationIdsHolder import org.jetbrains.plugins.github.util.GithubNotifications import org.jetbrains.plugins.github.util.GithubUtil /** * Handles default Github account for project */ @State(name = "GithubDefaultAccount", storages = [Storage(StoragePathMacros.WORKSPACE_FILE)], reportStatistic = false) internal class GithubProjectDefaultAccountHolder(project: Project) : PersistentDefaultAccountHolder<GithubAccount>(project) { override fun accountManager() = service<GHAccountManager>() override fun notifyDefaultAccountMissing() = runInEdt { val title = GithubBundle.message("accounts.default.missing") GithubUtil.LOG.info("${title}; ${""}") VcsNotifier.IMPORTANT_ERROR_NOTIFICATION.createNotification(title, NotificationType.WARNING) .setDisplayId(GithubNotificationIdsHolder.MISSING_DEFAULT_ACCOUNT) .addAction(GithubNotifications.getConfigureAction(project)) .notify(project) } }
apache-2.0
8f1bc3c6f6fcfdfb120ad7b61188f21d
46.685714
120
0.821343
4.765714
false
false
false
false
ktorio/ktor
ktor-utils/js/src/io/ktor/util/date/DateJs.kt
1
1696
/* * 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.util.date import kotlin.js.* /** * Create new gmt date from the [timestamp]. * @param timestamp is a number of epoch milliseconds (it is `now` by default). */ public actual fun GMTDate(timestamp: Long?): GMTDate { val date = timestamp?.toDouble()?.let { Date(it) } ?: Date() if (date.getTime().isNaN()) throw InvalidTimestampException(timestamp!!) with(date) { /* from SUNDAY 0 -> MONDAY 0 */ val dayOfWeek = WeekDay.from((getUTCDay() + 6) % 7) val month = Month.from(getUTCMonth()) return GMTDate( getUTCSeconds(), getUTCMinutes(), getUTCHours(), dayOfWeek, getUTCDate(), getUTCFullYear(), month, getUTCFullYear(), getTime().toLong() ) } } /** * Create an instance of [GMTDate] from the specified date/time components */ public actual fun GMTDate(seconds: Int, minutes: Int, hours: Int, dayOfMonth: Int, month: Month, year: Int): GMTDate { val timestamp = Date.UTC(year, month.ordinal, dayOfMonth, hours, minutes, seconds).toLong() return GMTDate(timestamp) } /** * Invalid exception: possible overflow or underflow */ public class InvalidTimestampException(timestamp: Long) : IllegalStateException( "Invalid date timestamp exception: $timestamp" ) /** * Gets current system time in milliseconds since certain moment in the past, only delta between two subsequent calls makes sense. */ public actual fun getTimeMillis(): Long = Date().getTime().toLong()
apache-2.0
bb9b1f57dc7369e1ce22e130501f2f71
27.745763
130
0.649175
4.326531
false
false
false
false
CzBiX/v2ex-android
app/src/main/kotlin/com/czbix/v2ex/ui/adapter/NodeController.kt
1
3482
package com.czbix.v2ex.ui.adapter import android.text.TextUtils import android.view.View import android.widget.ImageView import android.widget.TextView import com.airbnb.epoxy.EpoxyAttribute import com.airbnb.epoxy.EpoxyController import com.airbnb.epoxy.EpoxyModelClass import com.airbnb.epoxy.EpoxyModelWithHolder import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions import com.czbix.v2ex.R import com.czbix.v2ex.model.Node import com.czbix.v2ex.ui.ExHolder import com.czbix.v2ex.ui.fragment.NodeListFragment import com.czbix.v2ex.util.ViewUtils class NodeController(private val listener: NodeListFragment.OnNodeActionListener) : EpoxyController() { private var allData: List<Node>? = null private var currentData: List<Node>? = null private var lastFilter: String? = null fun setData(data: List<Node>?) { allData = data currentData = data if (lastFilter == null) { requestModelBuild() } else { filterText(lastFilter!!) } } override fun buildModels() { currentData?.forEach { node -> nodeControllerNode { id(node.id) node(node) listener([email protected]) } } } fun filterText(query: String) { currentData = if (TextUtils.isEmpty(query)) { allData } else { allData?.filter { node -> node.name.contains(query) || node.title!!.contains(query) || node.titleAlternative != null && node.titleAlternative.contains(query) } } requestDelayedModelBuild(100) } @EpoxyModelClass(layout = R.layout.view_node) abstract class NodeModel : EpoxyModelWithHolder<NodeModel.Holder>(), View.OnClickListener { @EpoxyAttribute lateinit var node: Node @EpoxyAttribute(EpoxyAttribute.Option.DoNotHash) lateinit var listener: NodeListFragment.OnNodeActionListener override fun bind(holder: Holder) { holder.apply { view.setOnClickListener(this@NodeModel) title.text = node.title val alternative = node.titleAlternative if (alternative.isNullOrEmpty()) { alertTitle.text = null alertTitle.visibility = View.INVISIBLE } else { alertTitle.text = alternative alertTitle.visibility = View.VISIBLE } setAvatarImg(this, node) } } override fun unbind(holder: Holder) { holder.glide.clear(holder.avatar) } fun setAvatarImg(holder: Holder, node: Node) { val glide = holder.glide val avatar = node.avatar ?: return val pixel = ViewUtils.getDimensionPixelSize(R.dimen.node_avatar_size) glide.load(avatar.getUrlByPx(pixel)) .transition(DrawableTransitionOptions.withCrossFade()).into(holder.avatar) } override fun onClick(v: View) { ViewUtils.hideInputMethod(v) listener.onNodeOpen(node) } class Holder : ExHolder<View>() { val title by bind<TextView>(R.id.title) val alertTitle by bind<TextView>(R.id.alertTitle) val avatar by bind<ImageView>(R.id.avatar_img) } } }
apache-2.0
faf8b563aed08cdde4dd95ddf3220be7
30.944954
103
0.606548
4.743869
false
false
false
false
onnerby/musikcube
src/musikdroid/app/src/main/java/io/casey/musikcube/remote/service/playback/impl/remote/Metadata.kt
2
1673
package io.casey.musikcube.remote.service.playback.impl.remote object Metadata { object Track { const val ID = "id" const val EXTERNAL_ID = "external_id" const val URI = "uri" const val TITLE = "title" const val ALBUM = "album" const val ALBUM_ID = "album_id" const val ALBUM_ARTIST = "album_artist" const val ALBUM_ARTIST_ID = "album_artist_id" const val GENRE = "genre" const val TRACK_NUM = "track_num" const val GENRE_ID = "genre_id" const val ARTIST = "artist" const val ARTIST_ID = "artist_id" const val THUMBNAIL_ID = "thumbnail_id" } object Album { const val ID = "id" const val TITLE = "title" const val ALBUM_ARTIST = "album_artist" const val ALBUM_ARTIST_ID = "album_artist_id" const val ARTIST = "artist" const val ARTIST_ID = "artist_id" const val THUMBNAIL_ID = "thumbnail_id" } object Category { const val OFFLINE = "offline" const val ALBUM = "album" const val ARTIST = "artist" const val ALBUM_ARTIST = "album_artist" const val GENRE = "genre" const val TRACKS = "track" const val PLAYLISTS = "playlists" } object Output { const val DRIVER_NAME = "driver_name" const val DEVICES = "devices" } object Device { const val DEVICE_NAME = "device_name" const val DEVICE_ID = "device_id" } object Environment { const val API_VERSION = "api_version" const val SDK_VERSION = "sdk_version" const val APP_VERSION = "app_version" } }
bsd-3-clause
1bade70ac01a8b5fcce68e8529915d7d
28.875
62
0.577406
3.908879
false
false
false
false
ClearVolume/scenery
src/test/kotlin/graphics/scenery/tests/unit/AxisTests.kt
2
5396
package graphics.scenery.tests.unit import graphics.scenery.numerics.Random import graphics.scenery.proteins.Axis import graphics.scenery.utils.LazyLogger import org.joml.Vector3f import org.junit.Test import kotlin.math.absoluteValue import kotlin.test.assertEquals import kotlin.test.assertTrue /** * This is the test for the axis class. * * @author Justin Buerger <[email protected]> */ class AxisTests { private val logger by LazyLogger() /** * Tests what happens when the axis gets a list of less then four points as a parameter */ @Test fun testTooFewPositions() { logger.info("Tests the result if to few positions are provided.") val list = listOf(Random.random3DVectorFromRange(-10f, 10f),Random.random3DVectorFromRange(-10f, 10f), Random.random3DVectorFromRange(-10f, 10f)) val axis = Axis(list) assertEquals(axis.direction, Vector3f()) assertEquals(axis.position, Vector3f()) } /** * Test what happens when one of the positions for the axis becomes null. */ @Test fun testNullPositions() { logger.info("Test the behaviour of the axis if one of the positions is null") val list = listOf(Random.random3DVectorFromRange(-10f, 10f),Random.random3DVectorFromRange(-10f, 10f), Random.random3DVectorFromRange(-10f, 10f), null) val axis = Axis(list) assertEquals(axis.direction, Vector3f()) assertEquals(axis.position, Vector3f()) } /** * Tests the least square approach for approximating the axis line. */ @Test fun testLeastSquare() { logger.info("Test if the least square algorithm works good enough") //adding points around the z axis val points = ArrayList<Vector3f>(50) val p0= Vector3f(+0f, +1f, 0f) points.add(p0) val p1= Vector3f(-1f, -0f, 1f) points.add(p1) val p2= Vector3f(+0f, +1f, 2f) points.add(p2) val p3= Vector3f(-1f, -0f, 3f) points.add(p3) val p4= Vector3f(+0f, +1f, 4f) points.add(p4) val p5= Vector3f(-1f, -0f, 5f) points.add(p5) val p6= Vector3f(+0f, +1f, 6f) points.add(p6) val p7= Vector3f(-1f, -0f, 7f) points.add(p7) val p8= Vector3f(+0f, +1f, 8f) points.add(p8) val p9= Vector3f(-1f, -0f, 9f) points.add(p9) val p10= Vector3f(+0f, +1f, 10f) points.add(p10) val p11= Vector3f(-1f, -0f, 11f) points.add(p11) val p12= Vector3f(+0f, +1f, 12f) points.add(p12) val p13= Vector3f(-1f, -0f, 13f) points.add(p13) val p14= Vector3f(+0f, +1f, 14f) points.add(p14) val p15= Vector3f(-1f, -0f, 15f) points.add(p15) val p16= Vector3f(+0f, +1f, 16f) points.add(p16) val p17= Vector3f(-1f, -0f, 17f) points.add(p17) val p18= Vector3f(+0f, +1f, 18f) points.add(p18) val p19= Vector3f(-1f, -0f, 19f) points.add(p19) val p20= Vector3f(+0f, +1f, 20f) points.add(p20) val p21= Vector3f(-1f, -0f, 21f) points.add(p21) val p22= Vector3f(+0f, +1f, 22f) points.add(p22) val p23= Vector3f(-1f, -0f, 23f) points.add(p23) val p24= Vector3f(+0f, +1f, 24f) points.add(p24) val p25= Vector3f(-1f, -0f, 25f) points.add(p25) val p26= Vector3f(+0f, +1f, 26f) points.add(p26) val p27= Vector3f(-1f, -0f, 27f) points.add(p27) val p28= Vector3f(+0f, +1f, 28f) points.add(p28) val p29= Vector3f(-1f, -0f, 29f) points.add(p29) val p30= Vector3f(+0f, +1f, 30f) points.add(p30) val p31= Vector3f(-1f, -0f, 31f) points.add(p31) val p32= Vector3f(+0f, +1f, 32f) points.add(p32) val p33= Vector3f(-1f, -0f, 33f) points.add(p33) val p34= Vector3f(+0f, +1f, 34f) points.add(p34) val p35= Vector3f(-1f, -0f, 35f) points.add(p35) val p36= Vector3f(+0f, +1f, 36f) points.add(p36) val p37= Vector3f(-1f, -0f, 37f) points.add(p37) val p38= Vector3f(+0f, +1f, 38f) points.add(p38) val p39= Vector3f(-1f, -0f, 39f) points.add(p39) val p40= Vector3f(+0f, +1f, 40f) points.add(p40) val p41= Vector3f(-1f, -0f, 41f) points.add(p41) val p42= Vector3f(+0f, +1f, 42f) points.add(p42) val p43= Vector3f(-1f, -0f, 43f) points.add(p43) val p44= Vector3f(+0f, +1f, 44f) points.add(p44) val p45= Vector3f(-1f, -0f, 45f) points.add(p45) val p46= Vector3f(+0f, +1f, 46f) points.add(p46) val p47= Vector3f(-1f, -0f, 47f) points.add(p47) val p48= Vector3f(+0f, +1f, 48f) points.add(p48) val p49= Vector3f(-1f, -0f, 49f) points.add(p49) val p50= Vector3f(+0f, +1f, 50f) points.add(p50) val lq = Axis.leastSquare(points) //the direction should now be approximately the z axis assertTrue { lq.direction.x().absoluteValue < 0.1f} assertTrue { lq.direction.y().absoluteValue < 0.1f} assertTrue { 0.9f < lq.direction.z() && lq.direction.z() < 1.1f } } }
lgpl-3.0
ce2138e758844ba23508f00f054113a2
31.902439
110
0.568755
2.848997
false
true
false
false
ClearVolume/scenery
src/main/kotlin/graphics/scenery/backends/vulkan/OpenGLSwapchain.kt
1
19378
package graphics.scenery.backends.vulkan import com.jogamp.opengl.GL2ES3.GL_MAJOR_VERSION import com.jogamp.opengl.GL2ES3.GL_MINOR_VERSION import com.sun.jna.Pointer import com.sun.jna.platform.win32.User32 import com.sun.jna.platform.win32.WinDef import graphics.scenery.Hub import graphics.scenery.backends.RenderConfigReader import graphics.scenery.backends.SceneryWindow import graphics.scenery.utils.SceneryPanel import org.lwjgl.PointerBuffer import org.lwjgl.glfw.GLFW.* import org.lwjgl.glfw.GLFWNativeGLX.glfwGetGLXWindow import org.lwjgl.glfw.GLFWNativeWin32.glfwGetWin32Window import org.lwjgl.glfw.GLFWNativeX11.glfwGetX11Display import org.lwjgl.glfw.GLFWWindowSizeCallback import org.lwjgl.opengl.GL import org.lwjgl.opengl.GL30.* import org.lwjgl.opengl.GLXNVSwapGroup import org.lwjgl.opengl.NVDrawVulkanImage import org.lwjgl.opengl.WGLNVSwapGroup import org.lwjgl.system.MemoryStack import org.lwjgl.system.MemoryUtil import org.lwjgl.system.MemoryUtil.NULL import org.lwjgl.system.MemoryUtil.memAllocInt import org.lwjgl.system.Platform import org.lwjgl.vulkan.VK10 import org.lwjgl.vulkan.VK10.* import org.lwjgl.vulkan.VkFenceCreateInfo import org.lwjgl.vulkan.VkQueue import org.lwjgl.vulkan.VkSemaphoreCreateInfo import java.nio.LongBuffer /** * GLFW-based OpenGL swapchain and window, using Nvidia's NV_draw_vulkan_image GL extension. * The swapchain will reside on [device] and submit to [queue]. All other parameters are not used. * * @author Ulrik Günther <[email protected]> */ class OpenGLSwapchain(device: VulkanDevice, queue: VkQueue, commandPools: VulkanRenderer.CommandPools, renderConfig: RenderConfigReader.RenderConfig, useSRGB: Boolean = true, val useFramelock: Boolean = System.getProperty("scenery.Renderer.Framelock", "false")?.toBoolean() ?: false, val bufferCount: Int = 2, override val undecorated: Boolean = System.getProperty("scenery.Renderer.ForceUndecoratedWindow", "false")?.toBoolean() ?: false) : VulkanSwapchain(device, queue, commandPools, renderConfig, useSRGB) { /** Swapchain handle. */ override var handle: Long = 0L /** Array for rendered images. */ override var images: LongArray = LongArray(0) /** Array for image views. */ override var imageViews: LongArray = LongArray(0) /** Color format of the images. */ override var format: Int = 0 /** Window instance to use. */ lateinit override var window: SceneryWindow//.GLFWWindow /** List of supported OpenGL extensions. */ val supportedExtensions = ArrayList<String>() private val WINDOW_RESIZE_TIMEOUT = 200 * 10e6 /** * Creates a window for this swapchain, and initialiases [win] as [SceneryWindow.GLFWWindow]. * Needs to be handed a [VulkanRenderer.SwapchainRecreator]. * Returns the initialised [SceneryWindow]. */ override fun createWindow(win: SceneryWindow, swapchainRecreator: VulkanRenderer.SwapchainRecreator): SceneryWindow { glfwDefaultWindowHints() glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API) glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE) glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE) glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4) glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5) glfwWindowHint(GLFW_SRGB_CAPABLE, if(useSRGB) { GLFW_TRUE } else { GLFW_FALSE }) glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE) if(undecorated) { glfwWindowHint(GLFW_DECORATED, GLFW_FALSE) } glfwWindowHint(GLFW_STEREO, if (renderConfig.stereoEnabled) { GLFW_TRUE } else { GLFW_FALSE }) val w = glfwCreateWindow(win.width, win.height, "scenery", MemoryUtil.NULL, MemoryUtil.NULL) if(w == null) { val buffer = PointerBuffer.allocateDirect(255) glfwGetError(buffer) throw IllegalStateException("Window could not be created: ${buffer.stringUTF8}") } window = SceneryWindow.GLFWWindow(w).apply { glfwSetWindowPos(w, 100, 100) // Handle canvas resize windowSizeCallback = object : GLFWWindowSizeCallback() { override operator fun invoke(window: Long, w: Int, h: Int) { if (lastResize > 0L && lastResize + WINDOW_RESIZE_TIMEOUT < System.nanoTime()) { lastResize = System.nanoTime() return } if (width <= 0 || height <= 0) return width = w height = h swapchainRecreator.mustRecreate = true lastResize = -1L } } glfwSetWindowSizeCallback(window, windowSizeCallback) glfwShowWindow(window) } window.width = win.width window.height = win.height return window } /** * Creates a new swapchain and returns it, potentially recycling or deallocating [oldSwapchain]. * In the special case of the [OpenGLSwapchain], an OpenGL context is created and checked for the * GL_NV_draw_vulkan_image extension, which it requires. */ override fun create(oldSwapchain: Swapchain?): Swapchain { val window = this.window if(window !is SceneryWindow.GLFWWindow) { throw IllegalStateException("Cannot use a window of type ${window.javaClass.simpleName}") } presentedFrames = 0 glfwMakeContextCurrent(window.window) GL.createCapabilities() logger.info("OpenGL swapchain running OpenGL ${glGetInteger(GL_MAJOR_VERSION)}.${glGetInteger(GL_MINOR_VERSION)} on ${glGetString(GL_RENDERER)}") (0 until glGetInteger(GL_NUM_EXTENSIONS)).map { supportedExtensions.add(glGetStringi(GL_EXTENSIONS, it) ?: "") } if (!supportedExtensions.contains("GL_NV_draw_vulkan_image")) { logger.error("NV_draw_vulkan_image not supported. Please use standard Vulkan swapchain.") throw UnsupportedOperationException("NV_draw_vulkan_image not supported. Please use standard Vulkan swapchain.") } format = if (useSRGB) { VK10.VK_FORMAT_B8G8R8A8_SRGB } else { VK10.VK_FORMAT_B8G8R8A8_UNORM } if (window.width <= 0 || window.height <= 0) { logger.warn("Received invalid window dimensions, resizing to sane values") // TODO: Better default values window.width = 2560 window.height = 1600 } val windowWidth = if(renderConfig.stereoEnabled && window.width < 10000) { window.width } else { window.width } logger.info("Creating backing images with ${windowWidth}x${window.height}") val semaphoreCreateInfo = VkSemaphoreCreateInfo.calloc() .sType(VK10.VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO) val fenceCreateInfo = VkFenceCreateInfo.calloc() .sType(VK10.VK_STRUCTURE_TYPE_FENCE_CREATE_INFO) presentQueue = VU.createDeviceQueue(device, device.queues.graphicsQueue.first) val imgs = (0 until bufferCount).map { with(VU.newCommandBuffer(device, commandPools.Standard, autostart = true)) { val t = VulkanTexture([email protected], commandPools, queue, queue, windowWidth, window.height, 1, format, 1) val image = t.createImage(windowWidth, window.height, 1, format, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT or VK_IMAGE_USAGE_SAMPLED_BIT, VK_IMAGE_TILING_OPTIMAL, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 1) VulkanTexture.transitionLayout(image.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, 1, commandBuffer = this) val view = t.createImageView(image, format) imageAvailableSemaphores.add([email protected]()) imageRenderedSemaphores.add([email protected]()) fences.add(VU.getLong("Swapchain image fence", { VK10.vkCreateFence([email protected], fenceCreateInfo, null, this) }, {})) imageUseFences.add(VU.getLong("Swapchain image usage fence", { VK10.vkCreateFence([email protected], fenceCreateInfo, null, this) }, {})) inFlight.add(null) endCommandBuffer([email protected], commandPools.Standard, queue, flush = true, dealloc = true) Pair(image.image, view) } } images = imgs.map { it.first }.toLongArray() imageViews = imgs.map { it.second }.toLongArray() handle = -1L glfwSwapInterval(0) glfwShowWindow(window.window) glEnable(GL_FRAMEBUFFER_SRGB) if (useFramelock) { enableFramelock() } fenceCreateInfo.free() semaphoreCreateInfo.free() return this } /** * Enables frame-locking for this swapchain, locking buffer swap events to other screens/machines. * Works only if the WGL_NV_swap_group (Windows) or GLX_NV_swap_group extension is supported. */ fun enableFramelock(): Boolean { val window = this.window if(window !is SceneryWindow.GLFWWindow) { throw IllegalStateException("Cannot use a window of type ${window.javaClass.simpleName}") } if (!supportedExtensions.contains("WGL_NV_swap_group") && !supportedExtensions.contains("GLX_NV_swap_group")) { logger.warn("Framelock requested, but not supported on this hardware.") // TODO: Figure out why K6000 does not report WGL_NV_swap_group correctly. // return false } val swapGroup = System.getProperty("scenery.VulkanRenderer.SwapGroup", "1").toInt() val swapBarrier = System.getProperty("scenery.VulkanRenderer.SwapBarrier", "1").toInt() val maxGroups = memAllocInt(1) val maxBarriers = memAllocInt(1) when (Platform.get()) { Platform.WINDOWS -> { val hwnd = glfwGetWin32Window(window.window) val hwndP = WinDef.HWND(Pointer(hwnd)) val hdc = User32.INSTANCE.GetDC(hwndP) WGLNVSwapGroup.wglQueryMaxSwapGroupsNV(Pointer.nativeValue(hdc.pointer), maxGroups, maxBarriers) if (!WGLNVSwapGroup.wglJoinSwapGroupNV(Pointer.nativeValue(hdc.pointer), swapGroup)) { logger.error("Failed to bind to swap group $swapGroup") return false } if (!WGLNVSwapGroup.wglBindSwapBarrierNV(swapGroup, swapBarrier)) { logger.error("Failed to bind to swap barrier $swapBarrier on swap group $swapGroup") return false } logger.info("Joined swap barrier $swapBarrier on swap group $swapGroup") return true } Platform.LINUX -> { val display = glfwGetX11Display() val glxWindow = glfwGetGLXWindow(window.window) GLXNVSwapGroup.glXQueryMaxSwapGroupsNV(display, 0, maxGroups, maxBarriers) if (GLXNVSwapGroup.glXJoinSwapGroupNV(display, glxWindow, swapGroup)) { logger.error("Failed to bind to swap group $swapGroup") return false } if (GLXNVSwapGroup.glXBindSwapBarrierNV(display, swapGroup, swapBarrier)) { logger.error("Failed to bind to swap barrier $swapBarrier on swap group $swapGroup") return false } logger.info("Joined swap barrier $swapBarrier on swap group $swapGroup") return true } else -> { logger.warn("Hardware Framelock not supported on this platform.") return false } } } /** * Disables frame-lock for this swapchain. */ @Suppress("unused") fun disableFramelock() { val window = this.window if(window !is SceneryWindow.GLFWWindow) { throw IllegalStateException("Cannot use a window of type ${window.javaClass.simpleName}") } if (!supportedExtensions.contains("WGL_NV_swap_group")) { logger.warn("Framelock requested, but not supported on this hardware.") return } when (Platform.get()) { Platform.WINDOWS -> { val hwnd = glfwGetWin32Window(window.window) val hwndP = WinDef.HWND(Pointer(hwnd)) val hdc = User32.INSTANCE.GetDC(hwndP) WGLNVSwapGroup.wglJoinSwapGroupNV(Pointer.nativeValue(hdc.pointer), 0) } Platform.LINUX -> { val display = glfwGetX11Display() val glxWindow = glfwGetGLXWindow(window.window) GLXNVSwapGroup.glXJoinSwapGroupNV(display, glxWindow, 0) } else -> logger.error("Hardware Framelock not supported on this platform.") } } /** * Presents the currently rendered image, drawing the Vulkan image into the current * OpenGL context. */ override fun present(waitForSemaphores: LongBuffer?) { val window = this.window if(window !is SceneryWindow.GLFWWindow) { throw IllegalStateException("Cannot use a window of type ${window.javaClass.simpleName}") } glDisable(GL_DEPTH_TEST) waitForSemaphores?.let { NVDrawVulkanImage.glWaitVkSemaphoreNV(waitForSemaphores.get(0)) } // note: glDrawVkImageNV expects the OpenGL screen space conventions, // so the Vulkan image's ST coordinates have to be flipped if (renderConfig.stereoEnabled) { glDrawBuffer(GL_BACK_LEFT) glClear(GL_COLOR_BUFFER_BIT) glDisable(GL_DEPTH_TEST) NVDrawVulkanImage.glDrawVkImageNV(images[presentedFrames.toInt() % bufferCount], 0, 0.0f, 0.0f, window.width.toFloat(), window.height.toFloat(), 0.0f, 0.0f, 1.0f, 0.5f, 0.0f) glDrawBuffer(GL_BACK_RIGHT) glClear(GL_COLOR_BUFFER_BIT) glDisable(GL_DEPTH_TEST) NVDrawVulkanImage.glDrawVkImageNV(images[presentedFrames.toInt() % bufferCount], 0, 0.0f, 0.0f, window.width.toFloat(), window.height.toFloat(), 0.0f, 0.5f, 1.0f, 1.0f, 0.0f) } else { glClear(GL_COLOR_BUFFER_BIT) NVDrawVulkanImage.glDrawVkImageNV(images[presentedFrames.toInt() % bufferCount], 0, 0.0f, 0.0f, window.width.toFloat(), window.height.toFloat(), 0.0f, 0.0f, 1.0f, 1.0f, 0.0f) } glfwSwapBuffers(window.window) presentedFrames++ } /** * Post-present routine, does nothing in this case. */ override fun postPresent(image: Int) { currentImage = (currentImage + 1) % images.size } /** * Proceeds to the next swapchain image. */ override fun next(timeout: Long): Pair<Long, Long>? { // NVDrawVulkanImage.glSignalVkSemaphoreNV(-1L) // return (presentedFrames % 2) to -1L//.toInt() MemoryStack.stackPush().use { stack -> VK10.vkQueueWaitIdle(queue) val signal = stack.mallocLong(1) signal.put(0, imageAvailableSemaphores[currentImage]) with(VU.newCommandBuffer(device, commandPools.Standard, autostart = true)) { endCommandBuffer([email protected], commandPools.Standard, queue, flush = true, dealloc = true, fence = imageUseFences[currentImage], signalSemaphores = signal) } } return imageAvailableSemaphores[currentImage] to imageUseFences[currentImage] } /** * Toggles fullscreen. */ override fun toggleFullscreen(hub: Hub, swapchainRecreator: VulkanRenderer.SwapchainRecreator) { val window = this.window if(window !is SceneryWindow.GLFWWindow) { throw IllegalStateException("Cannot use a window of type ${window.javaClass.simpleName}") } if (window.isFullscreen) { glfwSetWindowMonitor(window.window, NULL, 0, 0, window.width, window.height, GLFW_DONT_CARE) glfwSetWindowPos(window.window, 100, 100) glfwSetInputMode(window.window, GLFW_CURSOR, GLFW_CURSOR_NORMAL) swapchainRecreator.mustRecreate = true window.isFullscreen = false } else { val preferredMonitor = System.getProperty("scenery.FullscreenMonitor", "0").toInt() val monitor = if (preferredMonitor == 0) { glfwGetPrimaryMonitor() } else { val monitors = glfwGetMonitors() if (monitors != null && monitors.remaining() >= preferredMonitor) { monitors.get(preferredMonitor) } else { glfwGetPrimaryMonitor() } } val hmd = hub.getWorkingHMDDisplay() if (hmd != null) { window.width = hmd.getRenderTargetSize().x() / 2 window.height = hmd.getRenderTargetSize().y() logger.info("Set fullscreen window dimensions to ${window.width}x${window.height}") } glfwSetWindowMonitor(window.window, monitor, 0, 0, window.width, window.height, GLFW_DONT_CARE) glfwSetInputMode(window.window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN) swapchainRecreator.mustRecreate = true window.isFullscreen = true } } /** * Embeds the swapchain into a [SceneryFXPanel]. Not supported by [OpenGLSwapchain], see [FXSwapchain] instead. */ override fun embedIn(panel: SceneryPanel?) { if(panel != null) { logger.error("Embedding is not supported with the OpenGL-based swapchain. Use FXSwapchain instead.") } } /** * Returns the number of presented frames. */ override fun presentedFrames(): Long { return presentedFrames } /** * Closes the swapchain, freeing all of its resources. */ override fun close() { val window = this.window if(window !is SceneryWindow.GLFWWindow) { throw IllegalStateException("Cannot use a window of type ${window.javaClass.simpleName}") } vkQueueWaitIdle(queue) closeSyncPrimitives() windowSizeCallback.close() glfwDestroyWindow(window.window) } companion object: SwapchainParameters { override var headless = false override var usageCondition = { _: SceneryPanel? -> java.lang.Boolean.parseBoolean(System.getProperty("scenery.VulkanRenderer.UseOpenGLSwapchain", "false")) } } }
lgpl-3.0
e428bd4856abffe36b248bcad5894a06
37.296443
223
0.619497
4.656813
false
false
false
false
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/visualization/HideEmptyItemStrategy.kt
1
1896
/* * 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.visualization enum class HideEmptyItemStrategy { NONE, BEFORE_FIRST, AFTER_LAST, BEFORE_FIRST_AFTER_LAST, ALL; open fun isHide(): Boolean { return this == BEFORE_FIRST || this == AFTER_LAST || this == BEFORE_FIRST_AFTER_LAST || this == ALL } }
bsd-3-clause
a67dfcdf945b2536ebce1477e2f6e2e2
46.4
107
0.747363
4.471698
false
false
false
false
dahlstrom-g/intellij-community
platform/util/base/src/com/intellij/smRunner/OutputEventSplitterBase.kt
8
6592
// 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.smRunner 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 OutputEventSplitterBase<T>(private val serviceMessagePrefix: String, private val bufferTextUntilNewLine: Boolean, private val cutNewLineBeforeServiceMessage: Boolean) { data class OutputType<T>(val data: T, val streamType: OutputStreamType) enum class OutputStreamType { STDOUT, STDERR, SYSTEM } private data class Output<T>(val text: String, val outputType: OutputType<T>) private var newLinePending = false private val prevRefs = OutputStreamType.values().associateWith { AtomicReference<Output<T>>() } /** * For stderr and system [text] is provided as fast as possible unless [bufferTextUntilNewLine]. * For stdout [text] is either TC message that starts from [serviceMessagePrefix] and ends with new line * or chunk of process output * */ abstract fun onTextAvailable(text: String, outputType: OutputType<T>) /** * Only stdout ([OutputType.streamType] == [OutputStreamType.STDOUT]) 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: OutputType<T>) { val prevRef = requireNotNull(prevRefs[outputType.streamType]) { "reference to ${outputType.streamType} stream type is missing" } 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)) } } private fun processInternal(text: String, outputType: OutputType<T>): String? { var from = 0 val processServiceMessages = outputType.streamType == OutputStreamType.STDOUT // new line char and teamcity message start are two reasons to flush previous text var newLineInd = text.indexOf('\n') var teamcityMessageStartInd = if (processServiceMessages) text.indexOf(serviceMessagePrefix) 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(serviceMessagePrefix, nextFrom + serviceMessagePrefix.length) } if (newLineInd != -1 && nextFrom == newLineInd + 1) { newLineInd = text.indexOf('\n', 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 serviceMessagePrefix.length - 1 downTo 1) { if (text.regionMatches(text.length - suffixSize, serviceMessagePrefix, 0, suffixSize)) { return suffixSize } } return 0 } /** * 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, outputType: OutputType<T>, lastFlush: Boolean = false) { if (cutNewLineBeforeServiceMessage && outputType.streamType == OutputStreamType.STDOUT) { if (newLinePending) { //Prev. flush was "\n". if (!text.startsWith(serviceMessagePrefix) || (lastFlush)) { onTextAvailable("\n", outputType) } newLinePending = false } if (text == "\n" && !lastFlush) { newLinePending = true return } } onTextAvailable(text, outputType) } }
apache-2.0
83f9a31acacf0f640a34b1499b6b71cb
39.944099
158
0.687803
4.565097
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/quickfix/fixes/WrapWithSafeLetCallFixFactories.kt
3
18653
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix.fixes import com.intellij.openapi.diagnostic.Logger import com.intellij.psi.PsiElement import com.intellij.psi.SmartPsiElementPointer import com.intellij.psi.util.parentOfType import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.calls.* import org.jetbrains.kotlin.analysis.api.fir.diagnostics.KtFirDiagnostic import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.api.applicator.HLApplicator import org.jetbrains.kotlin.idea.api.applicator.HLApplicatorInput import org.jetbrains.kotlin.idea.api.applicator.applicator import org.jetbrains.kotlin.idea.core.FirKotlinNameSuggester import org.jetbrains.kotlin.idea.fir.api.fixes.HLQuickFix import org.jetbrains.kotlin.idea.fir.api.fixes.diagnosticFixFactory import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.types.expressions.OperatorConventions object WrapWithSafeLetCallFixFactories { class Input( val nullableExpressionPointer: SmartPsiElementPointer<KtExpression>, val suggestedVariableName: String, val isImplicitInvokeCallToMemberProperty: Boolean, ) : HLApplicatorInput private val LOG = Logger.getInstance(this::class.java) /** * Applicator that wraps a given target expression inside a `let` call on the input `nullableExpression`. * * Consider the following code snippet: * * ``` * fun test(s: String?) { * println(s.length) * } * ``` * * In this case, one use the applicator with the following arguments * - target expression: `s.length` * - nullable expression: `s` * - suggestedVariableName: `myName` * - isImplicitInvokeCallToMemberProperty: false * * Then the applicator changes the code to * * ``` * fun test(s: String?) { * println(s?.let { myName -> myName.length }) * } * ``` * `isImplicitInvokeCallToMemberProperty` controls the behavior when hoisting up the nullable expression. It should be set to true * if the call is to a invocable member property. */ val applicator: HLApplicator<KtExpression, Input> = applicator { familyAndActionName(KotlinBundle.lazyMessage("wrap.with.let.call")) applyTo { targetExpression, input -> val nullableExpression = input.nullableExpressionPointer.element ?: return@applyTo if (!nullableExpression.parents.contains(targetExpression)) { LOG.warn( "Unexpected input for WrapWithSafeLetCall. Nullable expression '${nullableExpression.text}' should be a descendant" + " of '${targetExpression.text}'." ) return@applyTo } val suggestedVariableName = input.suggestedVariableName val factory = KtPsiFactory(targetExpression) fun getNewExpression(nullableExpressionText: String, expressionUnderLetText: String): KtExpression { return when (suggestedVariableName) { "it" -> factory.createExpressionByPattern("$0?.let { $1 }", nullableExpressionText, expressionUnderLetText) else -> factory.createExpressionByPattern( "$0?.let { $1 -> $2 }", nullableExpressionText, suggestedVariableName, expressionUnderLetText ) } } val callExpression = nullableExpression.parentOfType<KtCallExpression>(withSelf = true) val qualifiedExpression = callExpression?.getQualifiedExpressionForSelector() val receiverExpression = qualifiedExpression?.receiverExpression if (receiverExpression != null && input.isImplicitInvokeCallToMemberProperty) { // In this case, the nullable expression is an invocable member. For example consider the following // // interface Foo { // val bar: (() -> Unit)? // } // fun test(foo: Foo) { // foo.bar() // } // // In this case, `foo.bar` is nullable and this fix should change the code to `foo.bar?.let { it() }`. But note that // the PSI structure of the above code is // // - qualifiedExpression: foo.bar() // - receiver: foo // - operationTokenNode: . // - selectorExpression: bar() // - calleeExpression: bar // - valueArgumentList: () // // So we need to explicitly construct the nullable expression text `foo.bar`. val nullableExpressionText = "${receiverExpression.text}${qualifiedExpression.operationSign.value}${nullableExpression.text}" val newInvokeCallText = "${suggestedVariableName}${callExpression.valueArgumentList?.text ?: ""}${ callExpression.lambdaArguments.joinToString( " ", prefix = " " ) { it.text } }" if (qualifiedExpression == targetExpression) { targetExpression.replace(getNewExpression(nullableExpressionText, newInvokeCallText)) } else { qualifiedExpression.replace(factory.createExpression(newInvokeCallText)) targetExpression.replace(getNewExpression(nullableExpressionText, targetExpression.text)) } } else { val nullableExpressionText = when (nullableExpression) { is KtBinaryExpression, is KtBinaryExpressionWithTypeRHS -> "(${nullableExpression.text})" else -> nullableExpression.text } nullableExpression.replace(factory.createExpression(suggestedVariableName)) targetExpression.replace(getNewExpression(nullableExpressionText, targetExpression.text)) } } } val forUnsafeCall = diagnosticFixFactory(KtFirDiagnostic.UnsafeCall::class) { diagnostic -> val nullableExpression = diagnostic.receiverExpression createWrapWithSafeLetCallInputForNullableExpressionIfMoreThanImmediateParentIsWrapped(nullableExpression) } val forUnsafeImplicitInvokeCall = diagnosticFixFactory(KtFirDiagnostic.UnsafeImplicitInvokeCall::class) { diagnostic -> val callExpression = diagnostic.psi.parentOfType<KtCallExpression>(withSelf = true) ?: return@diagnosticFixFactory emptyList() val callingFunctionalVariableInLocalScope = isCallingFunctionalTypeVariableInLocalScope(callExpression) ?: return@diagnosticFixFactory emptyList() createWrapWithSafeLetCallInputForNullableExpression( callExpression.calleeExpression, isImplicitInvokeCallToMemberProperty = !callingFunctionalVariableInLocalScope ) } private fun KtAnalysisSession.isCallingFunctionalTypeVariableInLocalScope(callExpression: KtCallExpression): Boolean? { val calleeExpression = callExpression.calleeExpression val calleeName = calleeExpression?.text ?: return null val callSite = callExpression.parent as? KtQualifiedExpression ?: callExpression val functionalVariableSymbol = (calleeExpression.resolveCall()?.singleCallOrNull<KtSimpleVariableAccessCall>())?.symbol ?: return false val localScope = callExpression.containingKtFile.getScopeContextForPosition(callSite) // If no symbol in the local scope contains the called symbol, then the symbol must be a member symbol. return localScope.scopes.getCallableSymbols { it.identifierOrNullIfSpecial == calleeName }.any { it == functionalVariableSymbol } } val forUnsafeInfixCall = diagnosticFixFactory(KtFirDiagnostic.UnsafeInfixCall::class) { diagnostic -> createWrapWithSafeLetCallInputForNullableExpressionIfMoreThanImmediateParentIsWrapped(diagnostic.receiverExpression) } val forUnsafeOperatorCall = diagnosticFixFactory(KtFirDiagnostic.UnsafeOperatorCall::class) { diagnostic -> createWrapWithSafeLetCallInputForNullableExpressionIfMoreThanImmediateParentIsWrapped(diagnostic.receiverExpression) } val forArgumentTypeMismatch = diagnosticFixFactory(KtFirDiagnostic.ArgumentTypeMismatch::class) { diagnostic -> if (diagnostic.isMismatchDueToNullability) createWrapWithSafeLetCallInputForNullableExpression(diagnostic.psi.wrappingExpressionOrSelf) else emptyList() } private fun KtAnalysisSession.createWrapWithSafeLetCallInputForNullableExpressionIfMoreThanImmediateParentIsWrapped( nullableExpression: KtExpression?, isImplicitInvokeCallToMemberProperty: Boolean = false, ): List<HLQuickFix<KtExpression, Input>> { val surroundingExpression = nullableExpression?.surroundingExpression if ( surroundingExpression == null || // If the surrounding expression is at a place that accepts null value, then we don't provide wrap with let call because the // plain safe call operator (?.) is a better fix. isExpressionAtNullablePosition(surroundingExpression) ) { return emptyList() } // In addition, if there is no parent that is at a nullable position, then we don't offer wrapping with let either because // it still doesn't fix the code. Hence, the plain safe call operator is a better fix. val surroundingNullableExpression = findParentExpressionAtNullablePosition(nullableExpression) ?: return emptyList() return createWrapWithSafeLetCallInputForNullableExpression( nullableExpression, isImplicitInvokeCallToMemberProperty, surroundingNullableExpression ) } private fun KtAnalysisSession.createWrapWithSafeLetCallInputForNullableExpression( nullableExpression: KtExpression?, isImplicitInvokeCallToMemberProperty: Boolean = false, surroundingExpression: KtExpression? = findParentExpressionAtNullablePosition(nullableExpression) ?: nullableExpression?.surroundingExpression ): List<HLQuickFix<KtExpression, Input>> { if (nullableExpression == null || surroundingExpression == null) return emptyList() val existingNames = nullableExpression.containingKtFile.getScopeContextForPosition(nullableExpression).scopes.getPossibleCallableNames() .mapNotNull { it.identifierOrNullIfSpecial } // Note, the order of the candidate matters. We would prefer the default `it` so the generated code won't need to declare the // variable explicitly. val candidateNames = listOfNotNull("it", getDeclaredParameterNameForArgument(nullableExpression)) val suggestedName = FirKotlinNameSuggester.suggestNameByMultipleNames(candidateNames) { it !in existingNames } return listOf( HLQuickFix( surroundingExpression, Input(nullableExpression.createSmartPointer(), suggestedName, isImplicitInvokeCallToMemberProperty), applicator ) ) } private fun KtAnalysisSession.getDeclaredParameterNameForArgument(argumentExpression: KtExpression): String? { val valueArgument = argumentExpression.parent as? KtValueArgument ?: return null val callExpression = argumentExpression.parentOfType<KtCallExpression>() val successCallTarget = callExpression?.resolveCall()?.singleFunctionCallOrNull()?.symbol ?: return null return successCallTarget.valueParameters.getOrNull(valueArgument.argumentIndex)?.name?.identifierOrNullIfSpecial } private fun KtAnalysisSession.findParentExpressionAtNullablePosition(expression: KtExpression?): KtExpression? { if (expression == null) return null var current = expression.surroundingExpression while (current != null && !isExpressionAtNullablePosition(current)) { current = current.surroundingExpression } return current } private fun KtAnalysisSession.isExpressionAtNullablePosition(expression: KtExpression): Boolean { val parent = expression.parent return when { parent is KtProperty && expression == parent.initializer -> { if (parent.typeReference == null) return true val symbol = parent.getSymbol() (symbol as? KtCallableSymbol)?.returnType?.isMarkedNullable ?: true } parent is KtValueArgument && expression == parent.getArgumentExpression() -> { // In the following logic, if call is missing, unresolved, or contains error, we just stop here so the wrapped call would be // inserted here. val functionCall = parent.getParentOfType<KtCallExpression>(strict = true) ?: return true val resolvedCall = functionCall.resolveCall().singleFunctionCallOrNull() ?: return true return doesFunctionAcceptNull(resolvedCall, parent.argumentIndex) ?: true } parent is KtBinaryExpression -> { if (parent.operationToken in KtTokens.ALL_ASSIGNMENTS && parent.left == expression) { // If current expression is an l-value in an assignment, just keep going up because one cannot assign to a let call. return false } val resolvedCall = parent.resolveCall()?.singleFunctionCallOrNull() when { resolvedCall != null -> { // The binary expression is a call to some function val isInExpression = parent.operationToken in OperatorConventions.IN_OPERATIONS val expressionIsArg = when { parent.left == expression -> isInExpression parent.right == expression -> !isInExpression else -> return true } doesFunctionAcceptNull(resolvedCall, if (expressionIsArg) 0 else -1) ?: true } parent.operationToken == KtTokens.EQ -> { // The binary expression is a variable assignment parent.left?.getKtType()?.isMarkedNullable ?: true } // The binary expression is some unrecognized constructs so we stop here. else -> true } } // Qualified expression can always just be updated with a safe call operator to to make it accept nullable receiver. Hence we // don't want to offer the wrap with let call quickfix. parent is KtQualifiedExpression && parent.receiverExpression == expression -> true // Ideally we should do more analysis on the control structure to determine if the type can actually allow null here. But that // may be too fancy and can be counter-intuitive to user. parent is KtContainerNodeForControlStructureBody -> true // Again, for simplicity's sake, we treat block as a place that can accept expression of any type. This is not strictly true // for lambda expressions, but it results in a more deterministic behavior. parent is KtBlockExpression -> true else -> false } } /** * Checks if the called function can accept null for the argument at the given index. If the index is -1, then we check the receiver * type. The function returns null if any necessary assumptions are not met. For example, if the call is not resolved to a unique * function or the function doesn't have a parameter at the given index. Then caller can do whatever needed to cover such cases. */ private fun KtAnalysisSession.doesFunctionAcceptNull(call: KtCall, index: Int): Boolean? { val symbol = (call as? KtFunctionCall<*>)?.symbol ?: return null if (index == -1) { // Null extension receiver means the function does not accept extension receiver and hence cannot be invoked on a nullable // value. return (symbol as? KtCallableSymbol)?.receiverType?.isMarkedNullable == true } return symbol.valueParameters.getOrNull(index)?.returnType?.isMarkedNullable } private val KtExpression.surroundingExpression: KtExpression? get() { var current: PsiElement? = parent while (true) { // Never go above declarations or control structure so that the wrap-with-let quickfix only applies to a "small" scope // around the nullable expression. if (current == null || current is KtContainerNodeForControlStructureBody || current is KtWhenEntry || current is KtParameter || current is KtProperty || current is KtReturnExpression || current is KtDeclaration || current is KtBlockExpression ) { return null } val parent = current.parent if (current is KtExpression && // We skip parenthesized expression and labeled expressions. current !is KtParenthesizedExpression && current !is KtLabeledExpression && // We skip KtCallExpression if it's the `selectorExpression` of a qualified expression because the selector expression is // not an actual expression that can be swapped for any arbitrary expressions. (parent !is KtQualifiedExpression || parent.selectorExpression != current) ) { return current } current = parent } } private val PsiElement.wrappingExpressionOrSelf: KtExpression? get() = parentOfType(withSelf = true) }
apache-2.0
4f3ba6dd69fc8156762e4edc7ac9a065
54.026549
158
0.654211
6.164243
false
false
false
false
Thelonedevil/TLDMaths
TLDMaths/src/test/kotlin/uk/tldcode/math/tldmaths/biginteger/OperatorsTest.kt
1
1145
package uk.tldcode.math.tldmaths.biginteger import org.junit.Test import java.math.BigInteger import kotlin.test.assertEquals class OperatorsTest { @Test fun DecrementTest(){ var result = BigInteger.TEN result-- assertEquals(BigInteger.valueOf(9),result) } @Test fun IncrementTest(){ var result = BigInteger.TEN result++ assertEquals(BigInteger.valueOf(11),result) } @Test fun RangeToTest(){ val result = (BigInteger.ONE..BigInteger.TEN) assertEquals("1, 2, 3, 4, 5, 6, 7, 8, 9, 10",result.joinToString(", ")) } @Test fun UntilTest(){ val result = (BigInteger.ONE until BigInteger.TEN) assertEquals("1, 2, 3, 4, 5, 6, 7, 8, 9",result.joinToString(", ")) } @Test fun DownToTest(){ val result = (BigInteger.TEN downTo BigInteger.ONE) assertEquals("10, 9, 8, 7, 6, 5, 4, 3, 2, 1",result.joinToString(", ")) } @Test fun DowntilTest(){ val result = (BigInteger.TEN downtil BigInteger.ONE) assertEquals("10, 9, 8, 7, 6, 5, 4, 3, 2",result.joinToString(", ")) } }
apache-2.0
27d27c430bdc3b80971696fa4485ad4c
26.285714
79
0.596507
3.74183
false
true
false
false
dahlstrom-g/intellij-community
python/python-psi-impl/src/com/jetbrains/python/inspections/PyClassVarInspection.kt
3
5328
package com.jetbrains.python.inspections import com.intellij.codeInspection.LocalInspectionToolSession import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElementVisitor import com.jetbrains.python.PyPsiBundle import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider import com.jetbrains.python.psi.* import com.jetbrains.python.psi.types.PyClassType import com.jetbrains.python.psi.types.TypeEvalContext class PyClassVarInspection : PyInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor = Visitor(holder, PyInspectionVisitor.getContext(session)) private class Visitor(holder: ProblemsHolder, context: TypeEvalContext) : PyInspectionVisitor(holder, context) { override fun visitPyTargetExpression(node: PyTargetExpression) { super.visitPyTargetExpression(node) if (node.hasAssignedValue()) { if (node.isQualified) { checkClassVarReassignment(node) } else { checkClassVarDeclaration(node) } } } override fun visitPyNamedParameter(node: PyNamedParameter) { super.visitPyNamedParameter(node) if (node.isClassVar()) { registerProblem(node.annotation?.value ?: node.typeComment, PyPsiBundle.message("INSP.class.var.can.not.be.used.in.annotations.for.function.parameters")) } } override fun visitPyFunction(node: PyFunction) { super.visitPyFunction(node) PyTypingTypeProvider.getReturnTypeAnnotation(node, myTypeEvalContext)?.let { if (resolvesToClassVar(if (it is PySubscriptionExpression) it.operand else it)) { registerProblem(node.typeComment ?: node.annotation?.value, PyPsiBundle.message("INSP.class.var.can.not.be.used.in.annotation.for.function.return.value")) } } } private fun checkClassVarDeclaration(target: PyTargetExpression) { when (val scopeOwner = ScopeUtil.getScopeOwner(target)) { is PyFile -> { if (PyUtil.isTopLevel(target) && target.isClassVar()) { registerProblem(target.typeComment ?: target.annotation?.value, PyPsiBundle.message("INSP.class.var.can.be.used.only.in.class.body")) } } is PyFunction -> { if (target.isClassVar()) { registerProblem(target.typeComment ?: target.annotation?.value, PyPsiBundle.message("INSP.class.var.can.not.be.used.in.function.body")) } } is PyClass -> { checkInheritedClassClassVarReassignmentOnClassLevel(target, scopeOwner) } } } private fun checkClassVarReassignment(target: PyTargetExpression) { val qualifierType = target.qualifier?.let { myTypeEvalContext.getType(it) } if (qualifierType is PyClassType && !qualifierType.isDefinition) { checkInstanceClassVarReassignment(target, qualifierType.pyClass) } } private fun checkInheritedClassClassVarReassignmentOnClassLevel(target: PyTargetExpression, cls: PyClass) { val name = target.name ?: return for (ancestor in cls.getAncestorClasses(myTypeEvalContext)) { val ancestorClassAttribute = ancestor.findClassAttribute(name, false, myTypeEvalContext) if (ancestorClassAttribute != null && ancestorClassAttribute.hasExplicitType() && target.hasExplicitType()) { if (ancestorClassAttribute.isClassVar() && !target.isClassVar()) { registerProblem(target, PyPsiBundle.message("INSP.class.var.can.not.override.class.variable", name, ancestor.name)) break } if (!ancestorClassAttribute.isClassVar() && target.isClassVar()) { registerProblem(target, PyPsiBundle.message("INSP.class.var.can.not.override.instance.variable", name, ancestor.name)) break } } } } private fun checkInstanceClassVarReassignment(target: PyQualifiedExpression, cls: PyClass) { val name = target.name ?: return for (ancestor in listOf(cls) + cls.getAncestorClasses(myTypeEvalContext)) { val inheritedClassAttribute = ancestor.findClassAttribute(name, false, myTypeEvalContext) if (inheritedClassAttribute != null && inheritedClassAttribute.isClassVar()) { registerProblem(target, PyPsiBundle.message("INSP.class.var.can.not.be.assigned.to.instance", name)) return } } } private fun PyTargetExpression.hasExplicitType(): Boolean = annotationValue != null || typeCommentAnnotation != null private fun <T> T.isClassVar(): Boolean where T : PyAnnotationOwner, T : PyTypeCommentOwner = PyTypingTypeProvider.isClassVar(this, myTypeEvalContext) private fun resolvesToClassVar(expression: PyExpression): Boolean { return expression is PyReferenceExpression && PyTypingTypeProvider.resolveToQualifiedNames(expression, myTypeEvalContext) .any { it == PyTypingTypeProvider.CLASS_VAR } } } }
apache-2.0
95c2831f302c0f5a011d9ef76c64b39d
43.408333
134
0.677177
5.167798
false
false
false
false
dahlstrom-g/intellij-community
platform/smRunner/vcs/src/com/intellij/execution/testframework/sm/vcs/RunTestsCheckinHandlerFactory.kt
7
15264
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.testframework.sm.vcs import com.intellij.build.BuildView import com.intellij.execution.* import com.intellij.execution.compound.CompoundRunConfiguration import com.intellij.execution.configurations.RunConfiguration import com.intellij.execution.executors.DefaultRunExecutor import com.intellij.execution.impl.EditConfigurationsDialog import com.intellij.execution.impl.RunDialog import com.intellij.execution.impl.RunManagerImpl import com.intellij.execution.process.ProcessAdapter import com.intellij.execution.process.ProcessEvent import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.runners.ExecutionUtil import com.intellij.execution.testframework.TestRunnerBundle import com.intellij.execution.testframework.TestsUIUtil.TestResultPresentation import com.intellij.execution.testframework.actions.ConsolePropertiesProvider import com.intellij.execution.testframework.sm.ConfigurationBean import com.intellij.execution.testframework.sm.SmRunnerBundle import com.intellij.execution.testframework.sm.runner.SMTestProxy import com.intellij.execution.testframework.sm.runner.history.actions.AbstractImportTestsAction import com.intellij.execution.testframework.sm.runner.ui.SMTestRunnerResultsForm import com.intellij.execution.testframework.sm.runner.ui.TestResultsViewer import com.intellij.execution.ui.ExecutionConsole import com.intellij.execution.ui.RunContentDescriptor import com.intellij.openapi.actionSystem.* import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.components.StoragePathMacros import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.ui.JBPopupMenu import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.vcs.CheckinProjectPanel import com.intellij.openapi.vcs.changes.CommitContext import com.intellij.openapi.vcs.changes.ui.BooleanCommitOption import com.intellij.openapi.vcs.checkin.BaseCommitCheck import com.intellij.openapi.vcs.checkin.CheckinHandler import com.intellij.openapi.vcs.checkin.CheckinHandlerFactory import com.intellij.openapi.vcs.checkin.CommitProblem import com.intellij.openapi.vcs.ui.RefreshableOnComponent import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.components.labels.LinkLabel import com.intellij.ui.components.labels.LinkListener import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.intellij.vcs.commit.NullCommitWorkflowHandler import com.intellij.vcs.commit.isBackgroundCommitChecks import com.intellij.vcs.commit.isNonModalCommit import kotlinx.coroutines.* import javax.swing.JComponent import kotlin.coroutines.resume private val LOG = logger<RunTestsCheckinHandlerFactory>() @State(name = "TestsVcsConfig", storages = [Storage(StoragePathMacros.PRODUCT_WORKSPACE_FILE)]) class TestsVcsConfiguration : PersistentStateComponent<TestsVcsConfiguration.MyState> { class MyState { var enabled = false var configuration : ConfigurationBean? = null } var myState = MyState() override fun getState() = myState override fun loadState(state: MyState) { myState = state } } class RunTestsCheckinHandlerFactory : CheckinHandlerFactory() { override fun createHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler { return if (isBackgroundCommitChecks() && (panel.isNonModalCommit || panel.commitWorkflowHandler is NullCommitWorkflowHandler)) RunTestsBeforeCheckinHandler(panel) else CheckinHandler.DUMMY } } class FailedTestCommitProblem(val problems: List<FailureDescription>) : CommitProblem { override val text: String get() { var str = "" val failed = problems.sumBy { it.failed } if (failed > 0) { str = TestRunnerBundle.message("tests.result.failure.summary", failed) } val ignored = problems.sumBy { it.ignored } if (ignored > 0) { str += (if (failed > 0) ", " else "") str += TestRunnerBundle.message("tests.result.ignore.summary", ignored) } val failedToStartMessages = problems .filter { it.failed == 0 && it.ignored == 0 } .mapNotNull { it.configName } .joinToString { TestRunnerBundle.message("failed.to.start.message", it) } if (failedToStartMessages.isNotEmpty()) { str += (if (ignored + failed > 0) ", " else "") str += failedToStartMessages } return str } } data class FailureDescription(val historyFileName: String, val failed: Int, val ignored: Int, val configuration: RunnerAndConfigurationSettings?, val configName: String?) private fun createCommitProblem(descriptions: List<FailureDescription>): FailedTestCommitProblem? = if (descriptions.isNotEmpty()) FailedTestCommitProblem(descriptions) else null class RunTestsBeforeCheckinHandler(private val commitPanel: CheckinProjectPanel) : BaseCommitCheck<FailedTestCommitProblem>() { private val project: Project get() = commitPanel.project private val settings: TestsVcsConfiguration get() = project.getService(TestsVcsConfiguration::class.java) override fun isEnabled(): Boolean = settings.myState.enabled override suspend fun doRunCheck(): FailedTestCommitProblem? { val configurationBean = settings.myState.configuration ?: return null val configurationSettings = RunManager.getInstance(project).findConfigurationByTypeAndName(configurationBean.configurationId, configurationBean.name) if (configurationSettings == null) { return createCommitProblem(listOf(FailureDescription("", 0, 0, configurationSettings, configurationBean.name))) } progress(name = SmRunnerBundle.message("progress.text.running.tests", configurationSettings.name)) return withContext(Dispatchers.IO) { val problems = ArrayList<FailureDescription>() val executor = DefaultRunExecutor.getRunExecutorInstance() val configuration = configurationSettings.configuration if (configuration is CompoundRunConfiguration) { val runManager = RunManagerImpl.getInstanceImpl(project) configuration.getConfigurationsWithTargets(runManager) .map { runManager.findSettings(it.key) } .filterNotNull() .forEach { startConfiguration(executor, it, problems) } } else { startConfiguration(executor, configurationSettings, problems) } return@withContext createCommitProblem(problems) } } private data class TestResultsFormDescriptor(val executionConsole: ExecutionConsole, val rootNode : SMTestProxy.SMRootTestProxy, val historyFileName: String) private suspend fun startConfiguration(executor: Executor, configurationSettings: RunnerAndConfigurationSettings, problems: ArrayList<FailureDescription>) { val environmentBuilder = ExecutionUtil.createEnvironment(executor, configurationSettings) ?: return val executionTarget = ExecutionTargetManager.getInstance(project).findTarget(configurationSettings.configuration) val environment = environmentBuilder.target(executionTarget).build() environment.setHeadless() val formDescriptor = suspendCancellableCoroutine<TestResultsFormDescriptor?> { continuation -> val messageBus = project.messageBus messageBus.connect(environment).subscribe(ExecutionManager.EXECUTION_TOPIC, object : ExecutionListener { override fun processNotStarted(executorId: String, env: ExecutionEnvironment) { if (environment.executionId == env.executionId) { Disposer.dispose(environment) problems.add(FailureDescription("", 0, 0, configurationSettings, configurationSettings.name)) continuation.resume(null) } } }) ProgramRunnerUtil.executeConfigurationAsync(environment, false, true) { if (it != null) { onProcessStarted(it, continuation) } } } ?: return val rootNode = formDescriptor.rootNode if (rootNode.isDefect || rootNode.children.isEmpty()) { val fileName = formDescriptor.historyFileName val presentation = TestResultPresentation(rootNode).presentation problems.add(FailureDescription(fileName, presentation.failedCount, presentation.ignoredCount, configurationSettings, configurationSettings.name)) awaitSavingHistory(fileName) } disposeConsole(formDescriptor.executionConsole) } private fun onProcessStarted(descriptor: RunContentDescriptor, continuation: CancellableContinuation<TestResultsFormDescriptor?>) { val handler = descriptor.processHandler if (handler != null) { val executionConsole = descriptor.console val resultsForm = executionConsole?.resultsForm val formDescriptor = if (resultsForm != null) TestResultsFormDescriptor(executionConsole, resultsForm.testsRootNode, resultsForm.historyFileName) else null val processListener = object : ProcessAdapter() { override fun processTerminated(event: ProcessEvent) = continuation.resume(formDescriptor) } handler.addProcessListener(processListener) resultsForm?.addEventsListener(object : TestResultsViewer.EventsListener { override fun onTestNodeAdded(sender: TestResultsViewer, test: SMTestProxy) = progress(details = test.getFullName()) }) continuation.invokeOnCancellation { handler.removeProcessListener(processListener) handler.destroyProcess() executionConsole?.let { disposeConsole(it) } } } else { continuation.resume(null) } } private val ExecutionConsole.resultsForm: SMTestRunnerResultsForm? get() = component as? SMTestRunnerResultsForm private val RunContentDescriptor.console: ExecutionConsole? get() = executionConsole?.let { if (it is BuildView) it.consoleView else it } private fun SMTestProxy.getFullName(): @NlsSafe String = if (parent == null || parent is SMTestProxy.SMRootTestProxy) presentableName else parent.getFullName() + "." + presentableName private suspend fun awaitSavingHistory(historyFileName: String) { withTimeout(timeMillis = 600000) { while (getHistoryFile(historyFileName).second == null) { delay(timeMillis = 500) } DumbService.getInstance(project).waitForSmartMode() } } override fun showDetails(problem: FailedTestCommitProblem) { val groupId = ExecutionEnvironment.getNextUnusedExecutionId() for (p in problem.problems) { if (p.historyFileName.isEmpty() && p.failed == 0 && p.ignored == 0) { if (p.configuration != null) { RunDialog.editConfiguration(project, p.configuration, ExecutionBundle.message("edit.run.configuration.for.item.dialog.title", p.configuration.name)) continue } if (p.configName != null) { EditConfigurationsDialog(project).show() continue } } val (path, virtualFile) = getHistoryFile(p.historyFileName) if (virtualFile != null) { AbstractImportTestsAction.doImport(project, virtualFile, groupId) } else { LOG.error("File not found: $path") } } } private fun getHistoryFile(fileName: String): Pair<String, VirtualFile?> { val path = "${TestStateStorage.getTestHistoryRoot(project).path}/$fileName.xml" val virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(path) return Pair(path, virtualFile) } @NlsContexts.DialogTitle private fun getInitialText(): String { val configurationBean = settings.myState.configuration return if (configurationBean != null) getOptionTitle(configurationBean.name) else SmRunnerBundle.message("checkbox.run.tests.before.commit.no.configuration") } override fun getBeforeCheckinConfigurationPanel(): RefreshableOnComponent { return object : BooleanCommitOption(commitPanel, getInitialText(), true, settings.myState::enabled) { override fun getComponent(): JComponent { val showFiltersPopup = LinkListener<Any> { sourceLink, _ -> JBPopupMenu.showBelow(sourceLink, ActionPlaces.UNKNOWN, createConfigurationChooser()) } val configureFilterLink = LinkLabel(SmRunnerBundle.message("link.label.choose.configuration.before.commit"), null, showFiltersPopup) checkBox.text = getInitialText() return JBUI.Panels.simplePanel(4, 0).addToLeft(checkBox).addToCenter(configureFilterLink) } private fun createConfigurationChooser(): ActionGroup { fun testConfiguration(it: RunConfiguration) = it is ConsolePropertiesProvider && it.createTestConsoleProperties(DefaultRunExecutor.getRunExecutorInstance()) != null val result = DefaultActionGroup() val runManager = RunManagerImpl.getInstanceImpl(project) for ((type, folderMap) in runManager.getConfigurationsGroupedByTypeAndFolder(false)) { var addedSeparator = false for ((folder, list) in folderMap.entries) { val localConfigurations: List<RunConfiguration> = list.map { it.configuration } .filter { testConfiguration(it) || it is CompoundRunConfiguration && it.getConfigurationsWithTargets(runManager).keys.all { one -> testConfiguration(one) } } if (localConfigurations.isEmpty()) continue if (!addedSeparator && result.childrenCount > 0) { result.addSeparator() addedSeparator = true } var target = result if (folder != null) { target = DefaultActionGroup(folder, true) result.add(target) } localConfigurations .forEach { configuration: RunConfiguration -> target.add(object : AnAction(configuration.icon) { init { templatePresentation.setText(configuration.name, false) } override fun actionPerformed(e: AnActionEvent) { val bean = ConfigurationBean() bean.configurationId = type.id bean.name = configuration.name settings.myState.configuration = bean checkBox.text = getOptionTitle(configuration.name) } }) } } } return result } } } @NlsContexts.DialogTitle private fun getOptionTitle(name: String): String { return SmRunnerBundle.message("checkbox.run.tests.before.commit", name) } private fun disposeConsole(executionConsole: ExecutionConsole) { UIUtil.invokeLaterIfNeeded { Disposer.dispose(executionConsole) } } }
apache-2.0
e79cd61a631810dbf10e0032deb5a95f
43.246377
192
0.729822
5.181263
false
true
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/streaming/StreamRelation.kt
1
946
package jp.juggler.subwaytooter.streaming import jp.juggler.subwaytooter.column.Column import jp.juggler.subwaytooter.column.canStreamingState import jp.juggler.util.LogCategory import java.lang.ref.WeakReference class StreamRelation( column: Column, val spec: StreamSpec ) { companion object { private val log = LogCategory("StreamDestination") } val columnInternalId = column.internalId val refColumn = WeakReference(column) val refCallback = WeakReference(column.streamCallback) fun canStartStreaming(): Boolean { return when (val column = refColumn.get()) { null -> { log.w("${spec.name} canStartStreaming: missing column.") false } else -> column.canStreamingState() } } } fun Column.getStreamDestination() = streamSpec?.let { StreamRelation(spec = it, column = this) }
apache-2.0
bb76ab48c7d152bca63fe6a2667f335d
26.666667
72
0.645877
4.592233
false
false
false
false
DreierF/MyTargets
app/src/main/java/de/dreier/mytargets/features/arrows/EditArrowViewModel.kt
1
5185
/* * 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.features.arrows import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import androidx.databinding.ObservableBoolean import androidx.databinding.ObservableField import androidx.databinding.ObservableFloat import androidx.databinding.ObservableInt import android.text.TextUtils import de.dreier.mytargets.R import de.dreier.mytargets.app.ApplicationInstance import de.dreier.mytargets.shared.models.Dimension import de.dreier.mytargets.shared.models.Dimension.Unit.MILLIMETER import de.dreier.mytargets.shared.models.Thumbnail import de.dreier.mytargets.shared.models.db.Arrow import de.dreier.mytargets.shared.models.db.ArrowImage class EditArrowViewModel(app: Application) : AndroidViewModel(app) { val arrowId = MutableLiveData<Long?>() val arrow: LiveData<Arrow?> var images: LiveData<List<ArrowImage>> var name = ObservableField<String>(getApplication<ApplicationInstance>().getString(R.string.my_arrow)) var maxArrowNumber = ObservableInt(12) var length = ObservableField<String>("") var material = ObservableField<String>("") var spine = ObservableField<String>("") var weight = ObservableField<String>("") var tipWeight = ObservableField<String>("") var vanes = ObservableField<String>("") var nock = ObservableField<String>("") var comment = ObservableField<String>("") var diameterValue = ObservableFloat(5f) var diameterUnit = ObservableField<Dimension.Unit>(MILLIMETER) var showAll = ObservableBoolean(false) var diameterErrorText = ObservableField<String>("") private val arrowDAO = ApplicationInstance.db.arrowDAO() init { arrow = Transformations.map(arrowId) { id -> if (id == null) { null } else { val arrow = arrowDAO.loadArrow(id) setFromArrow(arrow) arrow } } images = Transformations.map(arrowId) { id -> if (id == null) mutableListOf() else arrowDAO.loadArrowImages(id) } } private fun setFromArrow(arrow: Arrow) { name.set(arrow.name) maxArrowNumber.set(arrow.maxArrowNumber) length.set(arrow.length) material.set(arrow.material) spine.set(arrow.spine) weight.set(arrow.weight) tipWeight.set(arrow.tipWeight) vanes.set(arrow.vanes) nock.set(arrow.nock) comment.set(arrow.comment) diameterValue.set(arrow.diameter.value) diameterUnit.set(arrow.diameter.unit) } fun save(thumb: Thumbnail, imageFiles: List<ArrowImage>): Boolean { if (!validateInput()) { return false } val arrow = Arrow() arrow.id = arrowId.value ?: 0 arrow.name = name.get() ?: "" arrow.maxArrowNumber = maxArrowNumber.get() arrow.length = length.get() arrow.material = material.get() arrow.spine = spine.get() arrow.weight = weight.get() arrow.tipWeight = tipWeight.get() arrow.vanes = vanes.get() arrow.nock = nock.get() arrow.comment = comment.get() arrow.thumbnail = thumb arrow.diameter = Dimension(diameterValue.get(), diameterUnit.get()) arrowDAO.saveArrow(arrow, imageFiles) return true } private fun validateInput(): Boolean { if (diameterUnit.get() == MILLIMETER) { if (diameterValue.get() !in 1f..20f) { diameterErrorText.set(getApplication<ApplicationInstance>().getString(R.string.not_within_expected_range_mm)) return false } } else { if (diameterValue.get() !in 0f..1f) { diameterErrorText.set(getApplication<ApplicationInstance>().getString(R.string.not_within_expected_range_inch)) return false } } diameterErrorText.set("") return true } fun setArrowId(arrowId: Long?) { this.arrowId.value = arrowId } fun areAllPropertiesSet(): Boolean { return !TextUtils.isEmpty(length.get()) && !TextUtils.isEmpty(material.get()) && !TextUtils.isEmpty(spine.get()) && !TextUtils.isEmpty(weight.get()) && !TextUtils.isEmpty(tipWeight.get()) && !TextUtils.isEmpty(vanes.get()) && !TextUtils.isEmpty(nock.get()) && !TextUtils.isEmpty(comment.get()) } }
gpl-2.0
baea92cacdd7f72feaf97480156854d5
34.272109
127
0.64783
4.439212
false
false
false
false
MGaetan89/ShowsRage
app/src/main/kotlin/com/mgaetan89/showsrage/widget/ScheduleWidgetProvider.kt
1
1309
package com.mgaetan89.showsrage.widget import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.content.Context import android.content.Intent import android.net.Uri import com.mgaetan89.showsrage.Constants import com.mgaetan89.showsrage.R import com.mgaetan89.showsrage.activity.MainActivity class ScheduleWidgetProvider : ListWidgetProvider() { override fun getListAdapterIntent(context: Context?, widgetId: Int): Intent { if (context == null) { return Intent() } val intent = Intent(context, ScheduleWidgetService::class.java) intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId) intent.data = Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)) return intent } override fun getTitlePendingIntent(context: Context?, widgetId: Int): PendingIntent { val intent = Intent(context, MainActivity::class.java) intent.action = Constants.Intents.ACTION_DISPLAY_SCHEDULE intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK) return PendingIntent.getActivity(context, widgetId, intent, PendingIntent.FLAG_CANCEL_CURRENT) } override fun getWidgetEmptyText(context: Context?) = context?.getString(R.string.no_coming_episodes) override fun getWidgetTitle(context: Context?) = context?.getString(R.string.schedule) }
apache-2.0
0dbdc37f47fab78507f80995abb3c3f5
35.361111
101
0.799083
3.978723
false
false
false
false
google/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ChildSingleFirstEntityImpl.kt
1
10214
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.extractOneToAbstractOneParent import com.intellij.workspaceModel.storage.impl.updateOneToAbstractOneParentOfChild import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Abstract import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class ChildSingleFirstEntityImpl(val dataSource: ChildSingleFirstEntityData) : ChildSingleFirstEntity, WorkspaceEntityBase() { companion object { internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentSingleAbEntity::class.java, ChildSingleAbstractBaseEntity::class.java, ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE, false) val connections = listOf<ConnectionId>( PARENTENTITY_CONNECTION_ID, ) } override val commonData: String get() = dataSource.commonData override val parentEntity: ParentSingleAbEntity get() = snapshot.extractOneToAbstractOneParent(PARENTENTITY_CONNECTION_ID, this)!! override val firstData: String get() = dataSource.firstData override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: ChildSingleFirstEntityData?) : ModifiableWorkspaceEntityBase<ChildSingleFirstEntity>(), ChildSingleFirstEntity.Builder { constructor() : this(ChildSingleFirstEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity ChildSingleFirstEntity 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().isCommonDataInitialized()) { error("Field ChildSingleAbstractBaseEntity#commonData should be initialized") } if (_diff != null) { if (_diff.extractOneToAbstractOneParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) { error("Field ChildSingleAbstractBaseEntity#parentEntity should be initialized") } } else { if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) { error("Field ChildSingleAbstractBaseEntity#parentEntity should be initialized") } } if (!getEntityData().isFirstDataInitialized()) { error("Field ChildSingleFirstEntity#firstData 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 ChildSingleFirstEntity this.entitySource = dataSource.entitySource this.commonData = dataSource.commonData this.firstData = dataSource.firstData if (parents != null) { this.parentEntity = parents.filterIsInstance<ParentSingleAbEntity>().single() } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var commonData: String get() = getEntityData().commonData set(value) { checkModificationAllowed() getEntityData().commonData = value changedProperty.add("commonData") } override var parentEntity: ParentSingleAbEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToAbstractOneParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as ParentSingleAbEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as ParentSingleAbEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(true, PARENTENTITY_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.updateOneToAbstractOneParentOfChild(PARENTENTITY_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this } // 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 var firstData: String get() = getEntityData().firstData set(value) { checkModificationAllowed() getEntityData().firstData = value changedProperty.add("firstData") } override fun getEntityData(): ChildSingleFirstEntityData = result ?: super.getEntityData() as ChildSingleFirstEntityData override fun getEntityClass(): Class<ChildSingleFirstEntity> = ChildSingleFirstEntity::class.java } } class ChildSingleFirstEntityData : WorkspaceEntityData<ChildSingleFirstEntity>() { lateinit var commonData: String lateinit var firstData: String fun isCommonDataInitialized(): Boolean = ::commonData.isInitialized fun isFirstDataInitialized(): Boolean = ::firstData.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ChildSingleFirstEntity> { val modifiable = ChildSingleFirstEntityImpl.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): ChildSingleFirstEntity { return getCached(snapshot) { val entity = ChildSingleFirstEntityImpl(this) entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return ChildSingleFirstEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return ChildSingleFirstEntity(commonData, firstData, entitySource) { this.parentEntity = parents.filterIsInstance<ParentSingleAbEntity>().single() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() res.add(ParentSingleAbEntity::class.java) return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ChildSingleFirstEntityData if (this.entitySource != other.entitySource) return false if (this.commonData != other.commonData) return false if (this.firstData != other.firstData) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ChildSingleFirstEntityData if (this.commonData != other.commonData) return false if (this.firstData != other.firstData) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + commonData.hashCode() result = 31 * result + firstData.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + commonData.hashCode() result = 31 * result + firstData.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
4cc2b7a281dcc08e4e1366b047e26fed
36.551471
165
0.703936
5.706145
false
false
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/MusicPatch.kt
1
1330
package org.runestar.client.updater.mapper.std.classes import org.objectweb.asm.Type import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.DependsOn import org.runestar.client.updater.mapper.MethodParameters import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.withDimensions import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Field2 import org.runestar.client.updater.mapper.Method2 @DependsOn(Node::class) class MusicPatch : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.superType == type<Node>() } .and { it.instanceFields.count { it.type == ByteArray::class.type } == 3 } .and { it.instanceFields.count { it.type == ShortArray::class.type } == 1 } @MethodParameters() class clear : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.arguments.isEmpty() && it.returnType == Type.VOID_TYPE } } @DependsOn(RawSound::class) class rawSounds : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == type<RawSound>().withDimensions(1) } } }
mit
be5ab67a9ef7ee6da4ea7a59f3f2ac1e
41.935484
115
0.748872
3.993994
false
false
false
false
JetBrains/intellij-community
platform/build-scripts/src/org/jetbrains/intellij/build/impl/CompilationContextImpl.kt
1
20489
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceGetOrSet", "ReplaceNegatedIsEmptyWithIsNotEmpty") package org.jetbrains.intellij.build.impl import com.intellij.diagnostic.telemetry.use import com.intellij.diagnostic.telemetry.useWithScope2 import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.io.NioFiles import com.intellij.util.PathUtilRt import com.intellij.util.SystemProperties import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.common.Attributes import io.opentelemetry.api.trace.Span import kotlinx.coroutines.* import org.jetbrains.annotations.ApiStatus.Internal import org.jetbrains.intellij.build.* import org.jetbrains.intellij.build.TraceManager.spanBuilder import org.jetbrains.intellij.build.dependencies.BuildDependenciesCommunityRoot import org.jetbrains.intellij.build.dependencies.BuildDependenciesDownloader import org.jetbrains.intellij.build.dependencies.DependenciesProperties import org.jetbrains.intellij.build.dependencies.JdkDownloader import org.jetbrains.intellij.build.impl.JdkUtils.defineJdk import org.jetbrains.intellij.build.impl.JdkUtils.readModulesFromReleaseFile import org.jetbrains.intellij.build.impl.compilation.CompiledClasses import org.jetbrains.intellij.build.impl.logging.BuildMessagesHandler import org.jetbrains.intellij.build.impl.logging.BuildMessagesImpl import org.jetbrains.intellij.build.kotlin.KotlinBinaries import org.jetbrains.jps.model.* import org.jetbrains.jps.model.artifact.JpsArtifactService import org.jetbrains.jps.model.java.JpsJavaClasspathKind import org.jetbrains.jps.model.java.JpsJavaExtensionService import org.jetbrains.jps.model.java.JpsJavaSdkType import org.jetbrains.jps.model.library.JpsOrderRootType import org.jetbrains.jps.model.library.sdk.JpsSdkReference import org.jetbrains.jps.model.module.JpsModule import org.jetbrains.jps.model.serialization.JpsModelSerializationDataService import org.jetbrains.jps.model.serialization.JpsPathMapper import org.jetbrains.jps.model.serialization.JpsProjectLoader.loadProject import org.jetbrains.jps.util.JpsPathUtil import java.nio.file.Files import java.nio.file.Path import kotlin.io.path.name @JvmOverloads fun createCompilationContextBlocking(communityHome: BuildDependenciesCommunityRoot, projectHome: Path, defaultOutputRoot: Path, options: BuildOptions = BuildOptions()): CompilationContextImpl { return runBlocking(Dispatchers.Default) { createCompilationContext(communityHome = communityHome, projectHome = projectHome, defaultOutputRoot = defaultOutputRoot, options = options) } } suspend fun createCompilationContext(communityHome: BuildDependenciesCommunityRoot, projectHome: Path, defaultOutputRoot: Path, options: BuildOptions = BuildOptions()): CompilationContextImpl { val logDir = options.logPath?.let { Path.of(it).toAbsolutePath().normalize() } ?: (options.outputRootPath ?: defaultOutputRoot).resolve("log") TracerProviderManager.setOutput(logDir.resolve("trace.json")) return CompilationContextImpl.createCompilationContext(communityHome = communityHome, projectHome = projectHome, setupTracer = false, buildOutputRootEvaluator = { defaultOutputRoot }, options = options) } private fun computeBuildPaths(options: BuildOptions, project: JpsProject, communityHome: BuildDependenciesCommunityRoot, buildOutputRootEvaluator: (JpsProject) -> Path, projectHome: Path): BuildPaths { val buildOut = options.outputRootPath ?: buildOutputRootEvaluator(project) val logDir = options.logPath?.let { Path.of(it).toAbsolutePath().normalize() } ?: buildOut.resolve("log") return BuildPathsImpl(communityHome = communityHome, projectHome = projectHome, buildOut = buildOut, logDir = logDir) } @Internal class CompilationContextImpl private constructor( model: JpsModel, private val communityHome: BuildDependenciesCommunityRoot, override val messages: BuildMessages, override val paths: BuildPaths, override val options: BuildOptions, ) : CompilationContext { val global: JpsGlobal private val nameToModule: Map<String?, JpsModule> override var classesOutputDirectory: Path get() { val url = JpsJavaExtensionService.getInstance().getOrCreateProjectExtension(project).outputUrl return Path.of(JpsPathUtil.urlToOsPath(url)) } set(outputDirectory) { val url = "file://" + FileUtilRt.toSystemIndependentName(outputDirectory.toString()) JpsJavaExtensionService.getInstance().getOrCreateProjectExtension(project).outputUrl = url } override val project: JpsProject override val projectModel: JpsModel = model override val dependenciesProperties: DependenciesProperties override val bundledRuntime: BundledRuntime override lateinit var compilationData: JpsCompilationData override val stableJdkHome: Path by lazy { JdkDownloader.getJdkHome(communityHome, Span.current()::addEvent) } override val stableJavaExecutable: Path by lazy { JdkDownloader.getJavaExecutable(stableJdkHome) } init { project = model.project global = model.global val modules = project.modules nameToModule = modules.associateByTo(HashMap(modules.size)) { it.name } dependenciesProperties = DependenciesProperties(paths.communityHomeDirRoot) bundledRuntime = BundledRuntimeImpl(options = options, paths = paths, dependenciesProperties = dependenciesProperties, error = messages::error, info = messages::info) } companion object { suspend fun createCompilationContext(communityHome: BuildDependenciesCommunityRoot, projectHome: Path, buildOutputRootEvaluator: (JpsProject) -> Path, options: BuildOptions, setupTracer: Boolean): CompilationContextImpl { check(sequenceOf("platform/build-scripts", "bin/idea.properties", "build.txt").all { Files.exists(communityHome.communityRoot.resolve(it)) }) { "communityHome ($communityHome) doesn\'t point to a directory containing IntelliJ Community sources" } val messages = BuildMessagesImpl.create() if (options.printEnvironmentInfo) { messages.block("Environment info") { messages.info("Community home: ${communityHome.communityRoot}") messages.info("Project home: $projectHome") printEnvironmentDebugInfo() } } if (options.printFreeSpace) { logFreeDiskSpace(dir = projectHome, phase = "before downloading dependencies") } val isCompilationRequired = CompiledClasses.isCompilationRequired(options) // this is not a proper place to initialize tracker for downloader but this is the only place which is called in most build scripts val model = coroutineScope { launch { BuildDependenciesDownloader.TRACER = BuildDependenciesOpenTelemetryTracer.INSTANCE } loadProject(projectHome = projectHome, kotlinBinaries = KotlinBinaries(communityHome, messages), isCompilationRequired) } val buildPaths = computeBuildPaths(project = model.project, communityHome = communityHome, options = options, buildOutputRootEvaluator = buildOutputRootEvaluator, projectHome = projectHome) // not as part of prepareForBuild because prepareForBuild may be called several times per each product or another flavor // (see createCopyForProduct) if (setupTracer) { TracerProviderManager.setOutput(buildPaths.logDir.resolve("trace.json")) } val context = CompilationContextImpl(model = model, communityHome = communityHome, messages = messages, paths = buildPaths, options = options) /** * [defineJavaSdk] may be skipped using [CompiledClasses.isCompilationRequired] * after removing workaround from [JpsCompilationRunner.compileMissingArtifactsModules]. */ spanBuilder("define JDK").useWithScope2 { defineJavaSdk(context) } spanBuilder("prepare for build").useWithScope2 { context.prepareForBuild() } messages.setDebugLogPath(context.paths.logDir.resolve("debug.log")) // this is not a proper place to initialize logging but this is the only place which is called in most build scripts BuildMessagesHandler.initLogging(messages) return context } } fun createCopy(messages: BuildMessages, options: BuildOptions, buildOutputRootEvaluator: (JpsProject) -> Path): CompilationContextImpl { val copy = CompilationContextImpl(model = projectModel, communityHome = paths.communityHomeDirRoot, messages = messages, paths = computeBuildPaths(options = options, project = project, communityHome = communityHome, buildOutputRootEvaluator = buildOutputRootEvaluator, projectHome = paths.projectHome), options = options) copy.compilationData = compilationData return copy } internal fun prepareForBuild() { CompiledClasses.checkOptions(this) val logDir = paths.logDir if (Files.exists(logDir)) { Files.newDirectoryStream(logDir).use { stream -> for (file in stream) { if (!file.endsWith("trace.json")) { NioFiles.deleteRecursively(file) } } } } else { Files.createDirectories(logDir) } if (!this::compilationData.isInitialized) { compilationData = JpsCompilationData( dataStorageRoot = paths.buildOutputDir.resolve(".jps-build-data"), buildLogFile = logDir.resolve("compilation.log"), categoriesWithDebugLevelNullable = System.getProperty("intellij.build.debug.logging.categories", "") ) } overrideClassesOutputDirectory() for (artifact in JpsArtifactService.getInstance().getArtifacts(project)) { artifact.outputPath = "${paths.jpsArtifacts.resolve(PathUtilRt.getFileName(artifact.outputPath))}" } suppressWarnings(project) ConsoleSpanExporter.setPathRoot(paths.buildOutputDir) cleanOutput(keepCompilationState = CompiledClasses.keepCompilationState(options)) } private fun overrideClassesOutputDirectory() { val override = options.classesOutputDirectory when { !override.isNullOrEmpty() -> classesOutputDirectory = Path.of(override) options.useCompiledClassesFromProjectOutput -> require(Files.exists(classesOutputDirectory)) { "${BuildOptions.USE_COMPILED_CLASSES_PROPERTY} is enabled but the classes output directory $classesOutputDirectory doesn't exist" } else -> classesOutputDirectory = paths.buildOutputDir.resolve("classes") } Span.current().addEvent("set class output directory", Attributes.of(AttributeKey.stringKey("classOutputDirectory"), classesOutputDirectory.toString())) } override fun findRequiredModule(name: String): JpsModule { val module = findModule(name) checkNotNull(module) { "Cannot find required module \'$name\' in the project" } return module } override fun findModule(name: String): JpsModule? = nameToModule.get(name) override fun getModuleOutputDir(module: JpsModule): Path { val url = JpsJavaExtensionService.getInstance().getOutputUrl(module, false) check(url != null) { "Output directory for ${module.name} isn\'t set" } return Path.of(JpsPathUtil.urlToPath(url)) } override fun getModuleTestsOutputPath(module: JpsModule): String { val outputDirectory = JpsJavaExtensionService.getInstance().getOutputDirectory(module, true) check(outputDirectory != null) { "Output directory for ${module.name} isn\'t set" } return outputDirectory.absolutePath } override fun getModuleRuntimeClasspath(module: JpsModule, forTests: Boolean): List<String> { val enumerator = JpsJavaExtensionService.dependencies(module).recursively() // if project requires different SDKs they all shouldn't be added to test classpath .also { if (forTests) it.withoutSdk() } .includedIn(JpsJavaClasspathKind.runtime(forTests)) return enumerator.classes().roots.map { it.absolutePath } } override fun notifyArtifactWasBuilt(artifactPath: Path) { if (options.buildStepsToSkip.contains(BuildOptions.TEAMCITY_ARTIFACTS_PUBLICATION_STEP)) { return } val isRegularFile = Files.isRegularFile(artifactPath) var targetDirectoryPath = "" if (artifactPath.parent.startsWith(paths.artifactDir)) { targetDirectoryPath = FileUtilRt.toSystemIndependentName(paths.artifactDir.relativize(artifactPath.parent).toString()) } if (!isRegularFile) { targetDirectoryPath = (if (targetDirectoryPath.isEmpty()) "" else "$targetDirectoryPath/") + artifactPath.fileName } var pathToReport = artifactPath.toString() if (targetDirectoryPath.isNotEmpty()) { pathToReport += "=>$targetDirectoryPath" } messages.artifactBuilt(pathToReport) } } private suspend fun loadProject(projectHome: Path, kotlinBinaries: KotlinBinaries, isCompilationRequired: Boolean): JpsModel { val model = JpsElementFactory.getInstance().createModel() val pathVariablesConfiguration = JpsModelSerializationDataService.getOrCreatePathVariablesConfiguration(model.global) if (isCompilationRequired) { kotlinBinaries.loadKotlinJpsPluginToClassPath() val kotlinCompilerHome = kotlinBinaries.kotlinCompilerHome System.setProperty("jps.kotlin.home", kotlinCompilerHome.toString()) pathVariablesConfiguration.addPathVariable("KOTLIN_BUNDLED", kotlinCompilerHome.toString()) } withContext(Dispatchers.IO) { spanBuilder("load project").useWithScope2 { span -> pathVariablesConfiguration.addPathVariable("MAVEN_REPOSITORY", FileUtilRt.toSystemIndependentName( Path.of(SystemProperties.getUserHome(), ".m2/repository").toString())) val pathVariables = JpsModelSerializationDataService.computeAllPathVariables(model.global) loadProject(model.project, pathVariables, JpsPathMapper.IDENTITY, projectHome, { launch { it.run() } }, false) span.setAllAttributes(Attributes.of( AttributeKey.stringKey("project"), projectHome.toString(), AttributeKey.longKey("moduleCount"), model.project.modules.size.toLong(), AttributeKey.longKey("libraryCount"), model.project.libraryCollection.libraries.size.toLong(), )) } } return model as JpsModel } private fun suppressWarnings(project: JpsProject) { val compilerOptions = JpsJavaExtensionService.getInstance().getCompilerConfiguration(project).currentCompilerOptions compilerOptions.GENERATE_NO_WARNINGS = true compilerOptions.DEPRECATION = false @Suppress("SpellCheckingInspection") compilerOptions.ADDITIONAL_OPTIONS_STRING = compilerOptions.ADDITIONAL_OPTIONS_STRING.replace("-Xlint:unchecked", "") } private class BuildPathsImpl(communityHome: BuildDependenciesCommunityRoot, projectHome: Path, buildOut: Path, logDir: Path) : BuildPaths(communityHomeDirRoot = communityHome, buildOutputDir = buildOut, logDir = logDir, projectHome = projectHome) { init { artifactDir = buildOutputDir.resolve("artifacts") artifacts = FileUtilRt.toSystemIndependentName(artifactDir.toString()) } } private fun defineJavaSdk(context: CompilationContext) { val homePath = context.stableJdkHome val jbrVersionName = "jbr-17" defineJdk(global = context.projectModel.global, jdkName = jbrVersionName, homeDir = homePath) readModulesFromReleaseFile(model = context.projectModel, sdkName = jbrVersionName, sdkHome = homePath) val sdkReferenceToFirstModule = HashMap<JpsSdkReference<JpsDummyElement>, JpsModule>() for (module in context.projectModel.project.modules) { val sdkReference = module.getSdkReference(JpsJavaSdkType.INSTANCE) ?: continue sdkReferenceToFirstModule.putIfAbsent(sdkReference, module) } // validate all modules have proper SDK reference for ((sdkRef, module) in sdkReferenceToFirstModule) { val sdkName = sdkRef.sdkName val vendorPrefixEnd = sdkName.indexOf('-') val sdkNameWithoutVendor = if (vendorPrefixEnd == -1) sdkName else sdkName.substring(vendorPrefixEnd + 1) check(sdkNameWithoutVendor == "17") { "Project model at ${context.paths.projectHome} [module ${module.name}] requested SDK $sdkNameWithoutVendor, " + "but only '17' is supported as SDK in intellij project" } if (context.projectModel.global.libraryCollection.findLibrary(sdkName) == null) { defineJdk(context.projectModel.global, sdkName, homePath) readModulesFromReleaseFile(context.projectModel, sdkName, homePath) } } } private fun readModulesFromReleaseFile(model: JpsModel, sdkName: String, sdkHome: Path) { val additionalSdk = model.global.libraryCollection.findLibrary(sdkName) ?: error("Sdk '$sdkName' is not found") val urls = additionalSdk.getRoots(JpsOrderRootType.COMPILED).mapTo(HashSet()) { it.url } for (it in readModulesFromReleaseFile(sdkHome)) { if (!urls.contains(it)) { additionalSdk.addRoot(it, JpsOrderRootType.COMPILED) } } } private fun CompilationContext.cleanOutput(keepCompilationState: Boolean) { val outDir = paths.buildOutputDir if (!options.cleanOutputFolder) { Span.current().addEvent("skip output cleaning", Attributes.of( AttributeKey.stringKey("dir"), "$outDir", )) return } val outputDirectoriesToKeep = HashSet<String>(4) outputDirectoriesToKeep.add("log") if (keepCompilationState) { outputDirectoriesToKeep.add(compilationData.dataStorageRoot.name) outputDirectoriesToKeep.add("classes") outputDirectoriesToKeep.add(paths.jpsArtifacts.name) } spanBuilder("clean output") .setAttribute("path", outDir.toString()) .setAttribute(AttributeKey.stringArrayKey("outputDirectoriesToKeep"), java.util.List.copyOf(outputDirectoriesToKeep)) .use { span -> Files.newDirectoryStream(outDir).use { dirStream -> for (file in dirStream) { val attributes = Attributes.of(AttributeKey.stringKey("dir"), outDir.relativize(file).toString()) if (outputDirectoriesToKeep.contains(file.name)) { span.addEvent("skip cleaning", attributes) } else { span.addEvent("delete", attributes) NioFiles.deleteRecursively(file) } } } null } } private fun printEnvironmentDebugInfo() { // print it to the stdout since TeamCity will remove any sensitive fields from build log automatically // don't write it to debug log file! val env = System.getenv() for (key in env.keys.sorted()) { println("ENV $key = ${env[key]}") } val properties = System.getProperties() for (propertyName in properties.keys.sortedBy { it as String }) { println("PROPERTY $propertyName = ${properties[propertyName].toString()}") } }
apache-2.0
7a9baf3cd58dc48dd12eef963a33dacd
44.430155
137
0.690175
5.452102
false
false
false
false
spacecowboy/Feeder
app/src/main/java/com/nononsenseapps/feeder/ui/compose/text/TextComposer.kt
1
4391
package com.nononsenseapps.feeder.ui.compose.text import androidx.compose.runtime.Composable import androidx.compose.ui.text.SpanStyle class TextComposer( val paragraphEmitter: (AnnotatedParagraphStringBuilder) -> Unit ) { val spanStack: MutableList<Span> = mutableListOf() // The identity of this will change - do not reference it in blocks private var builder: AnnotatedParagraphStringBuilder = AnnotatedParagraphStringBuilder() fun terminateCurrentText() { if (builder.isEmpty()) { // Nothing to emit, and nothing to reset return } paragraphEmitter(builder) builder = AnnotatedParagraphStringBuilder() for (span in spanStack) { when (span) { is SpanWithStyle -> builder.pushStyle(span.spanStyle) is SpanWithAnnotation -> builder.pushStringAnnotation( tag = span.tag, annotation = span.annotation ) is SpanWithComposableStyle -> builder.pushComposableStyle(span.spanStyle) is SpanWithVerbatim -> builder.pushVerbatimTtsAnnotation(span.verbatim) } } } val endsWithWhitespace: Boolean get() = builder.endsWithWhitespace fun ensureDoubleNewline() = builder.ensureDoubleNewline() fun append(text: String) = builder.append(text) fun append(char: Char) = builder.append(char) fun <R> appendTable(block: () -> R): R { builder.ensureDoubleNewline() terminateCurrentText() return block() } fun <R> appendImage( link: String? = null, onLinkClick: (String) -> Unit, block: ( onClick: (() -> Unit)? ) -> R ): R { val url = link ?: findClosestLink() builder.ensureDoubleNewline() terminateCurrentText() val onClick: (() -> Unit)? = if (url?.isNotBlank() == true) { { onLinkClick(url) } } else { null } return block(onClick) } fun pop(index: Int) = builder.pop(index) fun pushStyle(style: SpanStyle): Int = builder.pushStyle(style) fun pushStringAnnotation(tag: String, annotation: String): Int = builder.pushStringAnnotation(tag = tag, annotation = annotation) fun pushComposableStyle(style: @Composable () -> SpanStyle): Int = builder.pushComposableStyle(style) fun popComposableStyle(index: Int) = builder.popComposableStyle(index) private fun findClosestLink(): String? { for (span in spanStack.reversed()) { if (span is SpanWithAnnotation && span.tag == "URL") { return span.annotation } } return null } } inline fun <R : Any> TextComposer.withParagraph( crossinline block: TextComposer.() -> R ): R { ensureDoubleNewline() return block(this) } inline fun <R : Any> TextComposer.withStyle( style: SpanStyle, crossinline block: TextComposer.() -> R ): R { spanStack.add(SpanWithStyle(style)) val index = pushStyle(style) return try { block() } finally { pop(index) spanStack.removeLast() } } inline fun <R : Any> TextComposer.withComposableStyle( noinline style: @Composable () -> SpanStyle, crossinline block: TextComposer.() -> R ): R { spanStack.add(SpanWithComposableStyle(style)) val index = pushComposableStyle(style) return try { block() } finally { popComposableStyle(index) spanStack.removeLast() } } inline fun <R : Any> TextComposer.withAnnotation( tag: String, annotation: String, crossinline block: TextComposer.() -> R ): R { spanStack.add(SpanWithAnnotation(tag = tag, annotation = annotation)) val index = pushStringAnnotation(tag = tag, annotation = annotation) return try { block() } finally { pop(index) spanStack.removeLast() } } sealed class Span data class SpanWithStyle( val spanStyle: SpanStyle ) : Span() data class SpanWithAnnotation( val tag: String, val annotation: String ) : Span() data class SpanWithComposableStyle( val spanStyle: @Composable () -> SpanStyle ) : Span() data class SpanWithVerbatim( val verbatim: String ) : Span()
gpl-3.0
141fb80dc4d27754a2f6f43e1f3e9f49
25.293413
92
0.612844
4.671277
false
false
false
false
DmytroTroynikov/aemtools
aem-intellij-core/src/main/kotlin/com/aemtools/completion/html/inserthandler/HtlTextInsertHandler.kt
1
1037
package com.aemtools.completion.html.inserthandler import com.aemtools.common.util.hasText import com.intellij.codeInsight.completion.InsertHandler import com.intellij.codeInsight.completion.InsertionContext import com.intellij.codeInsight.lookup.LookupElement import com.intellij.openapi.editor.Document /** * Base htl text insert handler. */ abstract class HtlTextInsertHandler(private val expression: String, private val offset: Int) : InsertHandler<LookupElement> { override fun handleInsert(context: InsertionContext, item: LookupElement) { val document = context.document val editor = context.editor val position = editor.caretModel.offset if (!tagHasExpression(document, position)) { document.insertString(position, expression) editor.caretModel.moveToOffset(position + offset) } } private fun tagHasExpression(document: Document, position: Int) = document.hasText("='$expression", position) || document.hasText("=\"$expression", position) }
gpl-3.0
17f0550ffac0d648078e386112cf4ffb
34.758621
97
0.746384
4.756881
false
false
false
false
fluidsonic/fluid-json
examples/sources-jvm/0002-CustomProperties.kt
1
1360
package examples import io.fluidsonic.json.* // Note that IntelliJ IDEA still only has limited supported for annotation processing with kapt, so enable this setting first: // Preferences > Build, Execution, Deployment > Build Tools > Gradle > Runner > Delegate IDE build/run actions to gradle // @Json.CustomProperties allows writing custom code to add properties on-the-fly, potentially making use of a context object. fun main() { val serializer = JsonCodingSerializer .builder(MyContext(authenticatedUserId = "5678")) .encodingWith(JsonCodecProvider.generated(MyCodecProvider::class)) .build() println(serializer.serializeValue(listOf( User(id = "1234", name = "Some Other User", emailAddress = "[email protected]"), User(id = "5678", name = "Authenticated User", emailAddress = "[email protected]") ))) } @Json( decoding = Json.Decoding.none, // prevent decoding altogether encoding = Json.Encoding.annotatedProperties // only encode properties annotated explicitly ) data class User( @Json.Property val id: String, @Json.Property val name: String, val emailAddress: String ) @Json.CustomProperties // function will be called during encoding fun JsonEncoder<MyContext>.writeCustomProperties(value: User) { if (context.authenticatedUserId == value.id) writeMapElement("emailAddress", value = value.emailAddress) }
apache-2.0
64204ab9411bb7d05b365becd0daa73f
33.871795
126
0.752206
4.108761
false
false
false
false
allotria/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/comment/ui/GHSubmittableTextFieldFactory.kt
2
1838
// 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.plugins.github.pullrequest.comment.ui import com.intellij.ide.BrowserUtil import com.intellij.openapi.util.NlsActions import com.intellij.ui.components.labels.LinkLabel import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.intellij.util.ui.codereview.timeline.comment.SubmittableTextField import com.intellij.util.ui.codereview.timeline.comment.SubmittableTextField.Companion.getEditorTextFieldVerticalOffset import com.intellij.util.ui.codereview.timeline.comment.SubmittableTextFieldModel import org.jetbrains.plugins.github.api.data.GHUser import org.jetbrains.plugins.github.i18n.GithubBundle import org.jetbrains.plugins.github.ui.avatars.GHAvatarIconsProvider import javax.swing.JComponent class GHSubmittableTextFieldFactory(private val model: SubmittableTextFieldModel) { fun create( @NlsActions.ActionText actionName: String = GithubBundle.message("action.comment.text"), onCancel: (() -> Unit)? = null ): JComponent = SubmittableTextField(actionName, model, onCancel = onCancel) fun create( avatarIconsProvider: GHAvatarIconsProvider, author: GHUser, @NlsActions.ActionText actionName: String = GithubBundle.message("action.comment.text"), onCancel: (() -> Unit)? = null ): JComponent { val authorLabel = LinkLabel.create("") { BrowserUtil.browse(author.url) }.apply { icon = avatarIconsProvider.getIcon(author.avatarUrl) isFocusable = true border = JBUI.Borders.empty(getEditorTextFieldVerticalOffset() - 2, 0) putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) } return SubmittableTextField(actionName, model, authorLabel, onCancel) } }
apache-2.0
35e4d74d071c11fd374a2bdc687f02bb
44.95
140
0.785637
4.418269
false
false
false
false
zpao/buck
src/com/facebook/buck/multitenant/runner/FakeMultitenantService.kt
1
3495
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.buck.multitenant.runner import com.facebook.buck.core.cell.name.CanonicalCellName import com.facebook.buck.core.cell.nameresolver.CellNameResolver import com.facebook.buck.core.path.ForwardRelativePath import com.facebook.buck.multitenant.query.MultitenantQueryEnvironment import com.facebook.buck.multitenant.service.DefaultFsToBuildPackageChangeTranslator import com.facebook.buck.multitenant.service.FsChanges import com.facebook.buck.multitenant.service.Index import com.facebook.buck.multitenant.service.IndexAppender import com.facebook.buck.query.QueryNormalizer import com.google.common.collect.ImmutableMap import java.nio.file.Path import java.util.Optional /** * Note that a real implementation of the service would subscribe to new commits to the repo and use * the changeTranslator to take the commit data and turn it into a [BuildPackageChanges] that it can * record via [IndexAppender.addCommitData]. */ class FakeMultitenantService( private val index: Index, private val indexAppender: IndexAppender, private val buildFileName: ForwardRelativePath, private val projectRoot: Path ) { fun handleBuckQueryRequest(query: String, changes: FsChanges): List<String> { val generation = requireNotNull(indexAppender.getGeneration(changes.commit)) { "commit '${changes.commit}' not indexed by service" } val changeTranslator = DefaultFsToBuildPackageChangeTranslator(buildFileName = buildFileName, projectRoot = projectRoot, existenceChecker = { path -> index.packageExists(generation, path) }, equalityChecker = { buildPackage -> index.containsBuildPackage(generation, buildPackage) }, includesProvider = { path -> index.getReverseIncludes(generation, path) }) val buildPackageChanges = changeTranslator.translateChanges(changes) val localizedIndex = index.createIndexForGenerationWithLocalChanges(generation, buildPackageChanges) val cellToBuildFileName = mapOf("" to "BUCK") val env = MultitenantQueryEnvironment(localizedIndex, generation, cellToBuildFileName, object : CellNameResolver { override fun getName(localName: Optional<String>?): CanonicalCellName { TODO("not implemented") } override fun getNameIfResolvable( localName: Optional<String>? ): Optional<CanonicalCellName> { TODO("not implemented") } override fun getKnownCells(): ImmutableMap<Optional<String>, CanonicalCellName>? { TODO("not implemented") } }) val queryTargets = env.evaluateQuery(QueryNormalizer.normalize(query)) return queryTargets.map { it.toString() } } }
apache-2.0
ab022dc4d2fc7f6f0b4fab9a2faa0460
43.807692
103
0.711874
4.748641
false
false
false
false
andrewoma/kson
src/main/kotlin/com/github/andrewoma/kson/JsValue.kt
1
3696
/* * Copyright (c) 2014 Andrew O'Malley * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.andrewoma.kson import java.math.BigDecimal import java.util.NoSuchElementException interface JsValue : Iterable<JsValue> { open operator fun get(name: String): JsValue = JsUndefined override fun iterator(): Iterator<JsValue> { return object : Iterator<JsValue> { var next = true override fun next() = if (hasNext()) { next = false this@JsValue } else { throw NoSuchElementException() } override fun hasNext() = next } } open fun asString(): String? = null open fun asBoolean(): Boolean? = null open fun asInt(): Int? = null open fun asLong(): Long? = null open fun asFloat(): Float? = null open fun asDouble(): Double? = null open fun asBigDecimal(): BigDecimal? = null } fun JsObject(vararg fields: Pair<String, JsValue>): JsObject = JsObject(linkedMapOf(*fields)) data class JsObject(val fields: Map<String, JsValue>) : JsValue { override fun get(name: String) = fields.getOrElse(name) { super.get(name) } override fun iterator() = fields.values.iterator() override fun toString(): String { return "JsObject($fields)" } } data class JsString(val value: String?) : JsValue { override fun asString(): String? = value } data class JsNumber(val value: BigDecimal?) : JsValue { override fun asInt() = value?.toInt() override fun asLong() = value?.toLong() override fun asFloat() = value?.toFloat() override fun asDouble() = value?.toDouble() override fun asBigDecimal() = value } data class JsBoolean(val value: Boolean?) : JsValue { override fun asBoolean() = value } fun JsArray(vararg values: JsValue): JsValue = JsArray(values.toList()) data class JsArray(val values: List<JsValue>) : JsValue { override fun iterator() = values.iterator() } object JsUndefined : JsValue object JsNull : JsValue fun toJsValue(value: Any?): JsValue { if (value == null) return JsNull return when (value) { is JsValue -> value is String -> JsString(value) is Boolean -> JsBoolean(value) is Int -> JsNumber(BigDecimal(value)) is Long -> JsNumber(BigDecimal(value)) is Float -> JsNumber(BigDecimal(value.toDouble())) is Double -> JsNumber(BigDecimal(value)) is Number -> JsNumber(BigDecimal(value.toString())) else -> throw IllegalArgumentException("Cannot convert ${value.javaClass.name} to a JsValue") } } // TODO ... add fromJsValue to "unwrap" values?
mit
0597e542657307e28dfd48fff8feb9ff
33.867925
101
0.678842
4.389549
false
false
false
false
leafclick/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/GHPRRequestExecutorComponent.kt
1
3148
// 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.pullrequest import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.wm.IdeFocusManager import com.intellij.ui.SimpleTextAttributes import com.intellij.util.ui.UIUtil import org.jetbrains.plugins.github.api.GithubApiRequestExecutor import org.jetbrains.plugins.github.api.GithubApiRequestExecutorManager import org.jetbrains.plugins.github.authentication.accounts.AccountTokenChangedListener import org.jetbrains.plugins.github.authentication.accounts.GithubAccount import org.jetbrains.plugins.github.authentication.accounts.GithubAccountManager import org.jetbrains.plugins.github.ui.util.DisposingWrapper import org.jetbrains.plugins.github.util.GitRemoteUrlCoordinates import org.jetbrains.plugins.github.util.GithubUIUtil class GHPRRequestExecutorComponent(private val requestExecutorManager: GithubApiRequestExecutorManager, private val project: Project, private val remoteUrl: GitRemoteUrlCoordinates, val account: GithubAccount, parentDisposable: Disposable) : DisposingWrapper(parentDisposable) { private val componentFactory by lazy(LazyThreadSafetyMode.NONE) { project.service<GHPRComponentFactory>() } private var requestExecutor: GithubApiRequestExecutor? = null init { background = UIUtil.getListBackground() ApplicationManager.getApplication().messageBus.connect(parentDisposable) .subscribe(GithubAccountManager.ACCOUNT_TOKEN_CHANGED_TOPIC, object : AccountTokenChangedListener { override fun tokenChanged(account: GithubAccount) { update() } }) update() } private fun update() { if (requestExecutor != null) return try { val executor = requestExecutorManager.getExecutor(account) setActualContent(executor) } catch (e: Exception) { setCenteredContent(GithubUIUtil.createNoteWithAction(::createRequestExecutorWithUserInput).apply { append("Log in", SimpleTextAttributes.LINK_ATTRIBUTES, Runnable { createRequestExecutorWithUserInput() }) append(" to GitHub to view pull requests", SimpleTextAttributes.GRAYED_ATTRIBUTES) }) } } private fun createRequestExecutorWithUserInput() { requestExecutorManager.getExecutor(account, project) IdeFocusManager.getInstance(project).requestFocusInProject(this@GHPRRequestExecutorComponent, project) } private fun setActualContent(executor: GithubApiRequestExecutor.WithTokenAuth) { requestExecutor = executor val disposable = Disposer.newDisposable() setContent(componentFactory.createComponent(remoteUrl, account, executor, disposable), disposable) } }
apache-2.0
90ea4e70e9ca271321bf3fbeac0f1984
43.985714
140
0.752224
5.522807
false
false
false
false
VREMSoftwareDevelopment/WiFiAnalyzer
app/src/main/kotlin/com/vrem/wifianalyzer/wifi/model/GroupBy.kt
1
1413
/* * WiFiAnalyzer * Copyright (C) 2015 - 2022 VREM Software Development <[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.vrem.wifianalyzer.wifi.model typealias GroupByKey<T> = (T) -> String internal val groupByChannel: GroupByKey<WiFiDetail> = { it.wiFiSignal.primaryFrequency.toString() } internal val groupBySSID: GroupByKey<WiFiDetail> = { it.wiFiIdentifier.ssid } internal val groupByVirtual: GroupByKey<WiFiDetail> = { it.wiFiVirtual.key } enum class GroupBy(val sort: Comparator<WiFiDetail>, val group: GroupByKey<WiFiDetail>) { NONE(sortByDefault(), groupBySSID), SSID(sortBySSID(), groupBySSID), CHANNEL(sortByChannel(), groupByChannel), VIRTUAL(sortBySSID(), groupByVirtual); val none: Boolean get() = NONE == this }
gpl-3.0
5a478aa4b2dae9c5aa0cdddaa9563b15
37.216216
99
0.7431
4.205357
false
false
false
false
peervalhoegen/SudoQ
sudoq-app/sudoqapp/src/main/kotlin/de/sudoq/controller/menus/preferences/RestrictTypesAdapter.kt
1
2811
/* * SudoQ is a Sudoku-App for Adroid Devices with Version 2.2 at least. * Copyright (C) 2012 Heiko Klare, Julian Geppert, Jan-Bernhard Kordaß, Jonathan Kieling, Tim Zeitz, Timo Abele * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. */ package de.sudoq.controller.menus.preferences import android.content.Context import android.graphics.Color import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.TextView import de.sudoq.R import de.sudoq.controller.menus.Utility import de.sudoq.model.sudoku.sudokuTypes.SudokuTypes import de.sudoq.persistence.sudoku.sudokuTypes.SudokuTypesListBE /** * Adapter für die Anzeige aller zu wählenden Sudoku Typen */ class RestrictTypesAdapter(context: Context, typesList: ArrayList<SudokuTypes>) : ArrayAdapter<SudokuTypes>(context, R.layout.restricttypes_item, SudokuTypes.values().toList()) { private val types: List<SudokuTypes> /** * {@inheritDoc} */ override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater val rowView = inflater.inflate(R.layout.restricttypes_item, parent, false) val type = super.getItem(position)!! val full = Utility.type2string(context, type) //translated name of Sudoku type; (rowView.findViewById(R.id.regular_languages_layout) as View).visibility = View.GONE (rowView.findViewById(R.id.irregular_languages_layout) as View).visibility = View.VISIBLE val sudokuType = rowView.findViewById<View>(R.id.combined_label) as TextView sudokuType.text = full val color = if (types.contains(type)) Color.BLACK else Color.LTGRAY sudokuType.setTextColor(color) return rowView } companion object { } /** * Erzeugt einen neuen SudokuLoadingAdpater mit den gegebenen Parametern * * @param context * der Applikationskontext * @param typesList * die Liste der Typen */ init { types = typesList Log.d("rtAdap", "rtAdap is initialized, size: " + types.size) } }
gpl-3.0
446a1eb778004fd281132b6019d9807a
43.587302
243
0.734687
4.222556
false
false
false
false
smmribeiro/intellij-community
plugins/ide-features-trainer/src/training/ui/views/LearnPanel.kt
1
15306
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package training.ui.views import com.intellij.icons.AllIcons import com.intellij.ide.IdeBundle import com.intellij.openapi.project.DumbService import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.impl.CloseProjectWindowHelper import com.intellij.ui.components.JBScrollPane import com.intellij.ui.components.labels.LinkLabel import com.intellij.ui.components.labels.LinkListener import com.intellij.ui.components.panels.VerticalBox import com.intellij.util.ui.JBInsets import com.intellij.util.ui.JBUI import com.intellij.util.ui.StartupUiUtil import org.intellij.lang.annotations.Language import training.lang.LangManager import training.learn.CourseManager import training.learn.LearnBundle import training.learn.course.Lesson import training.learn.lesson.LessonManager import training.statistic.LessonStartingWay import training.statistic.StatisticBase import training.ui.* import training.util.* import java.awt.* import java.awt.event.* import javax.swing.* import javax.swing.border.EmptyBorder import javax.swing.border.MatteBorder import kotlin.math.max internal class LearnPanel(val learnToolWindow: LearnToolWindow) : JPanel() { private val lessonPanel = JPanel() val lessonMessagePane = LessonMessagePane() private var nextButton: JButton? = null private val scrollPane = JBScrollPane(lessonPanel) private val stepAnimator = StepAnimator(scrollPane.verticalScrollBar, lessonMessagePane) private val lessonPanelBoxLayout = BoxLayout(lessonPanel, BoxLayout.Y_AXIS) internal var scrollToNewMessages = true init { isFocusable = false background = UISettings.instance.backgroundColor layout = BoxLayout(this, BoxLayout.Y_AXIS) isOpaque = true scrollPane.addComponentListener(object: ComponentAdapter() { override fun componentResized(e: ComponentEvent?) { updatePanelSize(getVisibleAreaWidth()) } }) } fun reinitMe(lesson: Lesson) { with(UISettings.instance) { border = EmptyBorder(northInset, 0, southInset, 0) } scrollToNewMessages = true clearMessages() lessonPanel.removeAll() removeAll() add(createHeaderPanel(lesson)) add(createSmallSeparator()) add(scaledRigid(UISettings.instance.panelWidth, JBUI.scale(4))) initLessonPanel(lesson) scrollPane.alignmentX = LEFT_ALIGNMENT add(scrollPane) } fun updatePanelSize(viewAreaWidth: Int) { val width = max(UISettings.instance.panelWidth, viewAreaWidth) - 2 * UISettings.instance.learnPanelSideOffset lessonMessagePane.preferredSize = null lessonMessagePane.setBounds(0, 0, width, 10000) lessonMessagePane.revalidate() lessonMessagePane.repaint() lessonMessagePane.preferredSize = Dimension(width, lessonMessagePane.preferredSize.height) lessonPanel.revalidate() lessonPanel.doLayout() // need to reset correct location for auto-scroll lessonPanel.repaint() } private fun createFooterPanel(lesson: Lesson): JPanel { val shiftedFooter = JPanel() shiftedFooter.name = "footerLessonPanel" shiftedFooter.layout = BoxLayout(shiftedFooter, BoxLayout.Y_AXIS) shiftedFooter.isFocusable = false shiftedFooter.isOpaque = false shiftedFooter.border = MatteBorder(JBUI.scale(1), 0, 0, 0, UISettings.instance.separatorColor) val footerContent = JPanel() footerContent.isOpaque = false footerContent.layout = BoxLayout(footerContent, BoxLayout.Y_AXIS) footerContent.add(rigid(0, 16)) footerContent.add(JLabel(IdeBundle.message("welcome.screen.learnIde.help.and.resources.text")).also { it.font = UISettings.instance.getFont(1).deriveFont(Font.BOLD) }) for (helpLink in lesson.helpLinks) { val text = helpLink.key val link = helpLink.value val linkLabel = LinkLabel<Any>(text, null) { _, _ -> openLinkInBrowser(link) StatisticBase.logHelpLinkClicked(lesson.id) } footerContent.add(rigid(0, 5)) footerContent.add(linkLabel.wrapWithUrlPanel()) } shiftedFooter.add(footerContent) shiftedFooter.add(Box.createHorizontalGlue()) val footer = JPanel() footer.add(shiftedFooter) footer.alignmentX = Component.LEFT_ALIGNMENT footer.isOpaque = false footer.layout = BoxLayout(footer, BoxLayout.Y_AXIS) footer.border = UISettings.instance.lessonHeaderBorder return footer } private fun initLessonPanel(lesson: Lesson) { lessonPanel.name = "lessonPanel" lessonPanel.layout = lessonPanelBoxLayout lessonPanel.isFocusable = false lessonPanel.isOpaque = true with(UISettings.instance) { lessonPanel.background = backgroundColor lessonPanel.border = EmptyBorder(0, learnPanelSideOffset, 0, learnPanelSideOffset) } lessonMessagePane.name = "lessonMessagePane" lessonMessagePane.isFocusable = false lessonMessagePane.isOpaque = false lessonMessagePane.alignmentX = Component.LEFT_ALIGNMENT lessonMessagePane.margin = JBInsets.emptyInsets() lessonMessagePane.border = EmptyBorder(0, 0, JBUI.scale(20), JBUI.scale(14)) lessonPanel.add(scaledRigid(UISettings.instance.panelWidth - 2 * UISettings.instance.learnPanelSideOffset, JBUI.scale(19))) lessonPanel.add(createLessonNameLabel(lesson)) lessonPanel.add(lessonMessagePane) lessonPanel.add(createButtonsPanel()) lessonPanel.add(Box.createVerticalGlue()) if (lesson.helpLinks.isNotEmpty() && Registry.`is`("ift.help.links", false)) { lessonPanel.add(rigid(0, 16)) lessonPanel.add(createFooterPanel(lesson)) } } private fun createLessonNameLabel(lesson: Lesson): JLabel { val lessonNameLabel = JLabel() lessonNameLabel.name = "lessonNameLabel" lessonNameLabel.border = UISettings.instance.lessonHeaderBorder lessonNameLabel.font = UISettings.instance.getFont(5).deriveFont(Font.BOLD) lessonNameLabel.alignmentX = Component.LEFT_ALIGNMENT lessonNameLabel.isFocusable = false lessonNameLabel.text = lesson.name lessonNameLabel.foreground = UISettings.instance.defaultTextColor return lessonNameLabel } private fun createHeaderPanel(lesson: Lesson): VerticalBox { val moduleNameLabel: JLabel = LinkLabelWithBackArrow<Any> { _, _ -> StatisticBase.logLessonStopped(StatisticBase.LessonStopReason.OPEN_MODULES) LessonManager.instance.stopLesson() LearningUiManager.resetModulesView() } moduleNameLabel.name = "moduleNameLabel" moduleNameLabel.font = UISettings.instance.getFont(1) moduleNameLabel.text = " ${lesson.module.name}" moduleNameLabel.foreground = UISettings.instance.defaultTextColor moduleNameLabel.isFocusable = false val linksPanel = JPanel() linksPanel.isOpaque = false linksPanel.layout = BoxLayout(linksPanel, BoxLayout.X_AXIS) linksPanel.alignmentX = LEFT_ALIGNMENT linksPanel.border = EmptyBorder(0, 0, JBUI.scale(12), 0) linksPanel.add(moduleNameLabel) linksPanel.add(Box.createHorizontalGlue()) val exitLink = JLabel(LearnBundle.message("exit.learning.link"), AllIcons.Actions.Exit, SwingConstants.LEADING) exitLink.cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) exitLink.addMouseListener(object : MouseAdapter() { override fun mouseClicked(e: MouseEvent) { if (!StatisticBase.isLearnProjectCloseLogged) { StatisticBase.logLessonStopped(StatisticBase.LessonStopReason.EXIT_LINK) } LessonManager.instance.stopLesson() val langSupport = LangManager.getInstance().getLangSupport() val project = learnToolWindow.project langSupport?.onboardingFeedbackData?.let { showOnboardingLessonFeedbackForm(project, it, false) langSupport.onboardingFeedbackData = null } if (langSupport != null && isLearningProject(project, langSupport)) { CloseProjectWindowHelper().windowClosing(project) } else { LearningUiManager.resetModulesView() ToolWindowManager.getInstance(project).getToolWindow(LearnToolWindowFactory.LEARN_TOOL_WINDOW)?.hide() } } }) linksPanel.add(exitLink) val headerPanel = VerticalBox() headerPanel.isOpaque = false headerPanel.alignmentX = LEFT_ALIGNMENT headerPanel.border = UISettings.instance.lessonHeaderBorder headerPanel.add(linksPanel) return headerPanel } fun addMessage(@Language("HTML") text: String, properties: LessonMessagePane.MessageProperties = LessonMessagePane.MessageProperties()) { val messages = MessageFactory.convert(text) MessageFactory.setLinksHandlers(messages) addMessages(messages, properties) } fun addMessages(messageParts: List<MessagePart>, properties: LessonMessagePane.MessageProperties = LessonMessagePane.MessageProperties()) { val needToShow = lessonMessagePane.addMessage(messageParts, properties) adjustMessagesArea() if (properties.state != LessonMessagePane.MessageState.INACTIVE) { scrollToMessage(needToShow()) } } fun focusCurrentMessage() { scrollToMessage(lessonMessagePane.getCurrentMessageRectangle()) } private fun scrollToMessage(needToShow: Rectangle?) { if (needToShow == null) return if (scrollToNewMessages) { adjustMessagesArea() val visibleSize = lessonPanel.visibleRect.size val needToScroll = max(0, needToShow.y + lessonMessagePane.location.y - visibleSize.height / 2 + needToShow.height / 2) scrollTo(needToScroll) } } fun adjustMessagesArea() { updatePanelSize(getVisibleAreaWidth()) revalidate() repaint() } fun resetMessagesNumber(number: Int) { val needToShow = lessonMessagePane.resetMessagesNumber(number) adjustMessagesArea() scrollToMessage(needToShow()) } fun removeInactiveMessages(number: Int) { lessonMessagePane.removeInactiveMessages(number) adjustMessagesArea() // TODO: fix it } fun messagesNumber(): Int = lessonMessagePane.messagesNumber() fun setPreviousMessagesPassed() { lessonMessagePane.passPreviousMessages() adjustMessagesArea() } private fun clearMessages() { lessonMessagePane.clear() } private fun createButtonsPanel(): JPanel { val buttonPanel = JPanel() buttonPanel.name = "buttonPanel" buttonPanel.border = EmptyBorder(0, UISettings.instance.checkIndent - JButton().insets.left, 0, 0) buttonPanel.isOpaque = false buttonPanel.isFocusable = false buttonPanel.layout = BoxLayout(buttonPanel, BoxLayout.X_AXIS) buttonPanel.alignmentX = Component.LEFT_ALIGNMENT rootPane?.defaultButton = null val previousLesson = getPreviousLessonForCurrent() val prevButton = previousLesson?.let { createNavigationButton(previousLesson, isNext = false) } val nextLesson = getNextLessonForCurrent() nextButton = nextLesson?.let { createNavigationButton(nextLesson, isNext = true) } for (button in listOfNotNull(prevButton, nextButton)) { button.margin = JBInsets.emptyInsets() button.isFocusable = false button.isEnabled = true button.isOpaque = false buttonPanel.add(button) } return buttonPanel } private fun createNavigationButton(targetLesson: Lesson, isNext: Boolean): JButton { val button = JButton() button.action = object : AbstractAction() { override fun actionPerformed(actionEvent: ActionEvent) { StatisticBase.logLessonStopped(StatisticBase.LessonStopReason.OPEN_NEXT_OR_PREV_LESSON) val startingWay = if (isNext) LessonStartingWay.NEXT_BUTTON else LessonStartingWay.PREV_BUTTON CourseManager.instance.openLesson(learnToolWindow.project, targetLesson, startingWay) } } button.text = if (isNext) { LearnBundle.message("learn.new.ui.button.next", targetLesson.name) } else LearnBundle.message("learn.new.ui.button.back") button.updateUI() button.isSelected = true if (!targetLesson.passed && !targetLesson.properties.canStartInDumbMode && DumbService.getInstance(learnToolWindow.project).isDumb) { button.isEnabled = false button.toolTipText = LearnBundle.message("indexing.message") button.isSelected = false DumbService.getInstance(learnToolWindow.project).runWhenSmart { button.isEnabled = true button.toolTipText = "" button.isSelected = true } } return button } fun makeNextButtonSelected() { nextButton?.let { rootPane?.defaultButton = it it.isSelected = true it.isFocusable = true it.requestFocus() } if (scrollToNewMessages) { adjustMessagesArea() scrollToTheEnd() } } fun clearRestoreMessage() { val needToShow = lessonMessagePane.clearRestoreMessages() scrollToMessage(needToShow()) } fun removeMessage(index: Int) { lessonMessagePane.removeMessage(index) } private fun getVisibleAreaWidth(): Int { val scrollWidth = scrollPane.verticalScrollBar?.size?.width ?: 0 return scrollPane.viewport.extentSize.width - scrollWidth } private fun scrollToTheEnd() { val vertical = scrollPane.verticalScrollBar if (useAnimation()) stepAnimator.startAnimation(vertical.maximum) else vertical.value = vertical.maximum } fun scrollToTheStart() { scrollPane.verticalScrollBar.value = 0 } private fun scrollTo(needTo: Int) { if (useAnimation()) stepAnimator.startAnimation(needTo) else { scrollPane.verticalScrollBar.value = needTo } } private fun useAnimation() = Registry.`is`("ift.use.scroll.animation", false) } private class LinkLabelWithBackArrow<T>(linkListener: LinkListener<T>) : LinkLabel<T>("", null, linkListener) { init { font = StartupUiUtil.getLabelFont() } override fun paint(g: Graphics?) { super.paint(g) val arrowWingHeight = textBounds.height / 4 val g2d = g as Graphics2D g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) val stroke3: Stroke = BasicStroke(1.2f * font.size / 13, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND) g2d.stroke = stroke3 g2d.color = foreground g2d.drawLine(textBounds.x, textBounds.y + textBounds.height / 2, textBounds.x + 5 * textBounds.height / 17, textBounds.y + textBounds.height / 2 - arrowWingHeight) g2d.drawLine(textBounds.x, textBounds.y + textBounds.height / 2, textBounds.x + 9 * textBounds.height / 17, textBounds.y + textBounds.height / 2) g2d.drawLine(textBounds.x, textBounds.y + textBounds.height / 2, textBounds.x + 5 * textBounds.height / 17, textBounds.y + textBounds.height / 2 + arrowWingHeight) } } private fun createSmallSeparator(): Component { // Actually standard JSeparator can be used, but it adds some extra size for Y and I don't know how to fix it :( val separatorPanel = JPanel() separatorPanel.isOpaque = false separatorPanel.layout = BoxLayout(separatorPanel, BoxLayout.X_AXIS) separatorPanel.add(Box.createHorizontalGlue()) separatorPanel.border = MatteBorder(0, 0, JBUI.scale(1), 0, UISettings.instance.separatorColor) return separatorPanel }
apache-2.0
8ffa9458dbbe78747f31eb4b5d90acb0
35.705036
139
0.735071
4.656526
false
false
false
false
smmribeiro/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/bundled/bundledGroovy.kt
7
1800
// 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. @file:JvmName("BundledGroovy") package org.jetbrains.plugins.groovy.bundled import com.intellij.openapi.application.PathManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.io.JarUtil.getJarAttribute import com.intellij.openapi.vfs.JarFileSystem import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.GlobalSearchScopesCore import groovy.lang.GroovyObject import org.jetbrains.plugins.groovy.config.AbstractConfigUtils.UNDEFINED_VERSION import java.io.File import java.util.jar.Attributes.Name.IMPLEMENTATION_VERSION val bundledGroovyVersion: @NlsSafe String by lazy(::doGetBundledGroovyVersion) private fun doGetBundledGroovyVersion(): String = getJarAttribute(bundledGroovyFile, IMPLEMENTATION_VERSION) ?: UNDEFINED_VERSION val bundledGroovyFile: File by lazy(::doGetBundledGroovyFile) private fun doGetBundledGroovyFile(): File { val jarPath = PathManager.getJarPathForClass(GroovyObject::class.java) ?: error("Cannot find JAR containing groovy classes") return File(jarPath) } val bundledGroovyJarRoot: VirtualFile? by lazy(::doGetBundledGroovyRoot) private fun doGetBundledGroovyRoot(): VirtualFile? { val jar = bundledGroovyFile val jarFile = VfsUtil.findFileByIoFile(jar, false) ?: return null return JarFileSystem.getInstance().getJarRootForLocalFile(jarFile) } fun createBundledGroovyScope(project: Project): GlobalSearchScope? { val root = bundledGroovyJarRoot ?: return null return GlobalSearchScopesCore.directoryScope(project, root, true) }
apache-2.0
6b2b5e290c3ce1a3ba6d03276ea71da8
41.857143
140
0.825556
4.390244
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/roots/KotlinNonJvmOrderEnumerationHandler.kt
6
1594
// 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.roots import com.intellij.openapi.module.Module import com.intellij.openapi.roots.ModuleRootModel import com.intellij.openapi.roots.OrderEnumerationHandler import com.intellij.openapi.roots.OrderRootType import org.jetbrains.jps.model.module.JpsModuleSourceRootType import org.jetbrains.kotlin.config.TestResourceKotlinRootType import org.jetbrains.kotlin.config.TestSourceKotlinRootType object KotlinNonJvmOrderEnumerationHandler : OrderEnumerationHandler() { class Factory : OrderEnumerationHandler.Factory() { override fun isApplicable(module: Module) = true override fun createHandler(module: Module) = KotlinNonJvmOrderEnumerationHandler } private val kotlinTestSourceRootTypes: Set<JpsModuleSourceRootType<*>> = setOf(TestSourceKotlinRootType, TestResourceKotlinRootType) override fun addCustomModuleRoots( type: OrderRootType, rootModel: ModuleRootModel, result: MutableCollection<String>, includeProduction: Boolean, includeTests: Boolean ): Boolean { if (type == OrderRootType.SOURCES) { if (includeProduction) { rootModel.getSourceRoots(includeTests).mapTo(result) { it.url } } else { rootModel.getSourceRoots(kotlinTestSourceRootTypes).mapTo(result) { it.url } } return true } return false } }
apache-2.0
7965a9d06dabd3a6d87d0178f6847a0a
39.897436
158
0.730238
5.175325
false
true
false
false
smmribeiro/intellij-community
plugins/editorconfig/src/org/editorconfig/language/psi/base/EditorConfigOptionValueIdentifierBase.kt
16
1530
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.editorconfig.language.psi.base import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import org.editorconfig.language.psi.EditorConfigOptionValueIdentifier import org.editorconfig.language.psi.impl.EditorConfigValueIdentifierDescriptorFinderVisitor import org.editorconfig.language.schema.descriptors.EditorConfigDescriptor import org.editorconfig.language.schema.descriptors.impl.EditorConfigUnsetValueDescriptor import org.editorconfig.language.services.EditorConfigElementFactory abstract class EditorConfigOptionValueIdentifierBase(node: ASTNode) : EditorConfigIdentifierElementBase(node), EditorConfigOptionValueIdentifier { final override fun getDescriptor(smart: Boolean): EditorConfigDescriptor? { val parent = describableParent ?: return null val visitor = EditorConfigValueIdentifierDescriptorFinderVisitor(this) val parentDescriptor = parent.getDescriptor(smart) ?: return null parentDescriptor.accept(visitor) return visitor.descriptor ?: unsetDescriptor } private val unsetDescriptor get() = if (EditorConfigUnsetValueDescriptor.matches(this)) EditorConfigUnsetValueDescriptor else null final override fun setName(newName: String): PsiElement { val factory = EditorConfigElementFactory.getInstance(project) val result = factory.createValueIdentifier(newName) replace(result) return result } }
apache-2.0
f7182b71b12bf30e50027797e79dd570
46.8125
140
0.82549
5.117057
false
true
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/ui/dsl/gridLayout/impl/GridImpl.kt
1
20321
// 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.ui.dsl.gridLayout.impl import com.intellij.ui.dsl.UiDslException import com.intellij.ui.dsl.checkTrue import com.intellij.ui.dsl.gridLayout.* import org.jetbrains.annotations.ApiStatus import java.awt.Dimension import java.awt.Insets import java.awt.Rectangle import java.util.* import javax.swing.JComponent import kotlin.math.max import kotlin.math.min @ApiStatus.Internal internal class GridImpl : Grid { override val resizableColumns = mutableSetOf<Int>() override val resizableRows = mutableSetOf<Int>() override val columnsGaps = mutableListOf<HorizontalGaps>() override val rowsGaps = mutableListOf<VerticalGaps>() val visible: Boolean get() = cells.any { it.visible } private val layoutData = LayoutData() private val cells = mutableListOf<Cell>() fun register(component: JComponent, constraints: Constraints) { if (!isEmpty(constraints)) { throw UiDslException("Some cells are occupied already: $constraints") } cells.add(ComponentCell(constraints, component)) } fun registerSubGrid(constraints: Constraints): Grid { if (!isEmpty(constraints)) { throw UiDslException("Some cells are occupied already: $constraints") } val result = GridImpl() cells.add(GridCell(constraints, result)) return result } fun unregister(component: JComponent): Boolean { val iterator = cells.iterator() for (cell in iterator) { when (cell) { is ComponentCell -> { if (cell.component == component) { iterator.remove() return true } } is GridCell -> { if (cell.content.unregister(component)) { return true } } } } return false } fun getPreferredSizeData(parentInsets: Insets): PreferredSizeData { calculatePreferredLayoutData() val outsideGaps = layoutData.getOutsideGaps(parentInsets) return PreferredSizeData(Dimension(layoutData.preferredWidth + outsideGaps.width, layoutData.preferredHeight + outsideGaps.height), outsideGaps ) } /** * Calculates [layoutData] and layouts all components */ fun layout(width: Int, height: Int, parentInsets: Insets) { calculatePreferredLayoutData() val outsideGaps = layoutData.getOutsideGaps(parentInsets) // Recalculate LayoutData for requested size with corrected insets calculateLayoutDataStep2(width - outsideGaps.width) calculateLayoutDataStep3() calculateLayoutDataStep4(height - outsideGaps.height) layout(outsideGaps.left, outsideGaps.top) } /** * Layouts components */ fun layout(x: Int, y: Int) { for (layoutCellData in layoutData.visibleCellsData) { val bounds = calculateBounds(layoutCellData, x, y) when (val cell = layoutCellData.cell) { is ComponentCell -> { cell.component.bounds = bounds } is GridCell -> { cell.content.layout(bounds.x, bounds.y) } } } } /** * Calculates [layoutData] for preferred size */ private fun calculatePreferredLayoutData() { calculateLayoutDataStep1() calculateLayoutDataStep2(layoutData.preferredWidth) calculateLayoutDataStep3() calculateLayoutDataStep4(layoutData.preferredHeight) calculateOutsideGaps(layoutData.preferredWidth, layoutData.preferredHeight) } /** * Step 1 of [layoutData] calculations */ fun calculateLayoutDataStep1() { layoutData.columnsSizeCalculator.reset() val visibleCellsData = mutableListOf<LayoutCellData>() var columnsCount = 0 var rowsCount = 0 for (cell in cells) { val preferredSize: Dimension when (cell) { is ComponentCell -> { val component = cell.component if (!component.isVisible) { continue } val componentMinimumSize = component.minimumSize val componentPreferredSize = component.preferredSize preferredSize = Dimension(max(componentMinimumSize.width, componentPreferredSize.width), max(componentMinimumSize.height, componentPreferredSize.height)) } is GridCell -> { val grid = cell.content if (!grid.visible) { continue } grid.calculateLayoutDataStep1() preferredSize = Dimension(grid.layoutData.preferredWidth, 0) } } val layoutCellData: LayoutCellData with(cell.constraints) { layoutCellData = LayoutCellData(cell = cell, preferredSize = preferredSize, columnGaps = HorizontalGaps( left = columnsGaps.getOrNull(x)?.left ?: 0, right = columnsGaps.getOrNull(x + width - 1)?.right ?: 0), rowGaps = VerticalGaps( top = rowsGaps.getOrNull(y)?.top ?: 0, bottom = rowsGaps.getOrNull(y + height - 1)?.bottom ?: 0) ) columnsCount = max(columnsCount, x + width) rowsCount = max(rowsCount, y + height) } visibleCellsData.add(layoutCellData) layoutData.columnsSizeCalculator.addConstraint(cell.constraints.x, cell.constraints.width, layoutCellData.cellPaddedWidth) } layoutData.visibleCellsData = visibleCellsData layoutData.preferredWidth = layoutData.columnsSizeCalculator.calculatePreferredSize() layoutData.dimension.setSize(columnsCount, rowsCount) } /** * Step 2 of [layoutData] calculations */ fun calculateLayoutDataStep2(width: Int) { layoutData.columnsCoord = layoutData.columnsSizeCalculator.calculateCoords(width, resizableColumns) for (layoutCellData in layoutData.visibleCellsData) { val cell = layoutCellData.cell if (cell is GridCell) { cell.content.calculateLayoutDataStep2(layoutData.getFullPaddedWidth(layoutCellData)) } } } /** * Step 3 of [layoutData] calculations */ fun calculateLayoutDataStep3() { layoutData.rowsSizeCalculator.reset() layoutData.baselineData.reset() for (layoutCellData in layoutData.visibleCellsData) { val constraints = layoutCellData.cell.constraints layoutCellData.baseline = null when (val cell = layoutCellData.cell) { is ComponentCell -> { if (!isSupportedBaseline(constraints)) { continue } val componentWidth = layoutData.getPaddedWidth(layoutCellData) + constraints.visualPaddings.width val baseline: Int if (componentWidth >= 0) { baseline = cell.constraints.componentHelper?.getBaseline(componentWidth, layoutCellData.preferredSize.height) ?: cell.component.getBaseline(componentWidth, layoutCellData.preferredSize.height) // getBaseline changes preferredSize, at least for JLabel layoutCellData.preferredSize.height = cell.component.preferredSize.height } else { baseline = -1 } if (baseline >= 0) { layoutCellData.baseline = baseline layoutData.baselineData.registerBaseline(layoutCellData, baseline) } } is GridCell -> { val grid = cell.content grid.calculateLayoutDataStep3() layoutCellData.preferredSize.height = grid.layoutData.preferredHeight if (grid.layoutData.dimension.height == 1 && isSupportedBaseline(constraints)) { // Calculate baseline for grid val gridBaselines = VerticalAlign.values() .mapNotNull { var result: Pair<VerticalAlign, RowBaselineData>? = null if (it != VerticalAlign.FILL) { val baselineData = grid.layoutData.baselineData.get(it) if (baselineData != null) { result = Pair(it, baselineData) } } result } if (gridBaselines.size == 1) { val (verticalAlign, gridBaselineData) = gridBaselines[0] val baseline = calculateBaseline(layoutCellData.preferredSize.height, verticalAlign, gridBaselineData) layoutCellData.baseline = baseline layoutData.baselineData.registerBaseline(layoutCellData, baseline) } } } } } for (layoutCellData in layoutData.visibleCellsData) { val constraints = layoutCellData.cell.constraints val height = if (layoutCellData.baseline == null) layoutCellData.gapHeight - layoutCellData.cell.constraints.visualPaddings.height + layoutCellData.preferredSize.height else { val rowBaselineData = layoutData.baselineData.get(layoutCellData) rowBaselineData!!.height } // Cell height including gaps and excluding visualPaddings layoutData.rowsSizeCalculator.addConstraint(constraints.y, constraints.height, height) } layoutData.preferredHeight = layoutData.rowsSizeCalculator.calculatePreferredSize() } /** * Step 4 of [layoutData] calculations */ fun calculateLayoutDataStep4(height: Int) { layoutData.rowsCoord = layoutData.rowsSizeCalculator.calculateCoords(height, resizableRows) for (layoutCellData in layoutData.visibleCellsData) { val cell = layoutCellData.cell if (cell is GridCell) { val subGridHeight = if (cell.constraints.verticalAlign == VerticalAlign.FILL) layoutData.getFullPaddedHeight(layoutCellData) else cell.content.layoutData.preferredHeight cell.content.calculateLayoutDataStep4(subGridHeight) } } } fun calculateOutsideGaps(width: Int, height: Int) { var left = 0 var right = 0 var top = 0 var bottom = 0 for (layoutCellData in layoutData.visibleCellsData) { val cell = layoutCellData.cell // Update visualPaddings val component = (cell as? ComponentCell)?.component val layout = component?.layout as? GridLayout if (layout != null) { val preferredSizeData = layout.getPreferredSizeData(component) cell.constraints.visualPaddings = preferredSizeData.outsideGaps } val bounds = calculateBounds(layoutCellData, 0, 0) when (cell) { is ComponentCell -> { left = min(left, bounds.x) top = min(top, bounds.y) right = max(right, bounds.x + bounds.width - width) bottom = max(bottom, bounds.y + bounds.height - height) } is GridCell -> { cell.content.calculateOutsideGaps(bounds.width, bounds.height) val outsideGaps = cell.content.layoutData.outsideGaps left = min(left, bounds.x - outsideGaps.left) top = min(top, bounds.y - outsideGaps.top) right = max(right, bounds.x + bounds.width + outsideGaps.right - width) bottom = max(bottom, bounds.y + bounds.height + outsideGaps.bottom - height) } } } layoutData.outsideGaps = Gaps(top = -top, left = -left, bottom = bottom, right = right) } fun getConstraints(component: JComponent): Constraints? { for (cell in cells) { when(cell) { is ComponentCell -> { if (cell.component == component) { return cell.constraints } } is GridCell -> { val constraints = cell.content.getConstraints(component) if (constraints != null) { return constraints } } } } return null } /** * Calculate bounds for [layoutCellData] */ private fun calculateBounds(layoutCellData: LayoutCellData, offsetX: Int, offsetY: Int): Rectangle { val cell = layoutCellData.cell val constraints = cell.constraints val visualPaddings = constraints.visualPaddings val paddedWidth = layoutData.getPaddedWidth(layoutCellData) val fullPaddedWidth = layoutData.getFullPaddedWidth(layoutCellData) val x = layoutData.columnsCoord[constraints.x] + constraints.gaps.left + layoutCellData.columnGaps.left - visualPaddings.left + when (constraints.horizontalAlign) { HorizontalAlign.LEFT -> 0 HorizontalAlign.CENTER -> (fullPaddedWidth - paddedWidth) / 2 HorizontalAlign.RIGHT -> fullPaddedWidth - paddedWidth HorizontalAlign.FILL -> 0 } val fullPaddedHeight = layoutData.getFullPaddedHeight(layoutCellData) val paddedHeight = if (constraints.verticalAlign == VerticalAlign.FILL) fullPaddedHeight else min(fullPaddedHeight, layoutCellData.preferredSize.height - visualPaddings.height) val y: Int val baseline = layoutCellData.baseline if (baseline == null) { y = layoutData.rowsCoord[constraints.y] + layoutCellData.rowGaps.top + constraints.gaps.top - visualPaddings.top + when (constraints.verticalAlign) { VerticalAlign.TOP -> 0 VerticalAlign.CENTER -> (fullPaddedHeight - paddedHeight) / 2 VerticalAlign.BOTTOM -> fullPaddedHeight - paddedHeight VerticalAlign.FILL -> 0 } } else { val rowBaselineData = layoutData.baselineData.get(layoutCellData)!! val rowHeight = layoutData.getHeight(layoutCellData) y = layoutData.rowsCoord[constraints.y] + calculateBaseline(rowHeight, constraints.verticalAlign, rowBaselineData) - baseline } return Rectangle(offsetX + x, offsetY + y, paddedWidth + visualPaddings.width, paddedHeight + visualPaddings.height) } /** * Calculates baseline for specified [height] */ private fun calculateBaseline(height: Int, verticalAlign: VerticalAlign, rowBaselineData: RowBaselineData): Int { return rowBaselineData.maxAboveBaseline + when (verticalAlign) { VerticalAlign.TOP -> 0 VerticalAlign.CENTER -> (height - rowBaselineData.height) / 2 VerticalAlign.BOTTOM -> height - rowBaselineData.height VerticalAlign.FILL -> 0 } } private fun isEmpty(constraints: Constraints): Boolean { for (cell in cells) { with(cell.constraints) { if (constraints.x + constraints.width > x && x + width > constraints.x && constraints.y + constraints.height > y && y + height > constraints.y ) { return false } } } return true } } /** * Data that collected before layout/preferred size calculations */ private class LayoutData { // // Step 1 // var visibleCellsData = emptyList<LayoutCellData>() val columnsSizeCalculator = ColumnsSizeCalculator() var preferredWidth = 0 /** * Maximum indexes of occupied cells excluding hidden components */ val dimension = Dimension() // // Step 2 // var columnsCoord = emptyArray<Int>() // // Step 3 // val rowsSizeCalculator = ColumnsSizeCalculator() var preferredHeight = 0 val baselineData = BaselineData() // // Step 4 // var rowsCoord = emptyArray<Int>() // // After Step 4 (for preferred size only) // /** * Extra gaps that guarantee no visual clippings (like focus rings). * Calculated for preferred size and this value is used for enlarged container as well. * [GridLayout] takes into account [outsideGaps] for in following cases: * 1. Preferred size is increased when needed to avoid clipping * 2. Layout content can be moved a little from left/top corner to avoid clipping * 3. In parents that also use [GridLayout]: aligning by visual padding is corrected according [outsideGaps] together with insets, * so components in parent and this container are aligned together */ var outsideGaps = Gaps.EMPTY fun getPaddedWidth(layoutCellData: LayoutCellData): Int { val fullPaddedWidth = getFullPaddedWidth(layoutCellData) return if (layoutCellData.cell.constraints.horizontalAlign == HorizontalAlign.FILL) fullPaddedWidth else min(fullPaddedWidth, layoutCellData.preferredSize.width - layoutCellData.cell.constraints.visualPaddings.width) } fun getFullPaddedWidth(layoutCellData: LayoutCellData): Int { val constraints = layoutCellData.cell.constraints return columnsCoord[constraints.x + constraints.width] - columnsCoord[constraints.x] - layoutCellData.gapWidth } fun getHeight(layoutCellData: LayoutCellData): Int { val constraints = layoutCellData.cell.constraints return rowsCoord[constraints.y + constraints.height] - rowsCoord[constraints.y] } fun getFullPaddedHeight(layoutCellData: LayoutCellData): Int { return getHeight(layoutCellData) - layoutCellData.gapHeight } fun getOutsideGaps(parentInsets: Insets): Gaps { return Gaps( top = max(outsideGaps.top, parentInsets.top), left = max(outsideGaps.left, parentInsets.left), bottom = max(outsideGaps.bottom, parentInsets.bottom), right = max(outsideGaps.right, parentInsets.right), ) } } /** * For sub-grids height of [preferredSize] calculated on late steps of [LayoutData] calculations */ private data class LayoutCellData(val cell: Cell, val preferredSize: Dimension, val columnGaps: HorizontalGaps, val rowGaps: VerticalGaps) { /** * Calculated on step 3 */ var baseline: Int? = null val gapWidth: Int get() = cell.constraints.gaps.width + columnGaps.width val gapHeight: Int get() = cell.constraints.gaps.height + rowGaps.height /** * Cell width including gaps and excluding visualPaddings */ val cellPaddedWidth: Int get() = preferredSize.width + gapWidth - cell.constraints.visualPaddings.width } private sealed class Cell(val constraints: Constraints) { abstract val visible: Boolean } private class ComponentCell(constraints: Constraints, val component: JComponent) : Cell(constraints) { override val visible: Boolean get() = component.isVisible } private class GridCell(constraints: Constraints, val content: GridImpl) : Cell(constraints) { override val visible: Boolean get() = content.visible } /** * Contains baseline data for rows, see [Constraints.baselineAlign] */ private class BaselineData { private val rowBaselineData = mutableMapOf<Int, MutableMap<VerticalAlign, RowBaselineData>>() fun reset() { rowBaselineData.clear() } fun registerBaseline(layoutCellData: LayoutCellData, baseline: Int) { val constraints = layoutCellData.cell.constraints checkTrue(isSupportedBaseline(constraints)) val rowBaselineData = getOrCreate(layoutCellData) rowBaselineData.maxAboveBaseline = max(rowBaselineData.maxAboveBaseline, baseline + layoutCellData.rowGaps.top + constraints.gaps.top - constraints.visualPaddings.top) rowBaselineData.maxBelowBaseline = max(rowBaselineData.maxBelowBaseline, layoutCellData.preferredSize.height - baseline + layoutCellData.rowGaps.bottom + constraints.gaps.bottom - constraints.visualPaddings.bottom) } /** * Returns data for single available row */ fun get(verticalAlign: VerticalAlign): RowBaselineData? { checkTrue(rowBaselineData.size <= 1) return rowBaselineData.firstNotNullOfOrNull { it.value }?.get(verticalAlign) } fun get(layoutCellData: LayoutCellData): RowBaselineData? { val constraints = layoutCellData.cell.constraints return rowBaselineData[constraints.y]?.get(constraints.verticalAlign) } private fun getOrCreate(layoutCellData: LayoutCellData): RowBaselineData { val constraints = layoutCellData.cell.constraints val mapByAlign = rowBaselineData.getOrPut(constraints.y) { EnumMap(VerticalAlign::class.java) } return mapByAlign.getOrPut(constraints.verticalAlign) { RowBaselineData() } } } /** * Max sizes for a row which include all gaps and exclude paddings */ private data class RowBaselineData(var maxAboveBaseline: Int = 0, var maxBelowBaseline: Int = 0) { val height: Int get() = maxAboveBaseline + maxBelowBaseline } private fun isSupportedBaseline(constraints: Constraints): Boolean { return constraints.baselineAlign && constraints.verticalAlign != VerticalAlign.FILL && constraints.height == 1 } @ApiStatus.Internal internal data class PreferredSizeData(val preferredSize: Dimension, val outsideGaps: Gaps)
apache-2.0
331e624978a201eae38479b1f483a04f
33.326014
158
0.681512
4.96846
false
false
false
false
Flank/flank
tool/execution/parallel/src/test/kotlin/flank/exection/parallel/benchmark/Execute.kt
1
995
package flank.exection.parallel.benchmark import flank.exection.parallel.Parallel import flank.exection.parallel.Tasks import flank.exection.parallel.from import flank.exection.parallel.internal.args import flank.exection.parallel.invoke import flank.exection.parallel.using import kotlinx.coroutines.runBlocking import kotlin.system.measureTimeMillis fun main() { data class Type(val id: Int) : Parallel.Type<Any> val types = (0..1000).map { Type(it) } val used = mutableSetOf<Parallel.Type<Any>>() val execute: Tasks = types.map { returns -> used += returns val args = (types - used) .shuffled() .run { take((0..size / 10).random()) } .toSet() returns from args using {} }.toSet() val edges = execute.sumOf { task -> task.args.size } println("edges: $edges") println() runBlocking { repeat(100) { measureTimeMillis { execute.invoke() }.let(::println) } } }
apache-2.0
573d8e20a6e95e65bb2099fc86591048
25.184211
65
0.645226
4.09465
false
false
false
false
jotomo/AndroidAPS
core/src/main/java/info/nightscout/androidaps/utils/protection/BiometricCheck.kt
1
3975
package info.nightscout.androidaps.utils.protection import androidx.biometric.BiometricConstants import androidx.biometric.BiometricPrompt import androidx.fragment.app.FragmentActivity import info.nightscout.androidaps.core.R import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.extensions.runOnUiThread import java.util.concurrent.Executors object BiometricCheck { fun biometricPrompt(activity: FragmentActivity, title: Int, ok: Runnable?, cancel: Runnable? = null, fail: Runnable? = null, passwordCheck: PasswordCheck) { val executor = Executors.newSingleThreadExecutor() val biometricPrompt = BiometricPrompt(activity, executor, object : BiometricPrompt.AuthenticationCallback() { override fun onAuthenticationError(errorCode: Int, errString: CharSequence) { super.onAuthenticationError(errorCode, errString) when (errorCode) { BiometricConstants.ERROR_UNABLE_TO_PROCESS, BiometricConstants.ERROR_TIMEOUT, BiometricConstants.ERROR_CANCELED, BiometricConstants.ERROR_LOCKOUT, BiometricConstants.ERROR_VENDOR, BiometricConstants.ERROR_LOCKOUT_PERMANENT, BiometricConstants.ERROR_USER_CANCELED -> { ToastUtils.showToastInUiThread(activity.baseContext, errString.toString()) // fallback to master password runOnUiThread(Runnable { passwordCheck.queryPassword(activity, R.string.master_password, R.string.key_master_password, { ok?.run() }, { cancel?.run() }, { fail?.run() }) }) } BiometricConstants.ERROR_NEGATIVE_BUTTON -> cancel?.run() BiometricConstants.ERROR_NO_DEVICE_CREDENTIAL -> { ToastUtils.showToastInUiThread(activity.baseContext, errString.toString()) // no pin set // fallback to master password runOnUiThread(Runnable { passwordCheck.queryPassword(activity, R.string.master_password, R.string.key_master_password, { ok?.run() }, { cancel?.run() }, { fail?.run() }) }) } BiometricConstants.ERROR_NO_SPACE, BiometricConstants.ERROR_HW_UNAVAILABLE, BiometricConstants.ERROR_HW_NOT_PRESENT, BiometricConstants.ERROR_NO_BIOMETRICS -> runOnUiThread(Runnable { passwordCheck.queryPassword(activity, R.string.master_password, R.string.key_master_password, { ok?.run() }, { cancel?.run() }, { fail?.run() }) }) } } override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) { super.onAuthenticationSucceeded(result) // Called when a biometric is recognized. ok?.run() } override fun onAuthenticationFailed() { super.onAuthenticationFailed() // Called when a biometric is valid but not recognized. fail?.run() } }) val promptInfo = BiometricPrompt.PromptInfo.Builder() .setTitle(activity.getString(title)) .setDescription(activity.getString(R.string.biometric_title)) .setNegativeButtonText(activity.getString(R.string.cancel)) // not possible with setDeviceCredentialAllowed // .setDeviceCredentialAllowed(true) // setDeviceCredentialAllowed creates new activity when PIN is requested, activity.fragmentManager crash afterwards .build() biometricPrompt.authenticate(promptInfo) } }
agpl-3.0
35f4b188f5a0b523b8c2f82af0669756
49.974359
172
0.601006
5.727666
false
false
false
false
romannurik/muzei
wearable/src/main/java/com/google/android/apps/muzei/datalayer/DataLayerArtProvider.kt
1
2521
/* * Copyright 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.muzei.datalayer import android.app.PendingIntent import android.content.Context import android.content.Intent import androidx.core.app.RemoteActionCompat import androidx.core.graphics.drawable.IconCompat import com.google.android.apps.muzei.api.provider.Artwork import com.google.android.apps.muzei.api.provider.MuzeiArtProvider import net.nurik.roman.muzei.R import java.io.File import java.io.FileInputStream import java.io.FileNotFoundException import java.io.InputStream /** * Provider handling art from a connected phone */ class DataLayerArtProvider : MuzeiArtProvider() { companion object { fun getAssetFile(context: Context): File = File(context.filesDir, "data_layer") } override fun onLoadRequested(initial: Boolean) { val context = context ?: return if (initial) { DataLayerLoadWorker.enqueueLoad(context) } } override fun getCommandActions(artwork: Artwork): List<RemoteActionCompat> { val context = context ?: return super.getCommandActions(artwork) return listOf(createOpenOnPhoneAction(context)) } private fun createOpenOnPhoneAction(context: Context): RemoteActionCompat { val title = context.getString(R.string.common_open_on_phone) val intent = Intent(context, OpenOnPhoneReceiver::class.java) return RemoteActionCompat( IconCompat.createWithResource(context, R.drawable.open_on_phone_button), title, title, PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)) } @Throws(FileNotFoundException::class) override fun openFile(artwork: Artwork): InputStream { val context = context ?: throw FileNotFoundException() return FileInputStream(getAssetFile(context)) } }
apache-2.0
99a3e58fa66d89965a5a5e904769bedd
35.028571
88
0.718366
4.600365
false
false
false
false
intellij-purescript/intellij-purescript
src/main/kotlin/org/purescript/psi/imports/PSImportedItem.kt
1
5730
package org.purescript.psi.imports import com.intellij.lang.ASTNode import com.intellij.psi.PsiReference import com.intellij.psi.util.PsiTreeUtil import org.purescript.psi.PSPsiElement import org.purescript.psi.data.PSDataDeclaration import org.purescript.psi.name.PSIdentifier import org.purescript.psi.name.PSProperName import org.purescript.psi.name.PSSymbol import org.purescript.psi.newtype.PSNewTypeDeclaration /** * Any element that can occur in a [PSImportList] */ sealed class PSImportedItem(node: ASTNode) : PSPsiElement(node), Comparable<PSImportedItem> { abstract override fun getName(): String internal val importDeclaration: PSImportDeclaration? get() = PsiTreeUtil.getParentOfType(this, PSImportDeclaration::class.java) /** * Compares this [PSImportedItem] with the specified [PSImportedItem] for order. * Returns zero if this [PSImportedItem] is equal to the specified * [other] [PSImportedItem], a negative number if it's less than [other], or a * positive number if it's greater than [other]. * * Different classes of [PSImportedItem] are ordered accordingly, in ascending order: * - [PSImportedClass] * - [PSImportedKind] * - [PSImportedType] * - [PSImportedData] * - [PSImportedValue] * - [PSImportedOperator] * * If the operands are of the same class, they are ordered according to their [getName]. */ override fun compareTo(other: PSImportedItem): Int = compareValuesBy( this, other, { when (it) { is PSImportedClass -> 0 is PSImportedKind -> 1 is PSImportedType -> 2 is PSImportedData -> 3 is PSImportedValue -> 4 is PSImportedOperator -> 5 } }, { it.name } ) } /** * An imported class declaration, e.g. * ``` * class Newtype * ``` * in * ``` * import Data.Newtype (class Newtype) * ``` */ class PSImportedClass(node: ASTNode) : PSImportedItem(node) { internal val properName: PSProperName get() = findNotNullChildByClass(PSProperName::class.java) override fun getName(): String = properName.name override fun getReference(): ImportedClassReference = ImportedClassReference(this) } /** * An imported data, type, or newtype declaration, e.g. * ``` * Maybe(..) * ``` * in * ``` * import Data.Maybe (Maybe(..)) * ``` */ class PSImportedData(node: ASTNode) : PSImportedItem(node) { /** * @return the [PSProperName] identifying this element */ internal val properName: PSProperName get() = findNotNullChildByClass(PSProperName::class.java) /** * @return the [PSImportedDataMemberList] containing the imported members, * if present */ internal val importedDataMemberList: PSImportedDataMemberList? get() = findChildByClass(PSImportedDataMemberList::class.java) /** * @return true if this element implicitly imports all members using * the (..) syntax, otherwise false */ val importsAll: Boolean get() = importedDataMemberList?.doubleDot != null /** * @return the data members imported explicitly using the * Type(A, B, C) syntax */ val importedDataMembers: Array<PSImportedDataMember> get() = importedDataMemberList?.dataMembers ?: emptyArray() /** * @return the [PSNewTypeDeclaration] that this element references to, * if it exists */ val newTypeDeclaration: PSNewTypeDeclaration? get() = reference.resolve() as? PSNewTypeDeclaration /** * @return the [PSDataDeclaration] that this element references to, * if it exists */ val dataDeclaration: PSDataDeclaration? get() = reference.resolve() as? PSDataDeclaration override fun getName(): String = properName.name override fun getReference(): ImportedDataReference = ImportedDataReference(this) } /** * An imported kind declaration, e.g. * ``` * kind Boolean * ``` * in * ``` * import Type.Data.Boolean (kind Boolean) * ``` */ class PSImportedKind(node: ASTNode) : PSImportedItem(node) { private val properName: PSProperName get() = findNotNullChildByClass(PSProperName::class.java) override fun getName(): String = properName.name } /** * An imported infix operator declaration, e.g. * ``` * (==) * ``` * in * ``` * import Data.Eq ((==)) * ``` */ class PSImportedOperator(node: ASTNode) : PSImportedItem(node) { val symbol: PSSymbol get() = findNotNullChildByClass(PSSymbol::class.java) override fun getName(): String = symbol.name override fun getReference(): PsiReference { return ImportedOperatorReference(this) } } /** * An imported infix type operator declaration, e.g. * ``` * type (~>) * ``` * in * ``` * import Prelude (type (~>)) * ``` */ class PSImportedType(node: ASTNode) : PSImportedItem(node) { private val identifier: PSIdentifier get() = findNotNullChildByClass(PSIdentifier::class.java) override fun getName(): String = identifier.name } /** * An imported value or class member declaration, e.g. * ``` * show * ``` * in * ``` * import Prelude (show) * ``` */ class PSImportedValue(node: ASTNode) : PSImportedItem(node) { val identifier: PSIdentifier get() = findNotNullChildByClass(PSIdentifier::class.java) override fun getName(): String = identifier.name override fun getReference(): ImportedValueReference = ImportedValueReference(this) }
bsd-3-clause
6b147c93eb4946ba5e4bca9ab36c9ab4
25.901408
93
0.639092
4.480063
false
false
false
false
siosio/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/internal/javaInternalUastUtils.kt
1
3685
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast.java import com.intellij.psi.JavaTokenType import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiElement import com.intellij.psi.PsiModifierListOwner import com.intellij.psi.impl.source.tree.CompositeElement import com.intellij.psi.tree.IElementType import org.jetbrains.uast.UDeclaration import org.jetbrains.uast.UElement import org.jetbrains.uast.UastBinaryOperator internal fun IElementType.getOperatorType() = when (this) { JavaTokenType.EQ -> UastBinaryOperator.ASSIGN JavaTokenType.PLUS -> UastBinaryOperator.PLUS JavaTokenType.MINUS -> UastBinaryOperator.MINUS JavaTokenType.ASTERISK -> UastBinaryOperator.MULTIPLY JavaTokenType.DIV -> UastBinaryOperator.DIV JavaTokenType.PERC -> UastBinaryOperator.MOD JavaTokenType.ANDAND -> UastBinaryOperator.LOGICAL_AND JavaTokenType.OROR -> UastBinaryOperator.LOGICAL_OR JavaTokenType.OR -> UastBinaryOperator.BITWISE_OR JavaTokenType.AND -> UastBinaryOperator.BITWISE_AND JavaTokenType.XOR -> UastBinaryOperator.BITWISE_XOR JavaTokenType.EQEQ -> UastBinaryOperator.IDENTITY_EQUALS JavaTokenType.NE -> UastBinaryOperator.IDENTITY_NOT_EQUALS JavaTokenType.GT -> UastBinaryOperator.GREATER JavaTokenType.GE -> UastBinaryOperator.GREATER_OR_EQUALS JavaTokenType.LT -> UastBinaryOperator.LESS JavaTokenType.LE -> UastBinaryOperator.LESS_OR_EQUALS JavaTokenType.LTLT -> UastBinaryOperator.SHIFT_LEFT JavaTokenType.GTGT -> UastBinaryOperator.SHIFT_RIGHT JavaTokenType.GTGTGT -> UastBinaryOperator.UNSIGNED_SHIFT_RIGHT JavaTokenType.PLUSEQ -> UastBinaryOperator.PLUS_ASSIGN JavaTokenType.MINUSEQ -> UastBinaryOperator.MINUS_ASSIGN JavaTokenType.ASTERISKEQ -> UastBinaryOperator.MULTIPLY_ASSIGN JavaTokenType.DIVEQ -> UastBinaryOperator.DIVIDE_ASSIGN JavaTokenType.PERCEQ -> UastBinaryOperator.REMAINDER_ASSIGN JavaTokenType.ANDEQ -> UastBinaryOperator.AND_ASSIGN JavaTokenType.XOREQ -> UastBinaryOperator.XOR_ASSIGN JavaTokenType.OREQ -> UastBinaryOperator.OR_ASSIGN JavaTokenType.LTLTEQ -> UastBinaryOperator.SHIFT_LEFT_ASSIGN JavaTokenType.GTGTEQ -> UastBinaryOperator.SHIFT_RIGHT_ASSIGN JavaTokenType.GTGTGTEQ -> UastBinaryOperator.UNSIGNED_SHIFT_RIGHT_ASSIGN else -> UastBinaryOperator.OTHER } internal fun <T> singletonListOrEmpty(element: T?) = if (element != null) listOf(element) else emptyList<T>() @Suppress("NOTHING_TO_INLINE") internal inline fun String?.orAnonymous(kind: String = ""): String { return this ?: ("<anonymous" + (if (kind.isNotBlank()) " $kind" else "") + ">") } internal fun <T> lz(initializer: () -> T) = lazy(LazyThreadSafetyMode.SYNCHRONIZED, initializer) val PsiModifierListOwner.annotations: Array<PsiAnnotation> get() = modifierList?.annotations ?: emptyArray() internal inline fun <reified T : UDeclaration, reified P : PsiElement> unwrap(element: P): P { val unwrapped = if (element is T) element.javaPsi else element assert(unwrapped !is UElement) return unwrapped as P } internal fun PsiElement.getChildByRole(role: Int) = (this as? CompositeElement)?.findChildByRoleAsPsiElement(role)
apache-2.0
515b225aaf043af2c19caa925e57114e
44.506173
114
0.790231
4.589041
false
false
false
false
siosio/intellij-community
plugins/grazie/src/main/kotlin/com/intellij/grazie/GraziePlugin.kt
1
1009
// 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 import com.intellij.ide.plugins.IdeaPluginDescriptor import com.intellij.ide.plugins.PluginManagerCore import com.intellij.openapi.extensions.PluginId import java.nio.file.Path internal object GraziePlugin { const val id = "tanvd.grazi" object LanguageTool { const val version = "5.4" const val url = "https://resources.jetbrains.com/grazie/model/language-tool" } private val descriptor: IdeaPluginDescriptor get() = PluginManagerCore.getPlugin(PluginId.getId(id))!! val group: String get() = GrazieBundle.message("grazie.group.name") val name: String get() = GrazieBundle.message("grazie.name") val isBundled: Boolean get() = descriptor.isBundled val classLoader: ClassLoader get() = descriptor.pluginClassLoader val libFolder: Path get() = descriptor.pluginPath.resolve("lib") }
apache-2.0
a2622c61d4445dfe7253c27a87318bcf
28.676471
140
0.745292
4.152263
false
false
false
false
jwren/intellij-community
python/src/com/jetbrains/python/console/actions/ShowCommandQueueAction.kt
3
2020
// 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.jetbrains.python.console.actions import com.intellij.execution.runners.ExecutionUtil import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.ToggleAction import com.intellij.openapi.components.service import com.intellij.openapi.project.DumbAware import com.jetbrains.python.PyBundle import com.jetbrains.python.console.PydevConsoleRunner.CONSOLE_COMMUNICATION_KEY import com.jetbrains.python.console.PythonConsoleView import icons.PythonIcons import javax.swing.Icon /*** * action for showing the CommandQueue window */ class ShowCommandQueueAction(private val consoleView: PythonConsoleView) : ToggleAction(PyBundle.message("python.console.command.queue.show.action.text"), PyBundle.message("python.console.command.queue.show.action.description"), emptyQueueIcon), DumbAware { companion object { private val emptyQueueIcon = PythonIcons.Python.CommandQueue private val notEmptyQueueIcon = ExecutionUtil.getLiveIndicator(emptyQueueIcon) @JvmStatic fun isCommandQueueIcon(icon: Icon): Boolean = icon == emptyQueueIcon || icon == notEmptyQueueIcon } override fun update(e: AnActionEvent) { super.update(e) val communication = consoleView.file.getCopyableUserData(CONSOLE_COMMUNICATION_KEY) communication?.let { if (service<CommandQueueForPythonConsoleService>().isEmpty(communication)) { e.presentation.icon = emptyQueueIcon } else { e.presentation.icon = notEmptyQueueIcon } } } override fun isSelected(e: AnActionEvent): Boolean { return consoleView.isShowQueue } override fun setSelected(e: AnActionEvent, state: Boolean) { consoleView.isShowQueue = state if (state) { consoleView.showQueue() } else { consoleView.restoreQueueWindow(false) } } }
apache-2.0
1a20aef881f9f3fcc433d7215add6be0
35.745455
158
0.756931
4.633028
false
false
false
false
androidx/androidx
wear/watchface/watchface/samples/src/main/java/androidx/wear/watchface/samples/ExampleCanvasDigitalWatchFaceService.kt
3
55679
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.watchface.samples import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.animation.TimeInterpolator import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.PointF import android.graphics.Rect import android.graphics.RectF import android.graphics.Typeface import android.graphics.drawable.Icon import android.text.format.DateFormat import android.util.FloatProperty import android.util.SparseArray import android.view.SurfaceHolder import android.view.animation.AnimationUtils import android.view.animation.PathInterpolator import androidx.annotation.ColorInt import androidx.annotation.RequiresApi import androidx.wear.watchface.CanvasComplicationFactory import androidx.wear.watchface.CanvasType import androidx.wear.watchface.ComplicationSlot import androidx.wear.watchface.ComplicationSlotsManager import androidx.wear.watchface.DrawMode import androidx.wear.watchface.Renderer import androidx.wear.watchface.WatchFace import androidx.wear.watchface.WatchFaceColors import androidx.wear.watchface.WatchFaceExperimental import androidx.wear.watchface.WatchFaceService import androidx.wear.watchface.WatchFaceType import androidx.wear.watchface.WatchState import androidx.wear.watchface.complications.ComplicationSlotBounds import androidx.wear.watchface.complications.DefaultComplicationDataSourcePolicy import androidx.wear.watchface.complications.SystemDataSources import androidx.wear.watchface.complications.data.ComplicationType import androidx.wear.watchface.complications.permission.dialogs.sample.ComplicationDeniedActivity import androidx.wear.watchface.complications.permission.dialogs.sample.ComplicationRationalActivity import androidx.wear.watchface.complications.rendering.CanvasComplicationDrawable import androidx.wear.watchface.style.CurrentUserStyleRepository import androidx.wear.watchface.style.UserStyleSchema import androidx.wear.watchface.style.UserStyleSetting import androidx.wear.watchface.style.UserStyleSetting.Option import androidx.wear.watchface.style.WatchFaceLayer import java.time.ZonedDateTime import kotlin.math.max import kotlin.math.min import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.android.asCoroutineDispatcher import kotlinx.coroutines.launch /** A simple example canvas based digital watch face. */ class ExampleCanvasDigitalWatchFaceService : WatchFaceService() { // Lazy because the context isn't initialized til later. private val watchFaceStyle by lazy { WatchFaceColorStyle.create(this, RED_STYLE) } private val colorStyleSetting by lazy { UserStyleSetting.ListUserStyleSetting( UserStyleSetting.Id(COLOR_STYLE_SETTING), resources, R.string.colors_style_setting, R.string.colors_style_setting_description, icon = null, options = listOf( UserStyleSetting.ListUserStyleSetting.ListOption( Option.Id(RED_STYLE), resources, R.string.colors_style_red, R.string.colors_style_red_screen_reader, Icon.createWithResource(this, R.drawable.red_style) ), UserStyleSetting.ListUserStyleSetting.ListOption( Option.Id(GREEN_STYLE), resources, R.string.colors_style_green, R.string.colors_style_green_screen_reader, Icon.createWithResource(this, R.drawable.green_style) ), UserStyleSetting.ListUserStyleSetting.ListOption( Option.Id(BLUE_STYLE), resources, R.string.colors_style_blue, R.string.colors_style_blue_screen_reader, Icon.createWithResource(this, R.drawable.blue_style) ) ), listOf( WatchFaceLayer.BASE, WatchFaceLayer.COMPLICATIONS, WatchFaceLayer.COMPLICATIONS_OVERLAY ) ) } private val canvasComplicationFactory = CanvasComplicationFactory { watchState, listener -> CanvasComplicationDrawable( watchFaceStyle.getDrawable(this@ExampleCanvasDigitalWatchFaceService)!!, watchState, listener ) } private val leftComplication = ComplicationSlot.createRoundRectComplicationSlotBuilder( ComplicationID.LEFT.ordinal, canvasComplicationFactory, listOf( ComplicationType.RANGED_VALUE, ComplicationType.GOAL_PROGRESS, ComplicationType.WEIGHTED_ELEMENTS, ComplicationType.SHORT_TEXT, ComplicationType.MONOCHROMATIC_IMAGE, ComplicationType.SMALL_IMAGE ), DefaultComplicationDataSourcePolicy( SystemDataSources.DATA_SOURCE_WATCH_BATTERY, ComplicationType.SHORT_TEXT ), ComplicationSlotBounds( createBoundsRect( LEFT_CIRCLE_COMPLICATION_CENTER_FRACTION, CIRCLE_COMPLICATION_DIAMETER_FRACTION ) ) ).setNameResourceId(R.string.left_complication_screen_name) .setScreenReaderNameResourceId(R.string.left_complication_screen_reader_name).build() private val rightComplication = ComplicationSlot.createRoundRectComplicationSlotBuilder( ComplicationID.RIGHT.ordinal, canvasComplicationFactory, listOf( ComplicationType.RANGED_VALUE, ComplicationType.GOAL_PROGRESS, ComplicationType.WEIGHTED_ELEMENTS, ComplicationType.SHORT_TEXT, ComplicationType.MONOCHROMATIC_IMAGE, ComplicationType.SMALL_IMAGE ), DefaultComplicationDataSourcePolicy( SystemDataSources.DATA_SOURCE_DATE, ComplicationType.SHORT_TEXT ), ComplicationSlotBounds( createBoundsRect( RIGHT_CIRCLE_COMPLICATION_CENTER_FRACTION, CIRCLE_COMPLICATION_DIAMETER_FRACTION ) ) ).setNameResourceId(R.string.right_complication_screen_name) .setScreenReaderNameResourceId(R.string.right_complication_screen_reader_name).build() private val upperAndLowerComplicationTypes = listOf( ComplicationType.LONG_TEXT, ComplicationType.RANGED_VALUE, ComplicationType.GOAL_PROGRESS, ComplicationType.WEIGHTED_ELEMENTS, ComplicationType.SHORT_TEXT, ComplicationType.MONOCHROMATIC_IMAGE, ComplicationType.SMALL_IMAGE ) // The upper and lower complicationSlots change shape depending on the complication's type. private val upperComplication = ComplicationSlot.createRoundRectComplicationSlotBuilder( ComplicationID.UPPER.ordinal, canvasComplicationFactory, upperAndLowerComplicationTypes, DefaultComplicationDataSourcePolicy( SystemDataSources.DATA_SOURCE_WORLD_CLOCK, ComplicationType.LONG_TEXT ), ComplicationSlotBounds( ComplicationType.values().associateWith { if (it == ComplicationType.LONG_TEXT || it == ComplicationType.NO_DATA) { createBoundsRect( UPPER_ROUND_RECT_COMPLICATION_CENTER_FRACTION, ROUND_RECT_COMPLICATION_SIZE_FRACTION ) } else { createBoundsRect( UPPER_CIRCLE_COMPLICATION_CENTER_FRACTION, CIRCLE_COMPLICATION_DIAMETER_FRACTION ) } }, ComplicationType.values().associateWith { RectF() } ) ).setNameResourceId(R.string.upper_complication_screen_name) .setScreenReaderNameResourceId(R.string.upper_complication_screen_reader_name).build() private val lowerComplication = ComplicationSlot.createRoundRectComplicationSlotBuilder( ComplicationID.LOWER.ordinal, canvasComplicationFactory, upperAndLowerComplicationTypes, DefaultComplicationDataSourcePolicy( SystemDataSources.DATA_SOURCE_NEXT_EVENT, ComplicationType.LONG_TEXT ), ComplicationSlotBounds( ComplicationType.values().associateWith { if (it == ComplicationType.LONG_TEXT || it == ComplicationType.NO_DATA) { createBoundsRect( LOWER_ROUND_RECT_COMPLICATION_CENTER_FRACTION, ROUND_RECT_COMPLICATION_SIZE_FRACTION ) } else { createBoundsRect( LOWER_CIRCLE_COMPLICATION_CENTER_FRACTION, CIRCLE_COMPLICATION_DIAMETER_FRACTION ) } }, ComplicationType.values().associateWith { RectF() } ) ).setNameResourceId(R.string.lower_complication_screen_name) .setScreenReaderNameResourceId(R.string.lower_complication_screen_reader_name).build() private val backgroundComplication = ComplicationSlot.createBackgroundComplicationSlotBuilder( ComplicationID.BACKGROUND.ordinal, canvasComplicationFactory, listOf(ComplicationType.PHOTO_IMAGE), DefaultComplicationDataSourcePolicy() ).setNameResourceId(R.string.background_complication_screen_name) .setScreenReaderNameResourceId(R.string.background_complication_screen_reader_name).build() override fun createUserStyleSchema() = UserStyleSchema(listOf(colorStyleSetting)) override fun createComplicationSlotsManager( currentUserStyleRepository: CurrentUserStyleRepository ) = ComplicationSlotsManager( listOf( leftComplication, rightComplication, upperComplication, lowerComplication, backgroundComplication ), currentUserStyleRepository ) override suspend fun createWatchFace( surfaceHolder: SurfaceHolder, watchState: WatchState, complicationSlotsManager: ComplicationSlotsManager, currentUserStyleRepository: CurrentUserStyleRepository ): WatchFace { val renderer = ExampleDigitalWatchCanvasRenderer( surfaceHolder, this, watchFaceStyle, currentUserStyleRepository, watchState, colorStyleSetting, complicationSlotsManager ) // createWatchFace is called on a worker thread but the observers should be called from the // UiThread. val uiScope = CoroutineScope(getUiThreadHandler().asCoroutineDispatcher()) uiScope.launch { upperComplication.complicationData.collect { // Force bounds recalculation, because this can affect the size of the central time // display. renderer.oldBounds.set(0, 0, 0, 0) } } uiScope.launch { lowerComplication.complicationData.collect() { // Force bounds recalculation, because this can affect the size of the central time // display. renderer.oldBounds.set(0, 0, 0, 0) } } return WatchFace(WatchFaceType.DIGITAL, renderer) .setComplicationDeniedDialogIntent( Intent(this, ComplicationDeniedActivity::class.java) ) .setComplicationRationaleDialogIntent( Intent(this, ComplicationRationalActivity::class.java) ) } @OptIn(WatchFaceExperimental::class) @Suppress("Deprecation") @RequiresApi(27) private class ExampleDigitalWatchCanvasRenderer( surfaceHolder: SurfaceHolder, private val context: Context, private var watchFaceColorStyle: WatchFaceColorStyle, currentUserStyleRepository: CurrentUserStyleRepository, watchState: WatchState, private val colorStyleSetting: UserStyleSetting.ListUserStyleSetting, private val complicationSlotsManager: ComplicationSlotsManager ) : Renderer.CanvasRenderer( surfaceHolder, currentUserStyleRepository, watchState, CanvasType.HARDWARE, INTERACTIVE_UPDATE_RATE_MS, clearWithBackgroundTintBeforeRenderingHighlightLayer = true ) { internal var oldBounds = Rect(0, 0, 0, 0) private fun getBaseDigitPaint() = Paint().apply { typeface = Typeface.create(DIGITAL_TYPE_FACE, Typeface.NORMAL) isAntiAlias = true } private val digitTextHoursPaint = getBaseDigitPaint() private val digitTextMinutesPaint = getBaseDigitPaint() private val digitTextSecondsPaint = getBaseDigitPaint() // Used for drawing the cached digits to the watchface. private val digitBitmapPaint = Paint().apply { isFilterBitmap = true } // Used for computing text sizes, not directly used for rendering. private var digitTextPaint = getBaseDigitPaint() private val clockBounds = Rect() private val digitBounds = Rect() private var digitTextSize = 0f private var smallDigitTextSize = 0f private var digitHeight = 0 private var digitWidth = 0 private var smallDigitHeight = 0 private var smallDigitWidth = 0 private var digitVerticalPadding = 0 private var gapWidth = 0f private val currentDigitStrings = DigitStrings() private val nextDigitStrings = DigitStrings() private val digitDrawProperties = DigitDrawProperties() private var drawProperties = DrawProperties() private var prevDrawMode = DrawMode.INTERACTIVE // Animation played when exiting ambient mode. private val ambientExitAnimator = AnimatorSet().apply { val linearOutSlow = AnimationUtils.loadInterpolator( context, android.R.interpolator.linear_out_slow_in ) playTogether( ObjectAnimator.ofFloat( drawProperties, DrawProperties.TIME_SCALE, 1.0f ).apply { duration = AMBIENT_TRANSITION_MS interpolator = linearOutSlow setAutoCancel(true) }, ObjectAnimator.ofFloat( drawProperties, DrawProperties.SECONDS_SCALE, 1.0f ).apply { duration = AMBIENT_TRANSITION_MS interpolator = linearOutSlow setAutoCancel(true) } ) } // Animation played when entering ambient mode. private val ambientEnterAnimator = AnimatorSet().apply { val fastOutLinearIn = AnimationUtils.loadInterpolator( context, android.R.interpolator.fast_out_linear_in ) playTogether( ObjectAnimator.ofFloat( drawProperties, DrawProperties.TIME_SCALE, 1.0f ).apply { duration = AMBIENT_TRANSITION_MS interpolator = fastOutLinearIn setAutoCancel(true) }, ObjectAnimator.ofFloat( drawProperties, DrawProperties.SECONDS_SCALE, 0.0f ).apply { duration = AMBIENT_TRANSITION_MS interpolator = fastOutLinearIn setAutoCancel(true) } ) } // A mapping from digit type to cached bitmap. One bitmap is cached per digit type, and the // digit shown in the cached image is stored in [currentCachedDigits]. private val digitBitmapCache = SparseArray<Bitmap>() // A mapping from digit type to the digit that the cached bitmap // (stored in [digitBitmapCache]) displays. private val currentCachedDigits = SparseArray<String>() private val coroutineScope = CoroutineScope(Dispatchers.Main.immediate) init { // Listen for style changes. coroutineScope.launch { currentUserStyleRepository.userStyle.collect { userStyle -> watchFaceColorStyle = WatchFaceColorStyle.create( context, userStyle[colorStyleSetting]!!.toString() ) watchfaceColors = WatchFaceColors( Color.valueOf(watchFaceColorStyle.activeStyle.primaryColor), Color.valueOf(watchFaceColorStyle.activeStyle.secondaryColor), Color.valueOf(Color.DKGRAY) ) // Apply the userStyle to the complicationSlots. ComplicationDrawables for each // of the styles are defined in XML so we need to replace the complication's // drawables. for ((_, complication) in complicationSlotsManager.complicationSlots) { (complication.renderer as CanvasComplicationDrawable).drawable = watchFaceColorStyle.getDrawable(context)!! } clearDigitBitmapCache() } } // Listen for ambient state changes. coroutineScope.launch { watchState.isAmbient.collect { if (it!!) { ambientEnterAnimator.start() } else { ambientExitAnimator.start() } // Trigger recomputation of bounds. oldBounds.set(0, 0, 0, 0) val antiAlias = !(it && watchState.hasLowBitAmbient) digitTextHoursPaint.isAntiAlias = antiAlias digitTextMinutesPaint.isAntiAlias = antiAlias digitTextSecondsPaint.isAntiAlias = antiAlias } } } override fun shouldAnimate(): Boolean { // Make sure we keep animating while ambientEnterAnimator is running. return ambientEnterAnimator.isRunning || super.shouldAnimate() } private fun applyColorStyleAndDrawMode(drawMode: DrawMode) { digitTextHoursPaint.color = when (drawMode) { DrawMode.INTERACTIVE -> watchFaceColorStyle.activeStyle.primaryColor DrawMode.LOW_BATTERY_INTERACTIVE -> multiplyColor(watchFaceColorStyle.activeStyle.primaryColor, 0.6f) DrawMode.MUTE -> multiplyColor(watchFaceColorStyle.activeStyle.primaryColor, 0.8f) DrawMode.AMBIENT -> watchFaceColorStyle.ambientStyle.primaryColor } digitTextMinutesPaint.color = when (drawMode) { DrawMode.INTERACTIVE -> watchFaceColorStyle.activeStyle.primaryColor DrawMode.LOW_BATTERY_INTERACTIVE -> multiplyColor(watchFaceColorStyle.activeStyle.primaryColor, 0.6f) DrawMode.MUTE -> multiplyColor(watchFaceColorStyle.activeStyle.primaryColor, 0.8f) DrawMode.AMBIENT -> watchFaceColorStyle.ambientStyle.primaryColor } digitTextSecondsPaint.color = when (drawMode) { DrawMode.INTERACTIVE -> watchFaceColorStyle.activeStyle.secondaryColor DrawMode.LOW_BATTERY_INTERACTIVE -> multiplyColor(watchFaceColorStyle.activeStyle.secondaryColor, 0.6f) DrawMode.MUTE -> multiplyColor(watchFaceColorStyle.activeStyle.secondaryColor, 0.8f) DrawMode.AMBIENT -> watchFaceColorStyle.ambientStyle.secondaryColor } if (prevDrawMode != drawMode) { prevDrawMode = drawMode clearDigitBitmapCache() } } override fun render(canvas: Canvas, bounds: Rect, zonedDateTime: ZonedDateTime) { recalculateBoundsIfChanged(bounds, zonedDateTime) applyColorStyleAndDrawMode(renderParameters.drawMode) if (renderParameters.watchFaceLayers.contains(WatchFaceLayer.BASE)) { drawBackground(canvas) } drawComplications(canvas, zonedDateTime) if (renderParameters.watchFaceLayers.contains(WatchFaceLayer.BASE)) { val is24Hour: Boolean = DateFormat.is24HourFormat(context) currentDigitStrings.set(zonedDateTime, is24Hour) nextDigitStrings.set(zonedDateTime.plusSeconds(1), is24Hour) val secondProgress = (zonedDateTime.nano.toDouble() / 1000000000.0).toFloat() val animationStartFraction = DIGIT_ANIMATION_START_TIME_FRACTION[DigitMode.OUTGOING]!! this.interactiveDrawModeUpdateDelayMillis = if (secondProgress < animationStartFraction && !ambientEnterAnimator.isRunning ) { // The seconds only animate part of the time so we can sleep until the seconds next need to // animate, which improves battery life. max( INTERACTIVE_UPDATE_RATE_MS, ((animationStartFraction - secondProgress) * 1000f).toLong() ) } else { INTERACTIVE_UPDATE_RATE_MS } // Move the left position to the left if there are fewer than two hour digits, to // ensure it is centered. If the clock is in transition from one to two hour digits or // vice versa, interpolate to animate the clock's position. // Move the left position to the left if there are fewer than two hour digits, to ensure // it is centered. If the clock is in transition from one to two hour digits or // vice versa, interpolate to animate the clock's position. val centeringAdjustment = ( getInterpolatedValue( (2 - currentDigitStrings.getNumberOfHoursDigits()).toFloat(), (2 - nextDigitStrings.getNumberOfHoursDigits()).toFloat(), POSITION_ANIMATION_START_TIME, POSITION_ANIMATION_END_TIME, secondProgress, CENTERING_ADJUSTMENT_INTERPOLATOR ) * digitWidth ) // This total width assumes two hours digits. val totalWidth = 2f * digitWidth + gapWidth + 2f * smallDigitWidth val left = clockBounds.exactCenterX() - 0.5f * (totalWidth + centeringAdjustment) val top = clockBounds.exactCenterY() - 0.5f * digitHeight val wholeTimeSaveCount = canvas.save() try { canvas.scale( drawProperties.timeScale, drawProperties.timeScale, clockBounds.exactCenterX(), clockBounds.exactCenterY() ) // Draw hours. drawDigit( canvas, left, top, currentDigitStrings, nextDigitStrings, DigitType.HOUR_TENS, secondProgress ) drawDigit( canvas, left + digitWidth, top, currentDigitStrings, nextDigitStrings, DigitType.HOUR_UNITS, secondProgress ) // Draw minutes. val minutesLeft = left + digitWidth * 2.0f + gapWidth drawDigit( canvas, minutesLeft, top, currentDigitStrings, nextDigitStrings, DigitType.MINUTE_TENS, secondProgress ) drawDigit( canvas, minutesLeft + smallDigitWidth, top, currentDigitStrings, nextDigitStrings, DigitType.MINUTE_UNITS, secondProgress ) // Scale the seconds if they're not fully showing, in and out of ambient for // example. val scaleSeconds = drawProperties.secondsScale < 1.0f if (drawProperties.secondsScale > 0f && (renderParameters.drawMode != DrawMode.AMBIENT || scaleSeconds) ) { val restoreCount = canvas.save() if (scaleSeconds) { // Scale the canvas around the center of the seconds bounds. canvas.scale( drawProperties.secondsScale, drawProperties.secondsScale, minutesLeft + smallDigitWidth, top + digitHeight - smallDigitHeight / 2 ) } // Draw seconds. val secondsTop = top + digitHeight - smallDigitHeight drawDigit( canvas, minutesLeft, secondsTop, currentDigitStrings, nextDigitStrings, DigitType.SECOND_TENS, secondProgress ) drawDigit( canvas, minutesLeft + smallDigitWidth, secondsTop, currentDigitStrings, nextDigitStrings, DigitType.SECOND_UNITS, secondProgress ) canvas.restoreToCount(restoreCount) } } finally { canvas.restoreToCount(wholeTimeSaveCount) } } } override fun renderHighlightLayer( canvas: Canvas, bounds: Rect, zonedDateTime: ZonedDateTime ) { drawComplicationHighlights(canvas, zonedDateTime) } override fun getMainClockElementBounds() = clockBounds private fun recalculateBoundsIfChanged(bounds: Rect, zonedDateTime: ZonedDateTime) { if (oldBounds == bounds) { return } oldBounds.set(bounds) calculateClockBound(bounds, zonedDateTime) } private fun calculateClockBound(bounds: Rect, zonedDateTime: ZonedDateTime) { val hasVerticalComplication = VERTICAL_COMPLICATION_IDS.any { complicationSlotsManager[it]!!.isActiveAt(zonedDateTime.toInstant()) } val hasHorizontalComplication = HORIZONTAL_COMPLICATION_IDS.any { complicationSlotsManager[it]!!.isActiveAt(zonedDateTime.toInstant()) } val marginX = if (hasHorizontalComplication) { (MARGIN_FRACTION_WITH_COMPLICATION.x * bounds.width().toFloat()).toInt() } else { (MARGIN_FRACTION_WITHOUT_COMPLICATION.x * bounds.width().toFloat()).toInt() } val marginY = if (hasVerticalComplication) { (MARGIN_FRACTION_WITH_COMPLICATION.y * bounds.height().toFloat()).toInt() } else { (MARGIN_FRACTION_WITHOUT_COMPLICATION.y * bounds.height().toFloat()).toInt() } clockBounds.set( bounds.left + marginX, bounds.top + marginY, bounds.right - marginX, bounds.bottom - marginY ) recalculateTextSize() } private fun recalculateTextSize() { // Determine the font size to fit by measuring the text for a sample size and compare to // the size. That assume the height of the text scales linearly. val sampleTextSize = clockBounds.height().toFloat() digitTextPaint.setTextSize(sampleTextSize) digitTextPaint.getTextBounds(ALL_DIGITS, 0, ALL_DIGITS.length, digitBounds) var textSize = clockBounds.height() * sampleTextSize / digitBounds.height().toFloat() val textRatio = textSize / clockBounds.height().toFloat() // Remain a top and bottom padding. textSize *= (1f - 2f * DIGIT_PADDING_FRACTION) // Calculate the total width fraction base on the text height. val totalWidthFraction: Float = (2f * DIGIT_WIDTH_FRACTION) + (DIGIT_WIDTH_FRACTION * GAP_WIDTH_FRACTION) + (2f * SMALL_DIGIT_SIZE_FRACTION * SMALL_DIGIT_WIDTH_FRACTION) textSize = min(textSize, (clockBounds.width().toFloat() / totalWidthFraction) * textRatio) setDigitTextSize(textSize) } private fun setDigitTextSize(textSize: Float) { clearDigitBitmapCache() digitTextSize = textSize digitTextPaint.textSize = digitTextSize digitTextPaint.getTextBounds(ALL_DIGITS, 0, 1, digitBounds) digitVerticalPadding = (digitBounds.height() * DIGIT_PADDING_FRACTION).toInt() digitWidth = (digitBounds.height() * DIGIT_WIDTH_FRACTION).toInt() digitHeight = digitBounds.height() + 2 * digitVerticalPadding smallDigitTextSize = textSize * SMALL_DIGIT_SIZE_FRACTION digitTextPaint.setTextSize(smallDigitTextSize) digitTextPaint.getTextBounds(ALL_DIGITS, 0, 1, digitBounds) smallDigitHeight = digitBounds.height() + 2 * digitVerticalPadding smallDigitWidth = (digitBounds.height() * SMALL_DIGIT_WIDTH_FRACTION).toInt() gapWidth = digitHeight * GAP_WIDTH_FRACTION digitTextHoursPaint.textSize = digitTextSize digitTextMinutesPaint.textSize = smallDigitTextSize digitTextSecondsPaint.textSize = smallDigitTextSize } private fun drawBackground(canvas: Canvas) { val backgroundColor = if (renderParameters.drawMode == DrawMode.AMBIENT) { watchFaceColorStyle.ambientStyle.backgroundColor } else { watchFaceColorStyle.activeStyle.backgroundColor } canvas.drawColor( getRGBColor( backgroundColor, drawProperties.backgroundAlpha, Color.BLACK ) ) } private fun drawComplications(canvas: Canvas, zonedDateTime: ZonedDateTime) { // First, draw the background complication if not in ambient mode if (renderParameters.drawMode != DrawMode.AMBIENT) { complicationSlotsManager[ComplicationID.BACKGROUND.ordinal]?.let { if (it.complicationData.value.type != ComplicationType.NO_DATA) { it.render( canvas, zonedDateTime, renderParameters ) } } } for (i in FOREGROUND_COMPLICATION_IDS) { val complication = complicationSlotsManager[i] as ComplicationSlot complication.render(canvas, zonedDateTime, renderParameters) } } private fun drawComplicationHighlights(canvas: Canvas, zonedDateTime: ZonedDateTime) { for (i in FOREGROUND_COMPLICATION_IDS) { val complication = complicationSlotsManager[i] as ComplicationSlot complication.renderHighlightLayer(canvas, zonedDateTime, renderParameters) } } private fun clearDigitBitmapCache() { currentCachedDigits.clear() digitBitmapCache.clear() } private fun drawDigit( canvas: Canvas, left: Float, top: Float, currentDigitStrings: DigitStrings, nextDigitStrings: DigitStrings, digitType: DigitType, secondProgress: Float ) { val currentDigit = currentDigitStrings.get(digitType) val nextDigit = nextDigitStrings.get(digitType) // Draw the current digit bitmap. if (currentDigit != nextDigit) { drawDigitWithAnimation( canvas, left, top, secondProgress, currentDigit, digitType, DigitMode.OUTGOING ) drawDigitWithAnimation( canvas, left, top, secondProgress, nextDigit, digitType, DigitMode.INCOMING ) } else { canvas.drawBitmap( getDigitBitmap(currentDigit, digitType), left, top, digitBitmapPaint ) } } private fun drawDigitWithAnimation( canvas: Canvas, left: Float, top: Float, secondProgress: Float, digit: String, digitType: DigitType, digitMode: DigitMode ) { getDigitDrawProperties( secondProgress, getTimeOffsetSeconds(digitType), digitMode, digitDrawProperties ) if (!digitDrawProperties.shouldDraw) { return } val bitmap = getDigitBitmap(digit, digitType) val centerX = left + bitmap.width / 2f val centerY = top + bitmap.height / 2f val restoreCount = canvas.save() canvas.scale(digitDrawProperties.scale, digitDrawProperties.scale, centerX, centerY) canvas.rotate(digitDrawProperties.rotation, centerX, centerY) val bitmapPaint = digitBitmapPaint bitmapPaint.alpha = (digitDrawProperties.opacity * 255.0f).toInt() canvas.drawBitmap(bitmap, left, top, bitmapPaint) bitmapPaint.alpha = 255 canvas.restoreToCount(restoreCount) } private fun createBitmap( width: Int, height: Int, digitType: DigitType ): Bitmap { val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) digitBitmapCache.put(digitType.ordinal, bitmap) return bitmap } /** * Returns a {@link Bitmap} representing the given {@code digit}, suitable for use as the * given {@code digitType}. */ private fun getDigitBitmap(digit: String, digitType: DigitType): Bitmap { val width: Int val height: Int val paint: Paint when (digitType) { DigitType.HOUR_TENS, DigitType.HOUR_UNITS -> { width = digitWidth height = digitHeight paint = digitTextHoursPaint } DigitType.MINUTE_TENS, DigitType.MINUTE_UNITS -> { width = smallDigitWidth height = smallDigitHeight paint = digitTextMinutesPaint } DigitType.SECOND_TENS, DigitType.SECOND_UNITS -> { width = smallDigitWidth height = smallDigitHeight paint = digitTextSecondsPaint } } val bitmap = digitBitmapCache.get(digitType.ordinal) ?: createBitmap(width, height, digitType) if (digit != currentCachedDigits.get(digitType.ordinal)) { currentCachedDigits.put(digitType.ordinal, digit) bitmap.eraseColor(Color.TRANSPARENT) val canvas = Canvas(bitmap) val textWidth = paint.measureText(digit) // We use the same vertical padding here for all types and sizes of digit so that // their tops and bottoms can be aligned. canvas.drawText( digit, (width - textWidth) / 2, height.toFloat() - digitVerticalPadding, paint ) } return bitmap } } private data class Vec2f(val x: Float, val y: Float) private enum class ComplicationID { UPPER, RIGHT, LOWER, LEFT, BACKGROUND } // Changing digits are animated. This enum is used to label the start and end animation parameters. private enum class DigitMode { OUTGOING, INCOMING } private enum class DigitType { HOUR_TENS, HOUR_UNITS, MINUTE_TENS, MINUTE_UNITS, SECOND_TENS, SECOND_UNITS } /** A class to provide string representations of each of the digits of a given time. */ private class DigitStrings { private var hourTens = "" private var hourUnits = "" private var minuteTens = "" private var minuteUnits = "" private var secondTens = "" private var secondUnits = "" /** Sets the time represented by this instance. */ fun set(zonedDateTime: ZonedDateTime, is24Hour: Boolean) { if (is24Hour) { val hourValue = zonedDateTime.hour hourTens = getTensDigitString(hourValue, true) hourUnits = getUnitsDigitString(hourValue) } else { var hourValue = zonedDateTime.hour % 12 // We should show 12 for noon and midnight. if (hourValue == 0) { hourValue = 12 } hourTens = getTensDigitString(hourValue, false) hourUnits = getUnitsDigitString(hourValue) } val minuteValue = zonedDateTime.minute minuteTens = getTensDigitString(minuteValue, true) minuteUnits = getUnitsDigitString(minuteValue) val secondsValue = zonedDateTime.second secondTens = getTensDigitString(secondsValue, true) secondUnits = getUnitsDigitString(secondsValue) } /** Returns a string representing the specified digit of the time represented by this object. */ fun get(digitType: DigitType): String { return when (digitType) { DigitType.HOUR_TENS -> hourTens DigitType.HOUR_UNITS -> hourUnits DigitType.MINUTE_TENS -> minuteTens DigitType.MINUTE_UNITS -> minuteUnits DigitType.SECOND_TENS -> secondTens DigitType.SECOND_UNITS -> secondUnits } } /** * Returns the number of hour digits in this object. If the representation is 24-hour, this will * always return 2. If 12-hour, this will return 1 or 2. */ fun getNumberOfHoursDigits(): Int { return if (hourTens == "") 1 else 2 } /** * Returns a {@link String} representing the tens digit of the provided non-negative {@code * value}. If {@code padWithZeroes} is true, returns zero if {@code value} < 10. If {@code * padWithZeroes} is false, returns an empty string if {@code value} < 10. */ private fun getTensDigitString(value: Int, padWithZeroes: Boolean): String { if (value < 10 && !padWithZeroes) { return "" } // We don't use toString() because during draw calls we don't want to avoid allocating objects. return DIGITS[(value / 10) % 10] } /** * Returns a {@link String} representing the units digit of the provided non-negative {@code * value}. */ private fun getUnitsDigitString(value: Int): String { // We don't use toString() because during draw calls we don't want to avoid allocating objects. return DIGITS[value % 10] } } private data class DigitDrawProperties( var shouldDraw: Boolean = false, var scale: Float = 0f, var rotation: Float = 0f, var opacity: Float = 0f ) private class DrawProperties( var backgroundAlpha: Float = 1f, var timeScale: Float = 1f, var secondsScale: Float = 1f ) { companion object { val TIME_SCALE = object : FloatProperty<DrawProperties>("timeScale") { override fun setValue(obj: DrawProperties, value: Float) { obj.timeScale = value } override fun get(obj: DrawProperties): Float { return obj.timeScale } } val SECONDS_SCALE = object : FloatProperty<DrawProperties>("secondsScale") { override fun setValue(obj: DrawProperties, value: Float) { obj.secondsScale = value } override fun get(obj: DrawProperties): Float { return obj.secondsScale } } } } companion object { private const val COLOR_STYLE_SETTING = "color_style_setting" private const val RED_STYLE = "red_style" private const val GREEN_STYLE = "green_style" private const val BLUE_STYLE = "blue_style" // Render at approximately 60fps in interactive mode. private const val INTERACTIVE_UPDATE_RATE_MS = 16L // Constants for the size of complication. private val CIRCLE_COMPLICATION_DIAMETER_FRACTION = Vec2f(0.252f, 0.252f) private val ROUND_RECT_COMPLICATION_SIZE_FRACTION = Vec2f(0.645f, 0.168f) // Constants for the upper complication location. private val UPPER_CIRCLE_COMPLICATION_CENTER_FRACTION = PointF(0.5f, 0.21f) private val UPPER_ROUND_RECT_COMPLICATION_CENTER_FRACTION = PointF(0.5f, 0.21f) // Constants for the lower complication location. private val LOWER_CIRCLE_COMPLICATION_CENTER_FRACTION = PointF(0.5f, 0.79f) private val LOWER_ROUND_RECT_COMPLICATION_CENTER_FRACTION = PointF(0.5f, 0.79f) // Constants for the left complication location. private val LEFT_CIRCLE_COMPLICATION_CENTER_FRACTION = PointF(0.177f, 0.5f) // Constants for the right complication location. private val RIGHT_CIRCLE_COMPLICATION_CENTER_FRACTION = PointF(0.823f, 0.5f) // Constants for the clock digits' position, based on the height and width of given bounds. private val MARGIN_FRACTION_WITHOUT_COMPLICATION = Vec2f(0.2f, 0.2f) private val MARGIN_FRACTION_WITH_COMPLICATION = Vec2f(0.4f, 0.4f) private val VERTICAL_COMPLICATION_IDS = arrayOf( ComplicationID.UPPER.ordinal, ComplicationID.LOWER.ordinal ) private val HORIZONTAL_COMPLICATION_IDS = arrayOf( ComplicationID.LEFT.ordinal, ComplicationID.RIGHT.ordinal ) private val FOREGROUND_COMPLICATION_IDS = arrayOf( ComplicationID.UPPER.ordinal, ComplicationID.RIGHT.ordinal, ComplicationID.LOWER.ordinal, ComplicationID.LEFT.ordinal ) // The name of the font used for drawing the text in the digit watch face. private const val DIGITAL_TYPE_FACE = "sans-serif-condensed-light" // The width of the large digit bitmaps, as a fraction of their height. private const val DIGIT_WIDTH_FRACTION = 0.65f // The height of the small digits (used for minutes and seconds), given as a fraction of the height // of the large digits. private const val SMALL_DIGIT_SIZE_FRACTION = 0.45f // The width of the small digit bitmaps, as a fraction of their height. private const val SMALL_DIGIT_WIDTH_FRACTION = 0.7f // The padding at the top and bottom of the digit bitmaps, given as a fraction of the height. // Needed as some characters may ascend or descend slightly (e.g. "8"). private const val DIGIT_PADDING_FRACTION = 0.05f // The gap between the hours and the minutes/seconds, given as a fraction of the width of the large // digits. private const val GAP_WIDTH_FRACTION = 0.1f // A string containing all digits, used to measure their height. private const val ALL_DIGITS = "0123456789" private val DIGITS = ALL_DIGITS.toCharArray().map { it.toString() } // The start and end times of the animations, expressed as a fraction of a second. // (So 0.5 means that the animation of that digit will begin half-way through the second). // Note that because we only cache one digit of each type, the current and next times must // not overlap. private val DIGIT_ANIMATION_START_TIME_FRACTION = mapOf( DigitMode.OUTGOING to 0.5f, DigitMode.INCOMING to 0.667f ) private val DIGIT_ANIMATION_END_TIME = mapOf( DigitMode.OUTGOING to 0.667f, DigitMode.INCOMING to 1f ) private const val POSITION_ANIMATION_START_TIME = 0.0833f private const val POSITION_ANIMATION_END_TIME = 0.5833f // Parameters governing the animation of the current and next digits. NB Scale is a size multiplier. // The first index is the values for the outgoing digit, and the second index for the incoming // digit. If seconds are changing from 1 -> 2 for example, the 1 will scale from 1f to 0.65f, and // rotate from 0f to 82f. The 2 will scale from 0.65f to 1f, and rotate from -97f to 0f. private val DIGIT_SCALE_START = mapOf(DigitMode.OUTGOING to 1f, DigitMode.INCOMING to 0.65f) private val DIGIT_SCALE_END = mapOf(DigitMode.OUTGOING to 0.65f, DigitMode.INCOMING to 1f) private val DIGIT_ROTATE_START_DEGREES = mapOf( DigitMode.OUTGOING to 0f, DigitMode.INCOMING to -97f ) private val DIGIT_ROTATE_END_DEGREES = mapOf(DigitMode.OUTGOING to 82f, DigitMode.INCOMING to 0f) private val DIGIT_OPACITY_START = mapOf(DigitMode.OUTGOING to 1f, DigitMode.INCOMING to 0.07f) private val DIGIT_OPACITY_END = mapOf(DigitMode.OUTGOING to 0f, DigitMode.INCOMING to 1f) // The offset used to stagger the animation when multiple digits are animating at the same time. private const val TIME_OFFSET_SECONDS_PER_DIGIT_TYPE = -5 / 60f // The duration of the ambient mode change animation. private const val AMBIENT_TRANSITION_MS = 333L private val DIGIT_SCALE_INTERPOLATOR = mapOf( DigitMode.OUTGOING to PathInterpolator(0.4f, 0f, 0.67f, 1f), DigitMode.INCOMING to PathInterpolator(0.33f, 0f, 0.2f, 1f) ) private val DIGIT_ROTATION_INTERPOLATOR = mapOf( DigitMode.OUTGOING to PathInterpolator(0.57f, 0f, 0.73f, 0.49f), DigitMode.INCOMING to PathInterpolator(0.15f, 0.49f, 0.37f, 1f) ) private val DIGIT_OPACITY_INTERPOLATOR = mapOf( DigitMode.OUTGOING to PathInterpolator(0.4f, 0f, 1f, 1f), DigitMode.INCOMING to PathInterpolator(0f, 0f, 0.2f, 1f) ) private val CENTERING_ADJUSTMENT_INTERPOLATOR = PathInterpolator(0.4f, 0f, 0.2f, 1f) @ColorInt private fun colorRgb(red: Float, green: Float, blue: Float) = 0xff000000.toInt() or ((red * 255.0f + 0.5f).toInt() shl 16) or ((green * 255.0f + 0.5f).toInt() shl 8) or (blue * 255.0f + 0.5f).toInt() private fun redFraction(@ColorInt color: Int) = Color.red(color).toFloat() / 255.0f private fun greenFraction(@ColorInt color: Int) = Color.green(color).toFloat() / 255.0f private fun blueFraction(@ColorInt color: Int) = Color.blue(color).toFloat() / 255.0f /** * Returns an RGB color that has the same effect as drawing `color` with `alphaFraction` over a * `backgroundColor` background. * * @param color the foreground color * @param alphaFraction the fraction of the alpha value, range from 0 to 1 * @param backgroundColor the background color */ private fun getRGBColor( @ColorInt color: Int, alphaFraction: Float, @ColorInt backgroundColor: Int ): Int { return colorRgb( lerp(redFraction(backgroundColor), redFraction(color), alphaFraction), lerp(greenFraction(backgroundColor), greenFraction(color), alphaFraction), lerp(blueFraction(backgroundColor), blueFraction(color), alphaFraction) ) } /** Returns a linear interpolation between a and b using the scalar s. */ private fun lerp(a: Float, b: Float, s: Float) = a + s * (b - a) /** * Returns the interpolation scalar (s) that satisfies the equation: `value = lerp(a, b, s)` * * If `a == b`, then this function will return 0. */ private fun lerpInv(a: Float, b: Float, value: Float) = if (a != b) (value - a) / (b - a) else 0.0f private fun getInterpolatedValue( startValue: Float, endValue: Float, startTime: Float, endTime: Float, currentTime: Float, interpolator: TimeInterpolator ): Float { val progress = when { currentTime < startTime -> 0f currentTime > endTime -> 1f else -> interpolator.getInterpolation(lerpInv(startTime, endTime, currentTime)) } return lerp(startValue, endValue, progress) } /** * Sets the [DigitDrawProperties] that should be used for drawing, given the specified * parameters. * * @param secondProgress the sub-second part of the current time, where 0 means the current second * has just begun, and 1 means the current second has just ended * @param offsetSeconds a value added to the start and end time of the animations * @param digitMode whether the digit is OUTGOING or INCOMING * @param output the [DigitDrawProperties] that will be set */ private fun getDigitDrawProperties( secondProgress: Float, offsetSeconds: Float, digitMode: DigitMode, output: DigitDrawProperties ) { val startTime = DIGIT_ANIMATION_START_TIME_FRACTION[digitMode]!! + offsetSeconds val endTime = DIGIT_ANIMATION_END_TIME[digitMode]!! + offsetSeconds output.shouldDraw = if (digitMode == DigitMode.OUTGOING) { secondProgress < endTime } else { secondProgress >= startTime } output.scale = getInterpolatedValue( DIGIT_SCALE_START[digitMode]!!, DIGIT_SCALE_END[digitMode]!!, startTime, endTime, secondProgress, DIGIT_SCALE_INTERPOLATOR[digitMode]!! ) output.rotation = getInterpolatedValue( DIGIT_ROTATE_START_DEGREES[digitMode]!!, DIGIT_ROTATE_END_DEGREES[digitMode]!!, startTime, endTime, secondProgress, DIGIT_ROTATION_INTERPOLATOR[digitMode]!! ) output.opacity = getInterpolatedValue( DIGIT_OPACITY_START[digitMode]!!, DIGIT_OPACITY_END[digitMode]!!, startTime, endTime, secondProgress, DIGIT_OPACITY_INTERPOLATOR[digitMode]!! ) } private fun getTimeOffsetSeconds(digitType: DigitType): Float { return when (digitType) { DigitType.HOUR_TENS -> 5f * TIME_OFFSET_SECONDS_PER_DIGIT_TYPE DigitType.HOUR_UNITS -> 4f * TIME_OFFSET_SECONDS_PER_DIGIT_TYPE DigitType.MINUTE_TENS -> 3f * TIME_OFFSET_SECONDS_PER_DIGIT_TYPE DigitType.MINUTE_UNITS -> 2f * TIME_OFFSET_SECONDS_PER_DIGIT_TYPE DigitType.SECOND_TENS -> 1f * TIME_OFFSET_SECONDS_PER_DIGIT_TYPE DigitType.SECOND_UNITS -> 0f } } /** Applies a multiplier to a color, e.g. to darken if it's < 1.0 */ private fun multiplyColor(colorInt: Int, multiplier: Float): Int { val adjustedMultiplier = multiplier / 255.0f return colorRgb( Color.red(colorInt).toFloat() * adjustedMultiplier, Color.green(colorInt).toFloat() * adjustedMultiplier, Color.blue(colorInt).toFloat() * adjustedMultiplier, ) } private fun createBoundsRect( centerFraction: PointF, size: Vec2f ): RectF { val halfWidth = size.x / 2.0f val halfHeight = size.y / 2.0f return RectF( (centerFraction.x - halfWidth), (centerFraction.y - halfHeight), (centerFraction.x + halfWidth), (centerFraction.y + halfHeight) ) } } }
apache-2.0
d206838d470dc3d128b2b46443170531
40.551493
115
0.583721
5.671114
false
false
false
false