repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
TeamWizardry/LibrarianLib
modules/facade/src/main/kotlin/com/teamwizardry/librarianlib/facade/value/GuiValue.kt
1
6429
package com.teamwizardry.librarianlib.facade.value import com.teamwizardry.librarianlib.core.util.lerp.Lerper import com.teamwizardry.librarianlib.facade.layer.AnimationTimeListener import com.teamwizardry.librarianlib.math.Animation import com.teamwizardry.librarianlib.math.BasicAnimation import com.teamwizardry.librarianlib.math.Easing import com.teamwizardry.librarianlib.math.KeyframeAnimation import java.util.PriorityQueue /** * The common functionality for both primitive and generic GuiValues */ public abstract class GuiValue<T>: AnimationTimeListener { private var _animationValue: T? = null private var currentTime: Float = 0f private val animations = PriorityQueue<ScheduledAnimation<T>>() private var animation: ScheduledAnimation<T>? = null //region API @JvmOverloads public fun animate(from: T, to: T, duration: Float, easing: Easing = Easing.linear, delay: Float = 0f): BasicAnimation<T> { if (!hasLerper) throw IllegalStateException("Can not animate a GuiValue that has no lerper") val animation = SimpleAnimation(from, to, duration, easing, false) scheduleAnimation(delay, animation) return animation } @JvmOverloads public fun animate(to: T, duration: Float, easing: Easing = Easing.linear, delay: Float = 0f): BasicAnimation<T> { if (!hasLerper) throw IllegalStateException("Can not animate a GuiValue that has no lerper") // `delay == 0f` should be interpreted as *immediately* reading the starting value, not reading it when the // animation actually starts. val animation = SimpleAnimation(currentValue, to, duration, easing, delay != 0f) scheduleAnimation(delay, animation) return animation } @JvmOverloads public fun animateKeyframes(initialValue: T, delay: Float = 0f): KeyframeAnimation<T> { if(!hasLerper) throw IllegalStateException("Can not animate a GuiValue that has no lerper") val animation = KeyframeAnimation(initialValue, lerperInstance) scheduleAnimation(delay, animation) return animation } /** * Schedule an animation to run in [delay] ticks */ public fun scheduleAnimation(delay: Float, animation: Animation<T>) { animations.add(ScheduledAnimation(currentTime + delay, animation)) } //endregion //region Subclass API /** * Whether this GuiValue has a lerper, and thus can be animated */ protected abstract val hasLerper: Boolean /** * The current value, used when animating from the current value, and when animations are detecting changes */ protected abstract val currentValue: T /** * Lerp the value */ protected abstract fun lerp(from: T, to: T, fraction: Float): T /** * Called when the animation value changes */ protected abstract fun animationChange(from: T, to: T) /** * Called to persist the final value of an animation when it completes. This is called _before_ the animation is * removed. */ protected abstract fun persistAnimation(value: T) /** * When this is true, [_animationValue] */ protected val useAnimationValue: Boolean get() = animation != null /** * The current animation's value */ protected val animationValue: T @Suppress("UNCHECKED_CAST") get() = _animationValue as T //endregion override fun updateTime(time: Float) { currentTime = time if (animation == null && animations.isEmpty()) return val oldValue = currentValue var didAnimate = false var newValue = oldValue var animation = animation fun finishAnimations() { animation?.also { newValue = it.finish(time) didAnimate = true animation = null } } fun startAnimation(newAnimation: ScheduledAnimation<T>) { animation = newAnimation newAnimation.start() } while (animations.isNotEmpty() && animations.peek().start <= time) { finishAnimations() startAnimation(animations.poll()) } // if we're past the end of the animation, wrap it up if (animation != null && time >= animation!!.end) { finishAnimations() } // if we survived this far, this is the current animation, and `time` is within its range animation?.also { newValue = it.update(time) didAnimate = true } if (didAnimate) { _animationValue = newValue if (oldValue != newValue) { animationChange(oldValue, newValue) } if (animation == null) { persistAnimation(newValue) _animationValue = null } this.animation = animation } } private val lerperInstance = object: Lerper<T>() { override fun lerp(from: T, to: T, fraction: Float): T { return [email protected](from, to, fraction) } } private class ScheduledAnimation<T>(val start: Float, val animation: Animation<T>): Comparable<ScheduledAnimation<T>> { val end: Float get() = start + animation.end fun update(time: Float): T { return animation.animate(time - start) } fun start() { animation.onStarted() } fun finish(time: Float): T { return animation.onStopped(time - start) } override fun compareTo(other: ScheduledAnimation<T>): Int { return start.compareTo(other.start) } } private inner class SimpleAnimation( var from: T, val to: T, duration: Float, val easing: Easing, /** * If true, this animation will load the current value into [from] when it starts. This is used for animations * with implicit start values. */ val fromCurrentValue: Boolean ): BasicAnimation<T>(duration) { override fun onStarted() { super.onStarted() if (fromCurrentValue) from = currentValue } override fun getValueAt(time: Float, loopCount: Int): T { return lerp(from, to, easing.ease(time)) } } }
lgpl-3.0
9d714e964fb12133a68e2a48e3b08032
31.474747
127
0.619536
4.779926
false
false
false
false
kamerok/Orny
app/src/main/kotlin/com/kamer/orny/data/android/ReactiveActivitiesImpl.kt
1
4743
package com.kamer.orny.data.android import android.accounts.AccountManager import android.app.Activity import android.content.Intent import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException import com.kamer.orny.di.app.ApplicationScope import com.kamer.orny.presentation.launch.LoginActivity import io.reactivex.Completable import io.reactivex.Single import io.reactivex.schedulers.Schedulers import javax.inject.Inject @ApplicationScope class ReactiveActivitiesImpl @Inject constructor( val activityHolder: ActivityHolder ) : ReactiveActivities, ActivityHolder.ActivityResultHandler { companion object { private const val REQUEST_LOGIN = 1000 private const val REQUEST_ACCOUNT_PICKER = 1001 private const val REQUEST_RECOVER_AUTH = 1002 } private var loginListener: CompletableListener? = null private var recoverGoogleAuthListener: CompletableListener? = null private var chooseAccountListener: SingleListener<String>? = null init { activityHolder.addActivityResultHandler(this) } override fun login(): Completable = Completable .create { e -> loginListener = object : CompletableListener { override fun onError(t: Throwable) = e.onError(t) override fun onSuccess() { e.onComplete() loginListener = null } } val activity = activityHolder.getActivity() activity?.startActivityForResult(LoginActivity.getIntent(activity), REQUEST_LOGIN) } .observeOn(Schedulers.io()) override fun recoverGoogleAuthException(exception: UserRecoverableAuthIOException): Completable = Completable .create { e -> recoverGoogleAuthListener = object : CompletableListener { override fun onError(t: Throwable) = e.onError(t) override fun onSuccess() { e.onComplete() recoverGoogleAuthListener = null } } activityHolder.getActivity()?.startActivityForResult(exception.intent, REQUEST_RECOVER_AUTH) } .observeOn(Schedulers.io()) override fun chooseGoogleAccount(credential: GoogleAccountCredential): Single<String> = Single .create<String> { e -> chooseAccountListener = object : SingleListener<String> { override fun onError(t: Throwable) = e.onError(t) override fun onSuccess(value: String) = e.onSuccess(value) } activityHolder.getActivity()?.startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER) } .observeOn(Schedulers.io()) override fun handleActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean = when (requestCode) { REQUEST_LOGIN -> { if (resultCode == Activity.RESULT_OK) { loginListener?.onSuccess() } else { loginListener?.onError(Exception("Login failed")) } true } REQUEST_RECOVER_AUTH -> { if (resultCode == Activity.RESULT_OK) { recoverGoogleAuthListener?.onSuccess() } else { recoverGoogleAuthListener?.onError(Exception("No permission")) } true } REQUEST_ACCOUNT_PICKER -> { if (resultCode == Activity.RESULT_OK && data != null && data.extras != null) { val accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME) if (accountName != null) { chooseAccountListener?.onSuccess(accountName) } else { chooseAccountListener?.onError(Exception("No name")) } } else { chooseAccountListener?.onError(Exception("Pick account failed")) } true } else -> false } private interface CompletableListener { fun onError(t: Throwable) fun onSuccess() } private interface SingleListener<in T> { fun onError(t: Throwable) fun onSuccess(value: T) } }
apache-2.0
603cd44e0ac9fe588a9165bff740faef
36.650794
129
0.576218
5.721351
false
false
false
false
AoEiuV020/LearningKotlin
app/src/test/kotlin/aoeiuv020/BasicSyntaxTest.kt
1
2563
package aoeiuv020 import java.util.Arrays import org.junit.Test import kotlin.test.assertEquals import kotlin.test.fail class BasicSyntaxTest { @Test fun readOnly() { val r = 0 // r = 1 // Val cannot be reassigned assertEquals(0, r) var v = 1 assertEquals(1, v) v = 2 assertEquals(2, v) } @Suppress("unused") fun comment() { /* block comment /* inner block comment */ fail() */ // fail() } @Test fun number() { var i = 0xff_ee_dd assertEquals(0xffeedd, i) i = 0b0110_1100 assertEquals(0x6c, i) } @Test fun assert() { assert(true) } @Test fun function() { fun sumA(a: Int, b: Int): Int = a + b assertEquals(3, sumA(1, 2)) fun sumB(a: Int, b: Int) = a + b assertEquals(3, sumB(1, 2)) fun sumC(a: Int, b: Int): Unit {} assertEquals(Unit.javaClass, sumC(1, 2).javaClass) //下面这个抛空指针异常且无法捕获,怀疑是kotlinc的bug, //bug reported kotlin-1.1.2: https://youtrack.jetbrains.com/issue/KT-17692 //已经修复了,1.1.4生效, // https://github.com/JetBrains/kotlin/commit/52237ce77fb6a3c3f0d0543260968b37b16e9c34 //assertEquals(Unit.javaClass, sumC(1, 2)::class.java) // org.jetbrains.kotlin.codegen.CompilationException: Back-end (JVM) Internal error: Failed to generate function function Cause: java.lang.NullPointerException } @Test fun lateinitTest() { } @Test fun isTest() { fun getObejct(): Any = "any" val any: Any = getObejct() assertEquals(String::class.java, any::class.java) // e: Type inference failed. The value of the type parameter T should be mentioned in input types (argument types, receiver type or expected type). Try to specify it explicitly. //assertEquals(String::class.java, any.javaClass) //assertEquals(3, any.length) // e: Unresolved reference: length if (any is String) { assertEquals(3, any.length) } //assertEquals(3, any.length) // e: Unresolved reference: length if (any !is String) { fail() return } assertEquals(3, any.length) } @Test fun destructArray() { fun p(vararg args: Int) = Arrays.toString(args) assertEquals("[1, 2]", p(1, 2)) val a = intArrayOf(7, 8) assertEquals("[1, 7, 8, 2]", p(1, *a, 2)) } }
mit
3ff519f321745e94208cfc38cccefdef
27.465909
223
0.572455
3.533145
false
true
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/contacts/ContactChipViewModel.kt
1
2744
package org.thoughtcrime.securesms.contacts import androidx.lifecycle.ViewModel import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.core.BackpressureStrategy import io.reactivex.rxjava3.core.Flowable import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.disposables.Disposable import io.reactivex.rxjava3.kotlin.plusAssign import io.reactivex.rxjava3.schedulers.Schedulers import org.thoughtcrime.securesms.dependencies.ApplicationDependencies import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.recipients.RecipientId import org.thoughtcrime.securesms.util.rx.RxStore /** * ViewModel expressly for displaying the current state of the contact chips * in the contact selection fragment. */ class ContactChipViewModel : ViewModel() { private val store = RxStore(emptyList<SelectedContacts.Model>()) val state: Flowable<List<SelectedContacts.Model>> = store.stateFlowable .distinctUntilChanged() .observeOn(AndroidSchedulers.mainThread()) val count = store.state.size private val disposables = CompositeDisposable() private val disposableMap: MutableMap<RecipientId, Disposable> = mutableMapOf() override fun onCleared() { disposables.clear() disposableMap.values.forEach { it.dispose() } disposableMap.clear() store.dispose() } fun add(selectedContact: SelectedContact) { disposables += getOrCreateRecipientId(selectedContact).map { Recipient.resolved(it) }.observeOn(Schedulers.io()).subscribe { recipient -> store.update { it + SelectedContacts.Model(selectedContact, recipient) } disposableMap[recipient.id]?.dispose() disposableMap[recipient.id] = store.update(recipient.live().asObservable().toFlowable(BackpressureStrategy.LATEST)) { changedRecipient, state -> val index = state.indexOfFirst { it.selectedContact.matches(selectedContact) } when { index == 0 -> { listOf(SelectedContacts.Model(selectedContact, changedRecipient)) + state.drop(index + 1) } index > 0 -> { state.take(index) + SelectedContacts.Model(selectedContact, changedRecipient) + state.drop(index + 1) } else -> { state } } } } } fun remove(selectedContact: SelectedContact) { store.update { list -> list.filterNot { it.selectedContact.matches(selectedContact) } } } private fun getOrCreateRecipientId(selectedContact: SelectedContact): Single<RecipientId> { return Single.fromCallable { selectedContact.getOrCreateRecipientId(ApplicationDependencies.getApplication()) } } }
gpl-3.0
40e3a204d22d6056d5a6fd31ce3cbf82
36.589041
150
0.742347
4.635135
false
false
false
false
DemonWav/StatCraft
src/main/kotlin/com/demonwav/statcraft/commands/sc/SCBlocksBroken.kt
1
1987
/* * StatCraft Bukkit Plugin * * Copyright (c) 2016 Kyle Wood (DemonWav) * https://www.demonwav.com * * MIT License */ package com.demonwav.statcraft.commands.sc import com.demonwav.statcraft.StatCraft import com.demonwav.statcraft.commands.ResponseBuilder import com.demonwav.statcraft.querydsl.QBlockBreak import com.demonwav.statcraft.querydsl.QPlayers import org.bukkit.command.CommandSender import java.sql.Connection class SCBlocksBroken(plugin: StatCraft) : SCTemplate(plugin) { init { plugin.baseCommand.registerCommand("blocksbroken", this) } override fun hasPermission(sender: CommandSender, args: Array<out String>?) = sender.hasPermission("statcraft.user.blocksbroken") override fun playerStatResponse(name: String, args: List<String>, connection: Connection): String { val id = getId(name) ?: return ResponseBuilder.build(plugin) { playerName { name } statName { "BlocksBroken" } stats["Total"] = "0" } val query = plugin.databaseManager.getNewQuery(connection) ?: return databaseError val b = QBlockBreak.blockBreak val total = query.from(b).where(b.id.eq(id)).uniqueResult(b.amount.sum()) ?: 0 return ResponseBuilder.build(plugin) { playerName { name } statName { "BlocksBroken" } stats["Total"] = df.format(total) } } override fun serverStatListResponse(num: Long, args: List<String>, connection: Connection): String? { val query = plugin.databaseManager.getNewQuery(connection) ?: return databaseError val b = QBlockBreak.blockBreak val p = QPlayers.players val result = query .from(b) .innerJoin(p) .on(b.id.eq(p.id)) .groupBy(p.name) .orderBy(b.amount.sum().desc()) .limit(num) .list(p.name, b.amount.sum()) return topListResponse("Blocks Broken", result) } }
mit
b2bf6b0df634034ac14aa6541106ec4d
30.539683
133
0.64922
4.156904
false
false
false
false
Soya93/Extract-Refactoring
plugins/settings-repository/src/keychain/OSXKeychainLibrary.kt
4
6568
/* * Copyright 2000-2016 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.keychain import com.intellij.openapi.util.SystemInfo import com.sun.jna.Pointer import java.nio.ByteBuffer import java.nio.CharBuffer val isOSXCredentialsStoreSupported: Boolean get() = SystemInfo.isMacIntel64 && SystemInfo.isMacOSLeopard // http://developer.apple.com/mac/library/DOCUMENTATION/Security/Reference/keychainservices/Reference/reference.html // It is very, very important to use CFRelease/SecKeychainItemFreeContent You must do it, otherwise you can get "An invalid record was encountered." interface OSXKeychainLibrary : com.sun.jna.Library { companion object { private val LIBRARY = com.sun.jna.Native.loadLibrary("Security", OSXKeychainLibrary::class.java) as OSXKeychainLibrary fun saveGenericPassword(serviceName: ByteArray, accountName: String, password: CharArray) { saveGenericPassword(serviceName, accountName, Charsets.UTF_8.encode(CharBuffer.wrap(password))) } fun saveGenericPassword(serviceName: ByteArray, accountName: String, password: String) { saveGenericPassword(serviceName, accountName, Charsets.UTF_8.encode(password)) } private fun saveGenericPassword(serviceName: ByteArray, accountName: String, passwordBuffer: ByteBuffer) { val passwordData: ByteArray val passwordDataSize = passwordBuffer.limit() if (passwordBuffer.hasArray() && passwordBuffer.arrayOffset() == 0) { passwordData = passwordBuffer.array() } else { passwordData = ByteArray(passwordDataSize) passwordBuffer.get(passwordData) } saveGenericPassword(serviceName, accountName, passwordData, passwordDataSize) } fun findGenericPassword(serviceName: ByteArray, accountName: String): String? { val accountNameBytes = accountName.toByteArray() val passwordSize = IntArray(1); val passwordData = arrayOf<Pointer?>(null); checkForError("find", LIBRARY.SecKeychainFindGenericPassword(null, serviceName.size, serviceName, accountNameBytes.size, accountNameBytes, passwordSize, passwordData)) val pointer = passwordData[0] ?: return null val result = String(pointer.getByteArray(0, passwordSize[0])) LIBRARY.SecKeychainItemFreeContent(null, pointer) return result } private fun saveGenericPassword(serviceName: ByteArray, accountName: String, password: ByteArray, passwordSize: Int) { val accountNameBytes = accountName.toByteArray() val itemRef = arrayOf<Pointer?>(null) checkForError("find (for save)", LIBRARY.SecKeychainFindGenericPassword(null, serviceName.size, serviceName, accountNameBytes.size, accountNameBytes, null, null, itemRef)) val pointer = itemRef[0] if (pointer == null) { checkForError("save (new)", LIBRARY.SecKeychainAddGenericPassword(null, serviceName.size, serviceName, accountNameBytes.size, accountNameBytes, passwordSize, password)) } else { checkForError("save (update)", LIBRARY.SecKeychainItemModifyContent(pointer, null, passwordSize, password)) LIBRARY.CFRelease(pointer) } } fun deleteGenericPassword(serviceName: ByteArray, accountName: String) { val itemRef = arrayOf<Pointer?>(null) val accountNameBytes = accountName.toByteArray() checkForError("find (for delete)", LIBRARY.SecKeychainFindGenericPassword(null, serviceName.size, serviceName, accountNameBytes.size, accountNameBytes, null, null, itemRef)) val pointer = itemRef[0] if (pointer != null) { checkForError("delete", LIBRARY.SecKeychainItemDelete(pointer)) LIBRARY.CFRelease(pointer) } } fun checkForError(message: String, code: Int) { if (code != 0 && code != /* errSecItemNotFound, always returned from find it seems */-25300) { val translated = LIBRARY.SecCopyErrorMessageString(code, null); val builder = StringBuilder(message).append(": ") if (translated == null) { builder.append(code); } else { val buf = CharArray(LIBRARY.CFStringGetLength(translated).toInt()) for (i in 0..buf.size - 1) { buf[i] = LIBRARY.CFStringGetCharacterAtIndex(translated, i.toLong()) } LIBRARY.CFRelease(translated) builder.append(buf).append(" (").append(code).append(')') } LOG.error(builder.toString()) } } } fun SecKeychainAddGenericPassword(keychain: Pointer?, serviceNameLength: Int, serviceName: ByteArray, accountNameLength: Int, accountName: ByteArray, passwordLength: Int, passwordData: ByteArray, itemRef: Pointer? = null): Int fun SecKeychainItemModifyContent(/*SecKeychainItemRef*/ itemRef: Pointer, /*SecKeychainAttributeList**/ attrList: Pointer?, length: Int, data: ByteArray): Int fun SecKeychainFindGenericPassword(keychainOrArray: Pointer?, serviceNameLength: Int, serviceName: ByteArray, accountNameLength: Int, accountName: ByteArray, passwordLength: IntArray? = null, passwordData: Array<Pointer?>? = null, itemRef: Array<Pointer?/*SecKeychainItemRef*/>? = null): Int fun SecKeychainItemDelete(itemRef: Pointer): Int fun /*CFString*/ SecCopyErrorMessageString(status: Int, reserved: Pointer?): Pointer? // http://developer.apple.com/library/mac/#documentation/CoreFoundation/Reference/CFStringRef/Reference/reference.html fun /*CFIndex*/ CFStringGetLength(/*CFStringRef*/ theString: Pointer): Long fun /*UniChar*/ CFStringGetCharacterAtIndex(/*CFStringRef*/ theString: Pointer, /*CFIndex*/ idx: Long): Char fun CFRelease(/*CFTypeRef*/ cf: Pointer) fun SecKeychainItemFreeContent(/*SecKeychainAttributeList*/attrList: Pointer?, data: Pointer?) }
apache-2.0
5b953533dcfc162e2e6993415cdd38e8
47.294118
228
0.696255
4.564281
false
false
false
false
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/stb/templates/stb_easy_font.kt
1
3634
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.stb.templates import org.lwjgl.generator.* import org.lwjgl.stb.* val stb_easy_font = "STBEasyFont".nativeClass(packageName = STB_PACKAGE, prefix = "STB", prefixMethod = "stb_", library = STB_LIBRARY) { includeSTBAPI("#include \"stb_easy_font.h\"") documentation = """ Native bindings to stb_easy_font.h from the <a href="https://github.com/nothings/stb">stb library</a>. Bitmap font for use in 3D APIs: ${ul( "Easy-to-deploy", "reasonably compact", "extremely inefficient performance-wise", "crappy-looking", "ASCII-only" )} Intended for when you just want to get some text displaying in a 3D app as quickly as possible. Doesn't use any textures, instead builds characters out of quads. <h3>SAMPLE CODE</h3> Here's sample code for old OpenGL; it's a lot more complicated to make work on modern APIs, and that's your problem. ${codeBlock(""" void print_string(float x, float y, char *text, float r, float g, float b) { static char buffer[99999]; // ~500 chars int num_quads; num_quads = stb_easy_font_print(x, y, text, NULL, buffer, sizeof(buffer)); glColor3f(r,g,b); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(2, GL_FLOAT, 16, buffer); glDrawArrays(GL_QUADS, 0, num_quads*4); glDisableClientState(GL_VERTEX_ARRAY); }""")} """ int( "easy_font_width", "Takes a string and returns the horizontal size.", charASCII_p.IN("text", "an ASCII string"), returnDoc = "the horizontal size, in pixels" ) int( "easy_font_height", "Takes a string and returns the vertical size (which can vary if {@code text} has newlines).", charASCII_p.IN("text", "an ASCII string"), returnDoc = "the vertical size, in pixels" ) int( "easy_font_print", """ Takes a string (which can contain '\n') and fills out a vertex buffer with renderable data to draw the string. Output data assumes increasing x is rightwards, increasing y is downwards. The vertex data is divided into quads, i.e. there are four vertices in the vertex buffer for each quad. The vertices are stored in an interleaved format: ${codeBlock(""" x:float y:float z:float color:uint8[4]""")} You can ignore z and color if you get them from elsewhere. This format was chosen in the hopes it would make it easier for you to reuse existing buffer-drawing code. If you pass in $NULL for color, it becomes {@code 255,255,255,255}. If the buffer isn't large enough, it will truncate. Expect it to use an average of ~270 bytes per character. If your API doesn't draw quads, build a reusable index list that allows you to render quads as indexed triangles. """, float.IN("x", "the x offset"), float.IN("y", "the y offset"), charASCII_p.IN("text", "an ASCII string"), nullable..Check(4)..unsigned_char_p.IN("color", "the text color, in RGBA (4 bytes)"), void_p.OUT("vertex_buffer", "a pointer to memory in which to store the vertex data"), AutoSize("vertex_buffer")..int.IN("vbuf_size", "the {@code vertex_buffer} size, in bytes"), returnDoc = "the number of quads" ) void( "easy_font_spacing", """ Use positive values to expand the space between characters, and small negative values (no smaller than {@code -1.5}) to contract the space between characters. E.g. {@code spacing = 1} adds one "pixel" of spacing between the characters. {@code spacing = -1} is reasonable but feels a bit too compact to me; {@code -0.5} is a reasonable compromise as long as you're scaling the font up. """, float.IN("spacing", "the font spacing") ) }
bsd-3-clause
cc0d4a73761c5e17ba3cf0d5a3a08d75
31.747748
160
0.699505
3.349309
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/platform/mixin/reference/target/TargetReference.kt
1
4453
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.reference.target import com.demonwav.mcdev.platform.mixin.handlers.MixinAnnotationHandler import com.demonwav.mcdev.platform.mixin.handlers.injectionPoint.AtResolver import com.demonwav.mcdev.platform.mixin.reference.MixinReference import com.demonwav.mcdev.platform.mixin.reference.parseMixinSelector import com.demonwav.mcdev.platform.mixin.util.ClassAndMethodNode import com.demonwav.mcdev.platform.mixin.util.MethodTargetMember import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.AT import com.demonwav.mcdev.util.ifEmpty import com.demonwav.mcdev.util.insideAnnotationAttribute import com.demonwav.mcdev.util.reference.PolyReferenceResolver import com.demonwav.mcdev.util.reference.completeToLiteral import com.intellij.openapi.project.Project import com.intellij.patterns.ElementPattern import com.intellij.patterns.PsiJavaPatterns import com.intellij.patterns.StandardPatterns import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementResolveResult import com.intellij.psi.PsiLiteral import com.intellij.psi.PsiMember import com.intellij.psi.ResolveResult import com.intellij.psi.util.parentOfType import com.intellij.util.ArrayUtilRt /** * The reference inside @At.target(). * * See [AtResolver] for details as to how resolving @At references works. */ object TargetReference : PolyReferenceResolver(), MixinReference { val ELEMENT_PATTERN: ElementPattern<PsiLiteral> = PsiJavaPatterns.psiLiteral(StandardPatterns.string()) .insideAnnotationAttribute(AT, "target") override val description: String get() = "target reference '%s'" override fun isValidAnnotation(name: String, project: Project) = name == AT fun resolveTarget(context: PsiElement): PsiMember? { val selector = parseMixinSelector(context) ?: return null return selector.resolveMember(context.project) } /** * Null is returned when no parent annotation handler could be found, in which case we shouldn't mark this * reference as unresolved. */ private fun getTargets(at: PsiAnnotation, forUnresolved: Boolean): List<ClassAndMethodNode>? { val (handler, annotation) = generateSequence(at.parent) { it.parent } .filterIsInstance<PsiAnnotation>() .mapNotNull { annotation -> val qName = annotation.qualifiedName ?: return@mapNotNull null MixinAnnotationHandler.forMixinAnnotation(qName, annotation.project)?.let { it to annotation } }.firstOrNull() ?: return null if (forUnresolved && handler.isSoft) { return null } return handler.resolveTarget(annotation).mapNotNull { (it as? MethodTargetMember)?.classAndMethod } } override fun isUnresolved(context: PsiElement): Boolean { val at = context.parentOfType<PsiAnnotation>() ?: return true val targets = getTargets(at, true)?.ifEmpty { return true } ?: return false return targets.all { val failure = AtResolver(at, it.clazz, it.method).isUnresolved() // leave it if there is a filter to blame, the target reference was at least resolved failure != null && failure.filterToBlame == null } } fun resolveNavigationTargets(context: PsiElement): Array<PsiElement>? { val at = context.parentOfType<PsiAnnotation>() ?: return null val targets = getTargets(at, false) ?: return null return targets.flatMap { AtResolver(at, it.clazz, it.method).resolveNavigationTargets() }.toTypedArray() } override fun resolveReference(context: PsiElement): Array<ResolveResult> { val result = resolveTarget(context) ?: return ResolveResult.EMPTY_ARRAY return arrayOf(PsiElementResolveResult(result)) } override fun collectVariants(context: PsiElement): Array<Any> { val at = context.parentOfType<PsiAnnotation>() ?: return ArrayUtilRt.EMPTY_OBJECT_ARRAY val targets = getTargets(at, false) ?: return ArrayUtilRt.EMPTY_OBJECT_ARRAY return targets.flatMap { target -> AtResolver(at, target.clazz, target.method).collectTargetVariants { builder -> builder.completeToLiteral(context) } }.toTypedArray() } }
mit
029f3e19c8d879e8eea91e6a24621647
41.817308
112
0.727599
4.662827
false
false
false
false
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/messages/dto/MessagesChatPreview.kt
1
2643
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.messages.dto import com.google.gson.annotations.SerializedName import com.vk.dto.common.id.UserId import com.vk.sdk.api.base.dto.BaseLinkButton import kotlin.Boolean import kotlin.Int import kotlin.String import kotlin.collections.List /** * @param adminId * @param joined * @param localId * @param members * @param membersCount * @param title * @param isMember * @param photo * @param isDon * @param isGroupChannel * @param button */ data class MessagesChatPreview( @SerializedName("admin_id") val adminId: UserId? = null, @SerializedName("joined") val joined: Boolean? = null, @SerializedName("local_id") val localId: Int? = null, @SerializedName("members") val members: List<UserId>? = null, @SerializedName("members_count") val membersCount: Int? = null, @SerializedName("title") val title: String? = null, @SerializedName("is_member") val isMember: Boolean? = null, @SerializedName("photo") val photo: MessagesChatSettingsPhoto? = null, @SerializedName("is_don") val isDon: Boolean? = null, @SerializedName("is_group_channel") val isGroupChannel: Boolean? = null, @SerializedName("button") val button: BaseLinkButton? = null )
mit
50a9b5e5877c256980781b05bf5c9944
34.716216
81
0.684071
4.242376
false
false
false
false
Mobcase/McImage
src/main/java/com/smallsoho/mcplugin/image/utils/CompressUtil.kt
2
1542
package com.smallsoho.mcplugin.image.utils import java.io.File class CompressUtil { companion object { private const val TAG = "Compress" fun compressImg(imgFile: File) { if (!ImageUtil.isImage(imgFile)) { return } val oldSize = imgFile.length() val newSize: Long if (ImageUtil.isJPG(imgFile)) { val tempFilePath: String = "${imgFile.path.substring(0, imgFile.path.lastIndexOf("."))}_temp" + imgFile.path.substring(imgFile.path.lastIndexOf(".")) Tools.cmd("guetzli", "${imgFile.path} $tempFilePath") val tempFile = File(tempFilePath) newSize = tempFile.length() LogUtil.log("newSize = $newSize") if (newSize < oldSize) { val imgFileName: String = imgFile.path if (imgFile.exists()) { imgFile.delete() } tempFile.renameTo(File(imgFileName)) } else { if (tempFile.exists()) { tempFile.delete() } } } else { Tools.cmd("pngquant", "--skip-if-larger --speed 1 --nofs --strip --force --output ${imgFile.path} -- ${imgFile.path}") newSize = File(imgFile.path).length() } LogUtil.log(TAG, imgFile.path, oldSize.toString(), newSize.toString()) } } }
apache-2.0
65a6a7a7ab759a8874e841a6eafec2e4
34.883721
134
0.485733
4.78882
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/ui/cafeteria/details/CafeteriaDetailsSectionsPagerAdapter.kt
1
1361
package de.tum.`in`.tumcampusapp.component.ui.cafeteria.details import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentStatePagerAdapter import androidx.viewpager.widget.PagerAdapter import org.joda.time.DateTime import org.joda.time.format.DateTimeFormat import org.joda.time.format.DateTimeFormatter import java.util.* import kotlin.collections.ArrayList /** * A [FragmentStatePagerAdapter] that returns a fragment corresponding to one * of the sections/tabs/pages. */ class CafeteriaDetailsSectionsPagerAdapter(fragmentManager: FragmentManager) : FragmentStatePagerAdapter(fragmentManager) { private var cafeteriaId: Int = 0 private var dates: List<DateTime> = ArrayList() private val formatter: DateTimeFormatter = DateTimeFormat.fullDate() fun setCafeteriaId(cafeteriaId: Int) { this.cafeteriaId = cafeteriaId } fun update(menuDates: List<DateTime>) { dates = menuDates notifyDataSetChanged() } override fun getCount() = dates.size override fun getItem(position: Int) = CafeteriaDetailsSectionFragment.newInstance(cafeteriaId, dates[position]) override fun getPageTitle(position: Int) = formatter.print(dates[position]).toUpperCase(Locale.getDefault()) override fun getItemPosition(`object`: Any): Int = PagerAdapter.POSITION_NONE }
gpl-3.0
6938207fd7a67eefbedeeff9c98bfc6f
33.025
123
0.765614
4.775439
false
false
false
false
kryptnostic/rhizome
src/test/kotlin/com/geekbeast/rhizome/hazelcast/HazelcastMapInMemoryMock.kt
1
9131
package com.geekbeast.rhizome.hazelcast import com.google.common.collect.Maps import com.hazelcast.map.IMap import com.hazelcast.internal.serialization.InternalSerializationService import com.hazelcast.internal.serialization.impl.DefaultSerializationServiceBuilder import com.hazelcast.internal.serialization.impl.SerializationServiceV1 import com.hazelcast.query.Predicate import com.hazelcast.query.impl.CachedQueryEntry import com.hazelcast.query.impl.getters.Extractors import com.kryptnostic.rhizome.pods.hazelcast.SelfRegisteringStreamSerializer import org.mockito.Matchers.* import org.mockito.Mockito import java.util.concurrent.TimeUnit import java.util.concurrent.locks.ReentrantLock private val _ss = DefaultSerializationServiceBuilder().build() private val registered = mutableSetOf<Class<*>>() private val registrationLock = ReentrantLock() /** * Mocks a hazelcast using a concurrent map. It implements put,putIfAbsent, get,set, and [] operator. * * If additional functionality is required regular mockito mocking behavior applies. * * @param keyClass A reference to the class of the key used for the map * @param valueClass A reference to the class of the value used for the map * @return A mocked IMap backed by a concurrent map. */ fun <K, V> mockHazelcastMap( keyClass: Class<K>, valueClass: Class<V>, streamSerializers: List<SelfRegisteringStreamSerializer<*>> = listOf(), ss: InternalSerializationService = _ss, extractors: Extractors = Extractors.newBuilder(ss).setAttributeConfigs(listOf()).setClassLoader(keyClass.classLoader).build() ): IMap<K, V> { val mock = Mockito.mock<IMap<*, *>>(IMap::class.java) as IMap<K, V> val backingMap = Maps.newConcurrentMap<K, V>() val ttlMap = Maps.newConcurrentMap<K, Long>() val idleMap = Maps.newConcurrentMap<K, IdleInfo>() // val ssMap = streamSerializers.associateBy { it.clazz } // val keyStreamSerializer = getSerializers(ssMap, keyClass) // val valueStreamSerializer = getSerializers(ssMap, valueClass) if (ss is SerializationServiceV1) { try { registrationLock.lock() streamSerializers.forEach { if (!registered.contains(it.clazz)) { ss.register(it.clazz, it) registered.add(it.clazz) } } } finally { registrationLock.unlock() } } Mockito.`when`(mock.put(any(keyClass), any(valueClass))).thenAnswer { val k = it.arguments[0] as K val v = it.arguments[1] as V backingMap.put(k, v) } Mockito.`when`(mock.putIfAbsent(any(keyClass), any(valueClass))).thenAnswer { val k = it.arguments[0] as K val v = it.arguments[1] as V handleExpiration(k, backingMap, ttlMap) handleIdleness(k, backingMap, ttlMap, idleMap) backingMap.putIfAbsent(k, v) } Mockito.`when`( mock.putIfAbsent( any(keyClass), any(valueClass), anyLong(), any(TimeUnit::class.java), anyLong(), any(TimeUnit::class.java) ) ).thenAnswer { val k = it.arguments[0] as K val v = it.arguments[1] as V val ttlUnit = it.arguments[3] as TimeUnit val ttl = ttlUnit.toNanos(it.arguments[2] as Long) val maxIdleTimeUnit = it.arguments[5] as TimeUnit val maxIdleTime = maxIdleTimeUnit.toNanos(it.arguments[4] as Long) val currentNanos = System.nanoTime() //Only start tracking if ttl or maxIdleTime are positive if (ttl > 0) ttlMap[k] = currentNanos + ttl if (maxIdleTime > 0) idleMap[k] = IdleInfo(maxIdleTime, currentNanos + maxIdleTime) backingMap.putIfAbsent(k, v) } Mockito.`when`(mock.set(any(keyClass), any(valueClass))).thenAnswer { val k = it.arguments[0] as K val v = it.arguments[1] as V handleIdleness(k, backingMap, ttlMap, idleMap) backingMap[k] = v Unit } Mockito.`when`(mock.getAll(anySetOf(keyClass))).thenAnswer { invocation -> val keys = invocation.arguments[0] as Set<K> keys.forEach { k -> handleExpiration(k, backingMap, ttlMap) handleIdleness(k, backingMap, ttlMap, idleMap) } keys.associateWith { backingMap[it] } } Mockito.`when`(mock.get(any(keyClass))).thenAnswer { val k = it.arguments[0] as K handleExpiration(k, backingMap, ttlMap) handleIdleness(k, backingMap, ttlMap, idleMap) backingMap[k] } Mockito.`when`(mock.delete(any())).thenAnswer { val k = it.arguments[0] as K backingMap.remove(k) Unit } Mockito.`when`(mock.remove(any(keyClass))).thenAnswer { val k = it.arguments[0] as K handleExpiration(k, backingMap, ttlMap) handleIdleness(k, backingMap, ttlMap, idleMap) backingMap.remove(k) } Mockito.`when`(mock.entrySet(any())).thenAnswer { invocation -> val p = invocation.arguments[0] as Predicate<K, V> handleExpiration(backingMap, ttlMap) handleIdleness(backingMap, ttlMap, idleMap) backingMap.asSequence() .map { CachedQueryEntry<K, V>(ss, ss.toData(it.component1()), it.component2(), extractors) } .filter(p::apply) .toSet() } Mockito.`when`(mock.keySet(any())).thenAnswer { it -> val p = it.arguments[0] as Predicate<K, V> handleExpiration(backingMap, ttlMap) handleIdleness(backingMap, ttlMap, idleMap) backingMap.asSequence() .map { CachedQueryEntry<K, V>(ss, ss.toData(it.component1()), it.component2(), extractors) } .filter(p::apply) .map { entry -> entry.component1() } .toSet() } Mockito.`when`(mock.values(any())).thenAnswer { it -> val p = it.arguments[0] as Predicate<K, V> handleExpiration(backingMap, ttlMap) handleIdleness(backingMap, ttlMap, idleMap) backingMap.asSequence() .map { CachedQueryEntry<K, V>(ss, ss.toData(it.component1()), it.component2(), extractors) } .filter(p::apply) .map { entry -> entry.component1() } .toList() } val mockCast = mock as Map<K,V> Mockito.`when`(mock.entries).thenAnswer { backingMap.entries } Mockito.`when`(mock.keys).thenAnswer { backingMap.keys } Mockito.`when`(mock.values).thenAnswer { backingMap.values } Mockito.`when`(mock.size).thenAnswer { backingMap.size } Mockito.`when`(mockCast.count()).thenAnswer { backingMap.count() } Mockito.`when`(mock.clear()).thenAnswer { backingMap.clear() } return mock } /** * Gets the correct stream serializer by first trying a lookup and then a linear search if that fails. * @param streamSerializers The map of stream serializers. * @param clazz The class for which a serializer is desired. */ private fun getSerializers( streamSerializers: Map<Class<*>, SelfRegisteringStreamSerializer<*>>, clazz: Class<*> ) = streamSerializers[clazz] ?: streamSerializers.getValue(streamSerializers.keys.first { it.isAssignableFrom(clazz) }) private fun <K, V> handleExpiration(backingMap: MutableMap<K, V>, expirationMap: MutableMap<K, Long>) { backingMap.keys -= expirationMap.filterValues { it <= System.nanoTime() }.keys } private fun <K, V> handleIdleness( k: K, backingMap: MutableMap<K, V>, ttlMap: MutableMap<K, Long>, idleMap: MutableMap<K, IdleInfo> ) { val idleInfo = idleMap[k] if (idleInfo != null) { if (idleInfo.expirationNanos > System.nanoTime()) { //Mark data as not idle. idleInfo.markNotIdle() } else { //Expire data from the maps backingMap.remove(k) idleMap.remove(k) ttlMap.remove(k) } } } private fun <K, V> handleIdleness( backingMap: MutableMap<K, V>, ttlMap: MutableMap<K, Long>, idleMap: MutableMap<K, IdleInfo> ) { idleMap.forEach { (k, idleInfo) -> val idleInfo = idleMap[k] if (idleInfo != null) { if (idleInfo.expirationNanos > System.nanoTime()) { //Mark data as not idle. idleInfo.markNotIdle() } else { //Expire data from the maps backingMap.remove(k) idleMap.remove(k) ttlMap.remove(k) } } } } private fun <K, V> handleExpiration(k: K, backingMap: MutableMap<K, V>, ttlMap: MutableMap<K, Long>) { val expiration = ttlMap[k] if (expiration != null && expiration <= System.nanoTime()) { backingMap.remove(k) ttlMap.remove(k) } } /** * Not meant to be used externally. */ private data class IdleInfo(val maxIdleNanos: Long, var expirationNanos: Long) { fun markNotIdle() { expirationNanos = System.nanoTime() + maxIdleNanos } }
apache-2.0
d8b81ca4d952e9f7e492f7a794eecd54
34.952756
133
0.626875
3.990822
false
false
false
false
laurentvdl/sqlbuilder
src/main/kotlin/sqlbuilder/impl/UpdateImpl.kt
1
7628
package sqlbuilder.impl import org.slf4j.LoggerFactory import sqlbuilder.Backend import sqlbuilder.IncorrectMetadataException import sqlbuilder.IncorrectResultSizeException import sqlbuilder.PersistenceException import sqlbuilder.SqlConverter import sqlbuilder.Update import sqlbuilder.exceptions.IntegrityConstraintViolationException import sqlbuilder.exclude import sqlbuilder.include import sqlbuilder.meta.PropertyReference import java.sql.PreparedStatement import java.sql.SQLException import java.sql.SQLIntegrityConstraintViolationException import java.sql.Statement import java.util.Arrays /** * Update statement: pass in a bean or run a custom statement * * @author Laurent Van der Linden */ class UpdateImpl(private val backend: Backend): Update { private val logger = LoggerFactory.getLogger(javaClass) private val metaResolver = backend.metaResolver private var entity: String? = null private var checkNullability = false private var getkeys = false private var generatedKeys: Array<out String>? = null private var includeFields: Set<String>? = null private var excludeFields: Set<String>? = null private var _generatedKey: Long = 0 override fun entity(entity: String): Update { this.entity = entity return this } override fun checkNullability(check: Boolean): Update { checkNullability = check return this } override fun updateBean(bean: Any) { val keys = metaResolver.getKeys(bean.javaClass) updateBean(bean, keys.map(PropertyReference::columnName).toTypedArray()) } override fun updateBean(bean: Any, keys: Array<out String>) { val keySet = keys.toSet() if (entity == null) entity = metaResolver.getTableName(bean.javaClass) entity = backend.configuration.escapeEntity(entity) if (keys.isEmpty()) { throw IncorrectMetadataException("cannot update bean without a list of keys") } val sqlCon = backend.getSqlConnection() try { val getters = metaResolver.getProperties(bean.javaClass, false) .exclude(excludeFields) .include(includeFields?.union(keySet)) val sql = StringBuilder("update ").append(entity).append(" set ") val valueProperties = getters.filter { !keys.contains(it.columnName) } val keyProperties = getters.filter { keys.contains(it.columnName) } valueProperties.joinTo(sql, ",") { "${it.columnName} = ?" } sql.append(" where ") keyProperties.joinTo(sql, " and ") { "${it.columnName} = ?" } val sqlString = sql.toString() logger.info(sqlString) val sqlConverter = SqlConverter(backend.configuration) try { if (checkNullability) { backend.checkNullability(entity!!, bean, sqlCon, getters) } var updates = 0 sqlCon.prepareStatement(sqlString)!!.use { ps: PreparedStatement -> for ((index, getter) in valueProperties.withIndex()) { try { sqlConverter.setParameter(ps, getter.get(bean), index + 1, getter.classType, null) } catch (e: IllegalArgumentException) { throw PersistenceException("unable to get " + getter.name, e) } } for ((index, getter) in keyProperties.withIndex()) { sqlConverter.setParameter(ps, getter.get(bean), valueProperties.size + index + 1, getter.classType, null) } updates = ps.executeUpdate() } if (updates != 1) { throw PersistenceException("updateBean resulted in $updates updated rows instead of 1 using <$sql> with bean $bean") } } catch (sqlix: SQLIntegrityConstraintViolationException) { throw IntegrityConstraintViolationException("update <$sql> failed due to integrity constraint", sqlix) } catch (sqlx: SQLException) { throw PersistenceException("update <$sql> failed", sqlx) } } finally { backend.closeConnection(sqlCon) } } override fun updateStatement(sql: String): Int { return updateStatement(sql, null, null) } override fun updateStatement(sql: String, vararg parameters: Any?): Int { return updateStatement(sql, parameters, null) } override fun updateStatement(sql: String, parameters: Array<out Any?>?, types: IntArray?): Int { logger.info(sql) val sqlConverter = SqlConverter(backend.configuration) val connection = backend.getSqlConnection() try { val autoGeneratedKeys = if (getkeys) Statement.RETURN_GENERATED_KEYS else Statement.NO_GENERATED_KEYS val preparedStatement = if (generatedKeys != null) connection.prepareStatement(sql, generatedKeys) else connection.prepareStatement(sql, autoGeneratedKeys) return preparedStatement.use { ps -> if (parameters != null) { for ((index, parameter) in parameters.withIndex()) { val parameterType = if (types == null) null else types[index] sqlConverter.setParameter(ps, parameter, index + 1, null, parameterType) } } val rows = ps.executeUpdate() _generatedKey = 0 if (getkeys || generatedKeys != null) { try { val keys = ps.generatedKeys if (keys != null) { if (keys.next()) { _generatedKey = keys.getLong(1) } keys.close() } } catch (ignore: AbstractMethodError) { } catch (sqlx: SQLException) { throw PersistenceException("unable to retrieve generated keys", sqlx) } } rows } } catch (e: Exception) { throw PersistenceException("update <$sql> failed with parameters ${Arrays.toString(parameters)}", e) } finally { backend.closeConnection(connection) } } override fun updateStatementExpecting(sql: String, expectedUpdateCount: Int, vararg parameters: Any?): Int { val updates = updateStatement(sql, parameters, null) if (updates != expectedUpdateCount) { val errorBuilder = StringBuilder("expected $expectedUpdateCount rows to be updated, but $updates rows were ($sql [") parameters.joinTo(errorBuilder, ",") errorBuilder.append("])") throw IncorrectResultSizeException(errorBuilder.toString()) } return updates } override fun getKeys(cond: Boolean): Update { this.getkeys = cond return this } override fun getKeys(vararg keys: String): Update { this.generatedKeys = keys return this } override fun excludeFields(vararg excludes: String): Update { this.excludeFields = excludes.toSet() return this } override fun includeFields(vararg includes: String): Update { this.includeFields = includes.toSet() return this } override fun getGeneratedKey(): Long = _generatedKey }
apache-2.0
b00729acb6fe1b1918931a7023711986
35.855072
167
0.599109
5.231824
false
false
false
false
jiaminglu/kotlin-native
Interop/StubGenerator/src/main/kotlin/org/jetbrains/kotlin/native/interop/gen/Mappings.kt
1
14394
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.native.interop.gen import org.jetbrains.kotlin.native.interop.indexer.* interface DeclarationMapper { fun getKotlinClassForPointed(structDecl: StructDecl): Classifier fun isMappedToStrict(enumDef: EnumDef): Boolean fun getKotlinNameForValue(enumDef: EnumDef): String fun getPackageFor(declaration: TypeDeclaration): String } fun DeclarationMapper.getKotlinClassFor( objCClassOrProtocol: ObjCClassOrProtocol, isMeta: Boolean = false ): Classifier { val pkg = if (objCClassOrProtocol.shouldBeImportedAsForwardDeclaration()) { when (objCClassOrProtocol) { is ObjCClass -> "objcnames.classes" is ObjCProtocol -> "objcnames.protocols" } } else { this.getPackageFor(objCClassOrProtocol) } val className = objCClassOrProtocol.kotlinClassName(isMeta) return Classifier.topLevel(pkg, className) } val PrimitiveType.kotlinType: KotlinClassifierType get() = when (this) { is CharType -> KotlinTypes.byte is BoolType -> KotlinTypes.boolean // TODO: C primitive types should probably be generated as type aliases for Kotlin types. is IntegerType -> when (this.size) { 1 -> KotlinTypes.byte 2 -> KotlinTypes.short 4 -> KotlinTypes.int 8 -> KotlinTypes.long else -> TODO(this.toString()) } is FloatingType -> when (this.size) { 4 -> KotlinTypes.float 8 -> KotlinTypes.double else -> TODO(this.toString()) } else -> throw NotImplementedError() } private val PrimitiveType.bridgedType: BridgedType get() { val kotlinType = this.kotlinType return BridgedType.values().single { it.kotlinType == kotlinType } } private val ObjCPointer.isNullable: Boolean get() = this.nullability != ObjCPointer.Nullability.NonNull /** * Describes the Kotlin types used to represent some C type. */ sealed class TypeMirror(val pointedType: KotlinClassifierType, val info: TypeInfo) { /** * Type to be used in bindings for argument or return value. */ abstract val argType: KotlinType /** * Mirror for C type to be represented in Kotlin as by-value type. */ class ByValue(pointedType: KotlinClassifierType, info: TypeInfo, val valueType: KotlinClassifierType) : TypeMirror(pointedType, info) { override val argType: KotlinType get() = if ((info is TypeInfo.Pointer || (info is TypeInfo.ObjCPointerInfo && info.type.isNullable))) { valueType.makeNullable() } else { valueType } } /** * Mirror for C type to be represented in Kotlin as by-ref type. */ class ByRef(pointedType: KotlinClassifierType, info: TypeInfo) : TypeMirror(pointedType, info) { override val argType: KotlinType get() = KotlinTypes.cValue.typeWith(pointedType) } } /** * Describes various type conversions for [TypeMirror]. */ sealed class TypeInfo { /** * The conversion from [TypeMirror.argType] to [bridgedType]. */ abstract fun argToBridged(expr: KotlinExpression): KotlinExpression /** * The conversion from [bridgedType] to [TypeMirror.argType]. */ abstract fun argFromBridged(expr: KotlinExpression, scope: KotlinScope): KotlinExpression abstract val bridgedType: BridgedType open fun cFromBridged(expr: NativeExpression): NativeExpression = expr open fun cToBridged(expr: NativeExpression): NativeExpression = expr /** * If this info is for [TypeMirror.ByValue], then this method describes how to * construct pointed-type from value type. */ abstract fun constructPointedType(valueType: KotlinType): KotlinClassifierType class Primitive(override val bridgedType: BridgedType, val varClass: Classifier) : TypeInfo() { override fun argToBridged(expr: KotlinExpression) = expr override fun argFromBridged(expr: KotlinExpression, scope: KotlinScope) = expr override fun constructPointedType(valueType: KotlinType) = varClass.typeWith(valueType) } class Boolean : TypeInfo() { override fun argToBridged(expr: KotlinExpression) = "$expr.toByte()" override fun argFromBridged(expr: KotlinExpression, scope: KotlinScope) = "$expr.toBoolean()" override val bridgedType: BridgedType get() = BridgedType.BYTE override fun cFromBridged(expr: NativeExpression) = "($expr) ? 1 : 0" override fun cToBridged(expr: NativeExpression) = "($expr) ? 1 : 0" override fun constructPointedType(valueType: KotlinType) = KotlinTypes.booleanVarOf.typeWith(valueType) } class Enum(val clazz: Classifier, override val bridgedType: BridgedType) : TypeInfo() { override fun argToBridged(expr: KotlinExpression) = "$expr.value" override fun argFromBridged(expr: KotlinExpression, scope: KotlinScope) = scope.reference(clazz) + ".byValue($expr)" override fun constructPointedType(valueType: KotlinType) = clazz.nested("Var").type // TODO: improve } class Pointer(val pointee: KotlinType) : TypeInfo() { override fun argToBridged(expr: String) = "$expr.rawValue" override fun argFromBridged(expr: KotlinExpression, scope: KotlinScope) = "interpretCPointer<${pointee.render(scope)}>($expr)" override val bridgedType: BridgedType get() = BridgedType.NATIVE_PTR override fun cFromBridged(expr: String) = "(void*)$expr" // Note: required for JVM override fun constructPointedType(valueType: KotlinType) = KotlinTypes.cPointerVarOf.typeWith(valueType) } class ObjCPointerInfo(val kotlinType: KotlinType, val type: ObjCPointer) : TypeInfo() { override fun argToBridged(expr: String) = "$expr.rawPtr" override fun argFromBridged(expr: KotlinExpression, scope: KotlinScope) = "interpretObjCPointerOrNull<${kotlinType.render(scope)}>($expr)" + if (type.isNullable) "" else "!!" override val bridgedType: BridgedType get() = BridgedType.OBJC_POINTER override fun constructPointedType(valueType: KotlinType) = KotlinTypes.objCObjectVar.typeWith(valueType) } class NSString(val type: ObjCPointer) : TypeInfo() { override fun argToBridged(expr: String) = "CreateNSStringFromKString($expr)" override fun argFromBridged(expr: KotlinExpression, scope: KotlinScope) = "CreateKStringFromNSString($expr)" + if (type.isNullable) "" else "!!" override val bridgedType: BridgedType get() = BridgedType.OBJC_POINTER override fun constructPointedType(valueType: KotlinType): KotlinClassifierType { return KotlinTypes.objCStringVarOf.typeWith(valueType) } } class ByRef(val pointed: KotlinType) : TypeInfo() { override fun argToBridged(expr: String) = error(pointed) override fun argFromBridged(expr: KotlinExpression, scope: KotlinScope) = error(pointed) override val bridgedType: BridgedType get() = error(pointed) override fun cFromBridged(expr: String) = error(pointed) override fun cToBridged(expr: String) = error(pointed) // TODO: this method must not exist override fun constructPointedType(valueType: KotlinType): KotlinClassifierType = error(pointed) } } fun mirrorPrimitiveType(type: PrimitiveType): TypeMirror.ByValue { val varClassName = when (type) { is CharType -> "ByteVar" is BoolType -> "BooleanVar" is IntegerType -> when (type.size) { 1 -> "ByteVar" 2 -> "ShortVar" 4 -> "IntVar" 8 -> "LongVar" else -> TODO(type.toString()) } is FloatingType -> when (type.size) { 4 -> "FloatVar" 8 -> "DoubleVar" else -> TODO(type.toString()) } else -> TODO(type.toString()) } val varClass = Classifier.topLevel("kotlinx.cinterop", varClassName) val varClassOf = Classifier.topLevel("kotlinx.cinterop", "${varClassName}Of") val info = if (type == BoolType) { TypeInfo.Boolean() } else { TypeInfo.Primitive(type.bridgedType, varClassOf) } return TypeMirror.ByValue(varClass.type, info, type.kotlinType) } private fun byRefTypeMirror(pointedType: KotlinClassifierType) : TypeMirror.ByRef { val info = TypeInfo.ByRef(pointedType) return TypeMirror.ByRef(pointedType, info) } fun mirror(declarationMapper: DeclarationMapper, type: Type): TypeMirror = when (type) { is PrimitiveType -> mirrorPrimitiveType(type) is RecordType -> byRefTypeMirror(declarationMapper.getKotlinClassForPointed(type.decl).type) is EnumType -> { val pkg = declarationMapper.getPackageFor(type.def) val kotlinName = declarationMapper.getKotlinNameForValue(type.def) when { declarationMapper.isMappedToStrict(type.def) -> { val bridgedType = (type.def.baseType.unwrapTypedefs() as PrimitiveType).bridgedType val clazz = Classifier.topLevel(pkg, kotlinName) val info = TypeInfo.Enum(clazz, bridgedType) TypeMirror.ByValue(clazz.nested("Var").type, info, clazz.type) } !type.def.isAnonymous -> { val baseTypeMirror = mirror(declarationMapper, type.def.baseType) TypeMirror.ByValue( Classifier.topLevel(pkg, kotlinName + "Var").type, baseTypeMirror.info, Classifier.topLevel(pkg, kotlinName).type ) } else -> mirror(declarationMapper, type.def.baseType) } } is PointerType -> { val pointeeType = type.pointeeType val unwrappedPointeeType = pointeeType.unwrapTypedefs() if (unwrappedPointeeType is VoidType) { val info = TypeInfo.Pointer(KotlinTypes.cOpaque) TypeMirror.ByValue(KotlinTypes.cOpaquePointerVar, info, KotlinTypes.cOpaquePointer) } else if (unwrappedPointeeType is ArrayType) { mirror(declarationMapper, pointeeType) } else { val pointeeMirror = mirror(declarationMapper, pointeeType) val info = TypeInfo.Pointer(pointeeMirror.pointedType) TypeMirror.ByValue( KotlinTypes.cPointerVar.typeWith(pointeeMirror.pointedType), info, KotlinTypes.cPointer.typeWith(pointeeMirror.pointedType) ) } } is ArrayType -> { // TODO: array type doesn't exactly correspond neither to pointer nor to value. val elemTypeMirror = mirror(declarationMapper, type.elemType) if (type.elemType.unwrapTypedefs() is ArrayType) { elemTypeMirror } else { val info = TypeInfo.Pointer(elemTypeMirror.pointedType) TypeMirror.ByValue( KotlinTypes.cArrayPointerVar.typeWith(elemTypeMirror.pointedType), info, KotlinTypes.cArrayPointer.typeWith(elemTypeMirror.pointedType) ) } } is FunctionType -> byRefTypeMirror(KotlinTypes.cFunction.typeWith(getKotlinFunctionType(declarationMapper, type))) is Typedef -> { val baseType = mirror(declarationMapper, type.def.aliased) val pkg = declarationMapper.getPackageFor(type.def) val name = type.def.name when (baseType) { is TypeMirror.ByValue -> TypeMirror.ByValue( Classifier.topLevel(pkg, "${name}Var").type, baseType.info, Classifier.topLevel(pkg, name).type ) is TypeMirror.ByRef -> TypeMirror.ByRef(Classifier.topLevel(pkg, name).type, baseType.info) } } is ObjCPointer -> objCPointerMirror(declarationMapper, type) else -> TODO(type.toString()) } private fun objCPointerMirror(declarationMapper: DeclarationMapper, type: ObjCPointer): TypeMirror.ByValue { if (type is ObjCObjectPointer && type.def.name == "NSString") { val info = TypeInfo.NSString(type) val valueType = KotlinTypes.string.makeNullableAsSpecified(type.isNullable) return TypeMirror.ByValue(info.constructPointedType(valueType), info, valueType) } val clazz = when (type) { is ObjCIdType -> type.protocols.firstOrNull()?.let { declarationMapper.getKotlinClassFor(it) } ?: KotlinTypes.objCObject is ObjCClassPointer -> KotlinTypes.objCClass is ObjCObjectPointer -> declarationMapper.getKotlinClassFor(type.def) is ObjCInstanceType -> TODO(type.toString()) // Must have already been handled. } return objCPointerMirror(clazz, type) } private fun objCPointerMirror(clazz: Classifier, type: ObjCPointer): TypeMirror.ByValue { val kotlinType = clazz.type val pointedType = KotlinTypes.objCObjectVar.typeWith(kotlinType.makeNullableAsSpecified(type.isNullable)) return TypeMirror.ByValue( pointedType, TypeInfo.ObjCPointerInfo(kotlinType, type), kotlinType ) } fun getKotlinFunctionType(declarationMapper: DeclarationMapper, type: FunctionType): KotlinFunctionType { val returnType = if (type.returnType.unwrapTypedefs() is VoidType) { KotlinTypes.unit } else { mirror(declarationMapper, type.returnType).argType } return KotlinFunctionType( type.parameterTypes.map { mirror(declarationMapper, it).argType }, returnType ) }
apache-2.0
f551b2a40fd7b433f7afd492d912ab0c
36.680628
118
0.659789
4.682498
false
false
false
false
anurse/advent-of-code
2019/src/main/kotlin/adventofcode/day01/main.kt
1
1077
package adventofcode.day01 import java.io.File fun main(args: Array<String>) { val inputFile = if (args.size < 1) { System.err.println("Usage: adventofcode day01 <INPUT FILE>") System.exit(1) throw Exception("Whoop"); } else { args[0] } solve(File(inputFile).readLines().map(::parseLine)) } fun parseLine(input: String): Int { return input.toInt() } fun solve(input: List<Int>) { val part1Result = input.map(::computeFuel).sum() println("[Part 1] Result: $part1Result"); var part2Result = input.map(::computeAllFuel).sum() println("[Part 2] Result: $part2Result"); } fun computeFuel(mass: Int) = Math.floor(mass.toDouble() / 3.0).toInt() - 2 fun computeAllFuel(currentMass: Int) = computeAllFuel(currentMass, 0) tailrec fun computeAllFuel(currentMass: Int, fuelTotal: Int = 0): Int { val fuelMass = computeFuel(currentMass) if (fuelMass <= 0) { return fuelTotal } else { return computeAllFuel(fuelMass, fuelTotal + fuelMass) } }
apache-2.0
49fad3d3fd912e86162fc3359d440026
25.615385
74
0.625812
3.429936
false
false
false
false
gurleensethi/LiteUtilities
liteutils/src/main/java/com/thetechnocafe/gurleensethi/liteutils/ScrollUtils.kt
1
3235
package com.thetechnocafe.gurleensethi.liteutils import android.support.design.widget.FloatingActionButton import android.support.v4.widget.NestedScrollView import android.support.v7.widget.RecyclerView import android.view.View /** * Created by gurleensethi on 27/07/17. */ interface ScrollListener { fun scrolledDown(); fun scrolledUp(); } /** * Hide/Show the FloatingActionButton when a NestedScrollView is scrolled * @param floatingActionButton to be hidden/shown * */ public fun NestedScrollView.hideFloatingActionButtonOnScroll(floatingActionButton: FloatingActionButton) { setOnScrollChangeListener(object : NestedScrollView.OnScrollChangeListener { override fun onScrollChange(v: NestedScrollView?, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) { //Calculate the y-axis displacement of the scroll val displacementY = scrollY - oldScrollY //According to the displacement hide or show the layout if (displacementY > 0) { floatingActionButton.hide() } else if (displacementY < 0) { floatingActionButton.show() } } }) } /** * Hide/Show callbacks when NestedScrollView is scrolled * @param listener with the required callbacks * */ public fun NestedScrollView.addScrollListener(listener: ScrollListener) { setOnScrollChangeListener(object : NestedScrollView.OnScrollChangeListener { override fun onScrollChange(v: NestedScrollView?, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) { //Calculate the y-axis displacement of the scroll val displacementY = scrollY - oldScrollY //According to the displacement hide or show the layout if (displacementY > 0) { listener.scrolledDown() } else if (displacementY < 0) { listener.scrolledUp() } } }) } /** * Hide/Show the FloatingActionButton when RecyclerView is scrolled * @param floatingActionButton to be hidden/shown * */ public fun RecyclerView.hideFloatingActionButtonOnScroll(floatingActionButton: FloatingActionButton) { setOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) if (dy > 0 && floatingActionButton.visibility == View.VISIBLE) { floatingActionButton.hide() } else if (dy < 0 && floatingActionButton.visibility != View.VISIBLE) { floatingActionButton.show() } } }) } /** * Hide/Show the FloatingActionButton when RecyclerView is scrolled * @param floatingActionButton to be hidden/shown * */ public fun RecyclerView.addScrollListener(listener: ScrollListener) { setOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) if (dy > 0) { listener.scrolledDown() } else if (dy < 0) { listener.scrolledUp() } } }) }
mit
ffd49b25ff904331b5d0fd867e59d15f
34.56044
121
0.66677
4.954058
false
false
false
false
apollostack/apollo-android
apollo-runtime/src/main/java/com/apollographql/apollo3/interceptor/ApolloInterceptor.kt
1
7008
package com.apollographql.apollo3.interceptor import com.apollographql.apollo3.api.Operation import com.apollographql.apollo3.api.internal.Optional import com.apollographql.apollo3.cache.CacheHeaders import com.apollographql.apollo3.cache.normalized.internal.ReadMode import com.apollographql.apollo3.exception.ApolloException import com.apollographql.apollo3.request.RequestHeaders import okhttp3.Response import java.util.UUID import java.util.concurrent.Executor /** * ApolloInterceptor is responsible for observing and modifying the requests going out and the corresponding responses * coming back in. Typical responsibilities include adding or removing headers from the request or response objects, * transforming the returned responses from one type to another, etc. */ interface ApolloInterceptor { /** * Intercepts the outgoing request and performs non blocking operations on the request or the response returned by the * next set of interceptors in the chain. * * @param request outgoing request object. * @param chain the ApolloInterceptorChain object containing the next set of interceptors. * @param dispatcher the Executor which dispatches the non blocking operations on the request/response. * @param callBack the Callback which will handle the interceptor's response or failure exception. */ fun interceptAsync(request: InterceptorRequest, chain: ApolloInterceptorChain, dispatcher: Executor, callBack: CallBack) /** * Disposes of the resources which are no longer required. * * * A use case for this method call would be when an [com.apollographql.apollo3.ApolloCall] needs to be * cancelled and resources need to be disposed of. */ fun dispose() /** * Handles the responses returned by [ApolloInterceptor] */ interface CallBack { /** * Gets called when the interceptor returns a response after successfully performing operations on the * request/response. May be called multiple times. * * @param response The response returned by the interceptor. */ fun onResponse(response: InterceptorResponse) /** * Called when interceptor starts fetching response from source type * * @param sourceType type of source been used to fetch response from */ fun onFetch(sourceType: FetchSourceType) /** * Gets called when an unexpected exception occurs while performing operations on the request or processing the * response returned by the next set of interceptors. Will be called at most once. */ fun onFailure(e: ApolloException) /** * Called after the last call to [.onResponse]. Do not call after [.onFailure]. */ fun onCompleted() } /** * Fetch source type */ enum class FetchSourceType { /** * Response is fetched from the cache (SQLite or memory or both) */ CACHE, /** * Response is fetched from the network */ NETWORK } /** * InterceptorResponse class represents the response returned by the [ApolloInterceptor]. */ class InterceptorResponse @JvmOverloads constructor(httpResponse: Response?, parsedResponse: com.apollographql.apollo3.api.ApolloResponse<*>? = null) { val httpResponse: Optional<Response> @JvmField val parsedResponse: Optional<com.apollographql.apollo3.api.ApolloResponse<*>?> init { this.httpResponse = Optional.fromNullable(httpResponse) this.parsedResponse = Optional.fromNullable(parsedResponse) } } /** * Request to be proceed with [ApolloInterceptor] */ class InterceptorRequest internal constructor(val operation: Operation<*>, val cacheHeaders: CacheHeaders, val requestHeaders: RequestHeaders, val optimisticUpdates: Optional<Operation.Data>, val fetchFromCache: Boolean, val sendQueryDocument: Boolean, val useHttpGetMethodForQueries: Boolean, val autoPersistQueries: Boolean, ) { val uniqueId = UUID.randomUUID() fun toBuilder(): Builder { return Builder(operation) .cacheHeaders(cacheHeaders) .requestHeaders(requestHeaders) .fetchFromCache(fetchFromCache) .optimisticUpdates(optimisticUpdates.orNull()) .sendQueryDocument(sendQueryDocument) .useHttpGetMethodForQueries(useHttpGetMethodForQueries) .autoPersistQueries(autoPersistQueries) } class Builder internal constructor(operation: Operation<*>) { private val operation: Operation<*> private var cacheHeaders = CacheHeaders.NONE private var requestHeaders = RequestHeaders.NONE private var fetchFromCache = false private var optimisticUpdates = Optional.absent<Operation.Data>() private var sendQueryDocument = true private var useHttpGetMethodForQueries = false private var autoPersistQueries = false fun cacheHeaders(cacheHeaders: CacheHeaders): Builder { this.cacheHeaders = cacheHeaders return this } fun requestHeaders(requestHeaders: RequestHeaders): Builder { this.requestHeaders = requestHeaders return this } fun fetchFromCache(fetchFromCache: Boolean): Builder { this.fetchFromCache = fetchFromCache return this } fun optimisticUpdates(optimisticUpdates: Operation.Data?): Builder { this.optimisticUpdates = Optional.fromNullable(optimisticUpdates) return this } fun optimisticUpdates(optimisticUpdates: Optional<Operation.Data>): Builder { this.optimisticUpdates = optimisticUpdates return this } fun sendQueryDocument(sendQueryDocument: Boolean): Builder { this.sendQueryDocument = sendQueryDocument return this } fun useHttpGetMethodForQueries(useHttpGetMethodForQueries: Boolean): Builder { this.useHttpGetMethodForQueries = useHttpGetMethodForQueries return this } fun autoPersistQueries(autoPersistQueries: Boolean): Builder { this.autoPersistQueries = autoPersistQueries return this } fun build(): InterceptorRequest { return InterceptorRequest( operation, cacheHeaders, requestHeaders, optimisticUpdates, fetchFromCache, sendQueryDocument, useHttpGetMethodForQueries, autoPersistQueries, ) } init { this.operation = operation } } companion object { @JvmStatic fun builder(operation: Operation<*>): Builder { return Builder(operation) } } } }
mit
0cbaf6bebce5348746562fa73b4ad318
34.39899
153
0.667523
5.445221
false
false
false
false
MaTriXy/material-dialogs
color/src/main/java/com/afollestad/materialdialogs/color/view/ColorCircleView.kt
2
3116
/** * 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.graphics.Canvas import android.graphics.Color import android.graphics.Color.TRANSPARENT import android.graphics.Paint import android.graphics.Paint.Style.FILL import android.graphics.Paint.Style.STROKE import android.graphics.drawable.Drawable import android.util.AttributeSet import android.view.View import androidx.annotation.ColorInt import androidx.core.content.ContextCompat.getDrawable import com.afollestad.materialdialogs.color.R.dimen import com.afollestad.materialdialogs.color.R.drawable import com.afollestad.materialdialogs.utils.MDUtil.dimenPx /** @author Aidan Follestad (afollestad) */ internal class ColorCircleView( context: Context, attrs: AttributeSet? = null ) : View(context, attrs) { private val strokePaint = Paint() private val fillPaint = Paint() private val borderWidth = dimenPx( dimen.color_circle_view_border ) private var transparentGrid: Drawable? = null init { setWillNotDraw(false) strokePaint.style = STROKE strokePaint.isAntiAlias = true strokePaint.color = Color.BLACK strokePaint.strokeWidth = borderWidth.toFloat() fillPaint.style = FILL fillPaint.isAntiAlias = true fillPaint.color = Color.DKGRAY } @ColorInt var color: Int = Color.BLACK set(value) { field = value fillPaint.color = value invalidate() } @ColorInt var border: Int = Color.DKGRAY set(value) { field = value strokePaint.color = value invalidate() } override fun onMeasure( widthMeasureSpec: Int, heightMeasureSpec: Int ) = super.onMeasure(widthMeasureSpec, widthMeasureSpec) override fun onDraw(canvas: Canvas) { super.onDraw(canvas) if (color == TRANSPARENT) { if (transparentGrid == null) { transparentGrid = getDrawable(context, drawable.transparentgrid ) } transparentGrid?.setBounds(0, 0, measuredWidth, measuredHeight) transparentGrid?.draw(canvas) } else { canvas.drawCircle( measuredWidth / 2f, measuredHeight / 2f, (measuredWidth / 2f) - borderWidth, fillPaint ) } canvas.drawCircle( measuredWidth / 2f, measuredHeight / 2f, (measuredWidth / 2f) - borderWidth, strokePaint ) } override fun onDetachedFromWindow() { super.onDetachedFromWindow() transparentGrid = null } }
apache-2.0
4cccae6194228a9f5eb020a5b605ac88
27.851852
75
0.710205
4.477011
false
false
false
false
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt
1
49687
package info.nightscout.androidaps.plugins.general.nsclient import info.nightscout.androidaps.R import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.ValueWrapper import info.nightscout.androidaps.database.entities.* import info.nightscout.androidaps.extensions.toJson import info.nightscout.androidaps.interfaces.ActivePlugin import info.nightscout.androidaps.interfaces.DataSyncSelector import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin import info.nightscout.androidaps.utils.DateUtil import info.nightscout.shared.sharedPreferences.SP import javax.inject.Inject import javax.inject.Singleton @Singleton class DataSyncSelectorImplementation @Inject constructor( private val sp: SP, private val aapsLogger: AAPSLogger, private val dateUtil: DateUtil, private val profileFunction: ProfileFunction, private val nsClientPlugin: NSClientPlugin, private val activePlugin: ActivePlugin, private val appRepository: AppRepository, private val localProfilePlugin: LocalProfilePlugin ) : DataSyncSelector { class QueueCounter( var bolusesRemaining: Long = -1L, var carbsRemaining: Long = -1L, var bcrRemaining: Long = -1L, var ttsRemaining: Long = -1L, var foodsRemaining: Long = -1L, var gvsRemaining: Long = -1L, var tesRemaining: Long = -1L, var dssRemaining: Long = -1L, var tbrsRemaining: Long = -1L, var ebsRemaining: Long = -1L, var pssRemaining: Long = -1L, var epssRemaining: Long = -1L, var oesRemaining: Long = -1L ) { fun size(): Long = bolusesRemaining + carbsRemaining + bcrRemaining + ttsRemaining + foodsRemaining + gvsRemaining + tesRemaining + dssRemaining + tbrsRemaining + ebsRemaining + pssRemaining + epssRemaining + oesRemaining } private val queueCounter = QueueCounter() override fun queueSize(): Long = queueCounter.size() override fun doUpload() { if (sp.getBoolean(R.string.key_ns_upload, true)) { processChangedBolusesCompat() processChangedCarbsCompat() processChangedBolusCalculatorResultsCompat() processChangedTemporaryBasalsCompat() processChangedExtendedBolusesCompat() processChangedProfileSwitchesCompat() processChangedEffectiveProfileSwitchesCompat() processChangedGlucoseValuesCompat() processChangedTempTargetsCompat() processChangedFoodsCompat() processChangedTherapyEventsCompat() processChangedDeviceStatusesCompat() processChangedOfflineEventsCompat() processChangedProfileStore() } } override fun resetToNextFullSync() { appRepository.getLastGlucoseValueIdWrapped().blockingGet().run { val currentLast = if (this is ValueWrapper.Existing) this.value else 0L sp.putLong(R.string.key_ns_glucose_value_new_data_id, currentLast) } sp.remove(R.string.key_ns_glucose_value_last_synced_id) appRepository.getLastTemporaryBasalIdWrapped().blockingGet().run { val currentLast = if (this is ValueWrapper.Existing) this.value else 0L sp.putLong(R.string.key_ns_temporary_basal_new_data_id, currentLast) } sp.remove(R.string.key_ns_temporary_basal_last_synced_id) appRepository.getLastTempTargetIdWrapped().blockingGet().run { val currentLast = if (this is ValueWrapper.Existing) this.value else 0L sp.putLong(R.string.key_ns_temporary_target_new_data_id, currentLast) } sp.remove(R.string.key_ns_temporary_target_last_synced_id) appRepository.getLastExtendedBolusIdWrapped().blockingGet().run { val currentLast = if (this is ValueWrapper.Existing) this.value else 0L sp.putLong(R.string.key_ns_extended_bolus_new_data_id, currentLast) } sp.remove(R.string.key_ns_extended_bolus_last_synced_id) sp.remove(R.string.key_ns_food_last_synced_id) sp.remove(R.string.key_ns_bolus_last_synced_id) sp.remove(R.string.key_ns_carbs_last_synced_id) sp.remove(R.string.key_ns_bolus_calculator_result_last_synced_id) sp.remove(R.string.key_ns_therapy_event_last_synced_id) sp.remove(R.string.key_ns_profile_switch_last_synced_id) sp.remove(R.string.key_ns_effective_profile_switch_last_synced_id) sp.remove(R.string.key_ns_offline_event_last_synced_id) sp.remove(R.string.key_ns_profile_store_last_synced_timestamp) val lastDeviceStatusDbIdWrapped = appRepository.getLastDeviceStatusIdWrapped().blockingGet() if (lastDeviceStatusDbIdWrapped is ValueWrapper.Existing) sp.putLong(R.string.key_ns_device_status_last_synced_id, lastDeviceStatusDbIdWrapped.value) else sp.remove(R.string.key_ns_device_status_last_synced_id) } override fun confirmLastBolusIdIfGreater(lastSynced: Long) { if (lastSynced > sp.getLong(R.string.key_ns_bolus_last_synced_id, 0)) { aapsLogger.debug(LTag.NSCLIENT, "Setting Bolus data sync from $lastSynced") sp.putLong(R.string.key_ns_bolus_last_synced_id, lastSynced) } } // Prepared for v3 (returns all modified after) override fun changedBoluses(): List<Bolus> { val startId = sp.getLong(R.string.key_ns_bolus_last_synced_id, 0) return appRepository.getModifiedBolusesDataFromId(startId) .blockingGet() .filter { it.type != Bolus.Type.PRIMING } .also { aapsLogger.debug(LTag.NSCLIENT, "Loading Bolus data for sync from $startId. Records ${it.size}") } } //private var lastBolusId = -1L //private var lastBolusTime = -1L override fun processChangedBolusesCompat(): Boolean { val lastDbIdWrapped = appRepository.getLastBolusIdWrapped().blockingGet() val lastDbId = if (lastDbIdWrapped is ValueWrapper.Existing) lastDbIdWrapped.value else 0L var startId = sp.getLong(R.string.key_ns_bolus_last_synced_id, 0) if (startId > lastDbId) { sp.putLong(R.string.key_ns_bolus_last_synced_id, 0) startId = 0 } //if (startId == lastBolusId && dateUtil.now() - lastBolusTime < 5000) return false //lastBolusId = startId //lastBolusTime = dateUtil.now() queueCounter.bolusesRemaining = lastDbId - startId appRepository.getNextSyncElementBolus(startId).blockingGet()?.let { bolus -> aapsLogger.info(LTag.NSCLIENT, "Loading Bolus data Start: $startId ID: ${bolus.first.id} HistoryID: ${bolus.second.id} ") when { // only NsId changed, no need to upload bolus.first.onlyNsIdAdded(bolus.second) -> { confirmLastBolusIdIfGreater(bolus.second.id) //lastBolusId = -1 processChangedBolusesCompat() aapsLogger.info(LTag.NSCLIENT, "Ignoring Bolus. Only NS id changed ID: ${bolus.first.id} HistoryID: ${bolus.second.id} ") return false } // without nsId = create new bolus.first.interfaceIDs.nightscoutId == null -> nsClientPlugin.nsClientService?.dbAdd("treatments", bolus.first.toJson(true, dateUtil), DataSyncSelector.PairBolus(bolus.first, bolus.second.id), "$startId/$lastDbId") // with nsId = update bolus.first.interfaceIDs.nightscoutId != null -> nsClientPlugin.nsClientService?.dbUpdate( "treatments", bolus.first.interfaceIDs.nightscoutId, bolus.first.toJson(false, dateUtil), DataSyncSelector.PairBolus(bolus.first, bolus.second.id), "$startId/$lastDbId" ) } return true } return false } override fun confirmLastCarbsIdIfGreater(lastSynced: Long) { if (lastSynced > sp.getLong(R.string.key_ns_carbs_last_synced_id, 0)) { aapsLogger.debug(LTag.NSCLIENT, "Setting Carbs data sync from $lastSynced") sp.putLong(R.string.key_ns_carbs_last_synced_id, lastSynced) } } // Prepared for v3 (returns all modified after) override fun changedCarbs(): List<Carbs> { val startId = sp.getLong(R.string.key_ns_carbs_last_synced_id, 0) return appRepository.getModifiedCarbsDataFromId(startId).blockingGet().also { aapsLogger.debug(LTag.NSCLIENT, "Loading Carbs data for sync from $startId. Records ${it.size}") } } //private var lastCarbsId = -1L //private var lastCarbsTime = -1L override fun processChangedCarbsCompat(): Boolean { val lastDbIdWrapped = appRepository.getLastCarbsIdWrapped().blockingGet() val lastDbId = if (lastDbIdWrapped is ValueWrapper.Existing) lastDbIdWrapped.value else 0L var startId = sp.getLong(R.string.key_ns_carbs_last_synced_id, 0) if (startId > lastDbId) { sp.putLong(R.string.key_ns_carbs_last_synced_id, 0) startId = 0 } //if (startId == lastCarbsId && dateUtil.now() - lastCarbsTime < 5000) return false //lastCarbsId = startId //lastCarbsTime = dateUtil.now() queueCounter.carbsRemaining = lastDbId - startId appRepository.getNextSyncElementCarbs(startId).blockingGet()?.let { carb -> aapsLogger.info(LTag.NSCLIENT, "Loading Carbs data Start: $startId ID: ${carb.first.id} HistoryID: ${carb.second.id} ") when { // only NsId changed, no need to upload carb.first.onlyNsIdAdded(carb.second) -> { confirmLastCarbsIdIfGreater(carb.second.id) //lastCarbsId = -1 processChangedCarbsCompat() aapsLogger.info(LTag.NSCLIENT, "Ignoring Carbs. Only NS id changed ID: ${carb.first.id} HistoryID: ${carb.second.id} ") return false } // without nsId = create new carb.first.interfaceIDs.nightscoutId == null -> nsClientPlugin.nsClientService?.dbAdd("treatments", carb.first.toJson(true, dateUtil), DataSyncSelector.PairCarbs(carb.first, carb.second.id), "$startId/$lastDbId") // with nsId = update carb.first.interfaceIDs.nightscoutId != null -> nsClientPlugin.nsClientService?.dbUpdate( "treatments", carb.first.interfaceIDs.nightscoutId, carb.first.toJson(false, dateUtil), DataSyncSelector.PairCarbs(carb.first, carb.second.id), "$startId/$lastDbId" ) } return true } return false } override fun confirmLastBolusCalculatorResultsIdIfGreater(lastSynced: Long) { if (lastSynced > sp.getLong(R.string.key_ns_bolus_calculator_result_last_synced_id, 0)) { aapsLogger.debug(LTag.NSCLIENT, "Setting BolusCalculatorResult data sync from $lastSynced") sp.putLong(R.string.key_ns_bolus_calculator_result_last_synced_id, lastSynced) } } // Prepared for v3 (returns all modified after) override fun changedBolusCalculatorResults(): List<BolusCalculatorResult> { val startId = sp.getLong(R.string.key_ns_bolus_calculator_result_last_synced_id, 0) return appRepository.getModifiedBolusCalculatorResultsDataFromId(startId).blockingGet().also { aapsLogger.debug(LTag.NSCLIENT, "Loading BolusCalculatorResult data for sync from $startId. Records ${it.size}") } } //private var lastBcrId = -1L //private var lastBcrTime = -1L override fun processChangedBolusCalculatorResultsCompat(): Boolean { val lastDbIdWrapped = appRepository.getLastBolusCalculatorResultIdWrapped().blockingGet() val lastDbId = if (lastDbIdWrapped is ValueWrapper.Existing) lastDbIdWrapped.value else 0L var startId = sp.getLong(R.string.key_ns_bolus_calculator_result_last_synced_id, 0) if (startId > lastDbId) { sp.putLong(R.string.key_ns_bolus_calculator_result_last_synced_id, 0) startId = 0 } //if (startId == lastBcrId && dateUtil.now() - lastBcrTime < 5000) return false //lastBcrId = startId //lastBcrTime = dateUtil.now() queueCounter.bcrRemaining = lastDbId - startId appRepository.getNextSyncElementBolusCalculatorResult(startId).blockingGet()?.let { bolusCalculatorResult -> aapsLogger.info(LTag.NSCLIENT, "Loading BolusCalculatorResult data Start: $startId ID: ${bolusCalculatorResult.first.id} HistoryID: ${bolusCalculatorResult.second.id} ") when { // only NsId changed, no need to upload bolusCalculatorResult.first.onlyNsIdAdded(bolusCalculatorResult.second) -> { confirmLastBolusCalculatorResultsIdIfGreater(bolusCalculatorResult.second.id) //lastBcrId = -1 processChangedBolusCalculatorResultsCompat() aapsLogger.info(LTag.NSCLIENT, "Ignoring BolusCalculatorResult. Only NS id changed ID: ${bolusCalculatorResult.first.id} HistoryID: ${bolusCalculatorResult.second.id} ") return false } // without nsId = create new bolusCalculatorResult.first.interfaceIDs.nightscoutId == null -> nsClientPlugin.nsClientService?.dbAdd( "treatments", bolusCalculatorResult.first.toJson(true, dateUtil, profileFunction), DataSyncSelector.PairBolusCalculatorResult(bolusCalculatorResult.first, bolusCalculatorResult.second.id), "$startId/$lastDbId" ) // with nsId = update bolusCalculatorResult.first.interfaceIDs.nightscoutId != null -> nsClientPlugin.nsClientService?.dbUpdate( "treatments", bolusCalculatorResult.first.interfaceIDs.nightscoutId, bolusCalculatorResult.first.toJson(false, dateUtil, profileFunction), DataSyncSelector.PairBolusCalculatorResult(bolusCalculatorResult.first, bolusCalculatorResult.second.id), "$startId/$lastDbId" ) } return true } return false } override fun confirmLastTempTargetsIdIfGreater(lastSynced: Long) { if (lastSynced > sp.getLong(R.string.key_ns_temporary_target_last_synced_id, 0)) { aapsLogger.debug(LTag.NSCLIENT, "Setting TemporaryTarget data sync from $lastSynced") sp.putLong(R.string.key_ns_temporary_target_last_synced_id, lastSynced) } } // Prepared for v3 (returns all modified after) override fun changedTempTargets(): List<TemporaryTarget> { val startId = sp.getLong(R.string.key_ns_temporary_target_last_synced_id, 0) return appRepository.getModifiedTemporaryTargetsDataFromId(startId).blockingGet().also { aapsLogger.debug(LTag.NSCLIENT, "Loading TemporaryTarget data for sync from $startId. Records ${it.size}") } } //private var lastTtId = -1L //private var lastTtTime = -1L override fun processChangedTempTargetsCompat(): Boolean { val lastDbIdWrapped = appRepository.getLastTempTargetIdWrapped().blockingGet() val lastDbId = if (lastDbIdWrapped is ValueWrapper.Existing) lastDbIdWrapped.value else 0L var startId = sp.getLong(R.string.key_ns_temporary_target_last_synced_id, 0) if (startId > lastDbId) { sp.putLong(R.string.key_ns_temporary_target_last_synced_id, 0) startId = 0 } //if (startId == lastTtId && dateUtil.now() - lastTtTime < 5000) return false //lastTtId = startId //lastTtTime = dateUtil.now() queueCounter.ttsRemaining = lastDbId - startId appRepository.getNextSyncElementTemporaryTarget(startId).blockingGet()?.let { tt -> aapsLogger.info(LTag.NSCLIENT, "Loading TemporaryTarget data Start: $startId ID: ${tt.first.id} HistoryID: ${tt.second.id} ") when { // record is not valid record and we are within first sync, no need to upload tt.first.id != tt.second.id && tt.second.id <= sp.getLong(R.string.key_ns_temporary_target_new_data_id, 0) -> { confirmLastTempTargetsIdIfGreater(tt.second.id) //lastTbrId = -1 processChangedTempTargetsCompat() aapsLogger.info(LTag.NSCLIENT, "Ignoring TemporaryTarget. Change within first sync ID: ${tt.first.id} HistoryID: ${tt.second.id} ") return false } // only NsId changed, no need to upload tt.first.onlyNsIdAdded(tt.second) -> { confirmLastTempTargetsIdIfGreater(tt.second.id) //lastTtId = -1 processChangedTempTargetsCompat() aapsLogger.info(LTag.NSCLIENT, "Ignoring TemporaryTarget. Only NS id changed ID: ${tt.first.id} HistoryID: ${tt.second.id} ") return false } // without nsId = create new tt.first.interfaceIDs.nightscoutId == null -> nsClientPlugin.nsClientService?.dbAdd( "treatments", tt.first.toJson(true, profileFunction.getUnits(), dateUtil), DataSyncSelector.PairTemporaryTarget(tt.first, tt.second.id), "$startId/$lastDbId" ) // existing with nsId = update tt.first.interfaceIDs.nightscoutId != null -> nsClientPlugin.nsClientService?.dbUpdate( "treatments", tt.first.interfaceIDs.nightscoutId, tt.first.toJson(false, profileFunction.getUnits(), dateUtil), DataSyncSelector.PairTemporaryTarget(tt.first, tt.second.id), "$startId/$lastDbId" ) } return true } return false } override fun confirmLastFoodIdIfGreater(lastSynced: Long) { if (lastSynced > sp.getLong(R.string.key_ns_food_last_synced_id, 0)) { aapsLogger.debug(LTag.NSCLIENT, "Setting Food data sync from $lastSynced") sp.putLong(R.string.key_ns_food_last_synced_id, lastSynced) } } // Prepared for v3 (returns all modified after) override fun changedFoods(): List<Food> { val startId = sp.getLong(R.string.key_ns_food_last_synced_id, 0) return appRepository.getModifiedFoodDataFromId(startId).blockingGet().also { aapsLogger.debug(LTag.NSCLIENT, "Loading Food data for sync from $startId. Records ${it.size}") } } //private var lastFoodId = -1L //private var lastFoodTime = -1L override fun processChangedFoodsCompat(): Boolean { val lastDbIdWrapped = appRepository.getLastFoodIdWrapped().blockingGet() val lastDbId = if (lastDbIdWrapped is ValueWrapper.Existing) lastDbIdWrapped.value else 0L var startId = sp.getLong(R.string.key_ns_food_last_synced_id, 0) if (startId > lastDbId) { sp.putLong(R.string.key_ns_food_last_synced_id, 0) startId = 0 } //if (startId == lastFoodId && dateUtil.now() - lastFoodTime < 5000) return false //lastFoodId = startId //lastFoodTime = dateUtil.now() queueCounter.foodsRemaining = lastDbId - startId appRepository.getNextSyncElementFood(startId).blockingGet()?.let { food -> aapsLogger.info(LTag.NSCLIENT, "Loading Food data Start: $startId ID: ${food.first.id} HistoryID: ${food.second} ") when { // only NsId changed, no need to upload food.first.onlyNsIdAdded(food.second) -> { confirmLastFoodIdIfGreater(food.second.id) //lastFoodId = -1 processChangedFoodsCompat() aapsLogger.info(LTag.NSCLIENT, "Ignoring Food. Only NS id changed ID: ${food.first.id} HistoryID: ${food.second.id} ") return false } // without nsId = create new food.first.interfaceIDs.nightscoutId == null -> nsClientPlugin.nsClientService?.dbAdd("food", food.first.toJson(true), DataSyncSelector.PairFood(food.first, food.second.id), "$startId/$lastDbId") // with nsId = update food.first.interfaceIDs.nightscoutId != null -> nsClientPlugin.nsClientService?.dbUpdate( "food", food.first.interfaceIDs.nightscoutId, food.first.toJson(false), DataSyncSelector.PairFood(food.first, food.second.id), "$startId/$lastDbId" ) } return true } return false } override fun confirmLastGlucoseValueIdIfGreater(lastSynced: Long) { if (lastSynced > sp.getLong(R.string.key_ns_glucose_value_last_synced_id, 0)) { aapsLogger.debug(LTag.NSCLIENT, "Setting GlucoseValue data sync from $lastSynced") sp.putLong(R.string.key_ns_glucose_value_last_synced_id, lastSynced) } } // Prepared for v3 (returns all modified after) override fun changedGlucoseValues(): List<GlucoseValue> { val startId = sp.getLong(R.string.key_ns_glucose_value_last_synced_id, 0) return appRepository.getModifiedBgReadingsDataFromId(startId).blockingGet().also { aapsLogger.debug(LTag.NSCLIENT, "Loading GlucoseValue data for sync from $startId . Records ${it.size}") } } //private var lastGvId = -1L //private var lastGvTime = -1L override tailrec fun processChangedGlucoseValuesCompat() { val lastDbIdWrapped = appRepository.getLastGlucoseValueIdWrapped().blockingGet() val lastDbId = if (lastDbIdWrapped is ValueWrapper.Existing) lastDbIdWrapped.value else 0L var startId = sp.getLong(R.string.key_ns_glucose_value_last_synced_id, 0) if (startId > lastDbId) { sp.putLong(R.string.key_ns_glucose_value_last_synced_id, 0) startId = 0 } //if (startId == lastGvId && dateUtil.now() - lastGvTime < 5000) return false //lastGvId = startId //lastGvTime = dateUtil.now() queueCounter.gvsRemaining = lastDbId - startId var tailCall = false appRepository.getNextSyncElementGlucoseValue(startId).blockingGet()?.let { gv -> aapsLogger.info(LTag.NSCLIENT, "Loading GlucoseValue data ID: ${gv.first.id} HistoryID: ${gv.second.id} ") if (activePlugin.activeBgSource.shouldUploadToNs(gv.first)) { when { // record is not valid record and we are within first sync, no need to upload gv.first.id != gv.second.id && gv.second.id <= sp.getLong(R.string.key_ns_glucose_value_new_data_id, 0) -> { confirmLastGlucoseValueIdIfGreater(gv.second.id) //lastGvId = -1 aapsLogger.info(LTag.NSCLIENT, "Ignoring GlucoseValue. Change within first sync ID: ${gv.first.id} HistoryID: ${gv.second.id} ") tailCall = true } // only NsId changed, no need to upload gv.first.onlyNsIdAdded(gv.second) -> { confirmLastGlucoseValueIdIfGreater(gv.second.id) //lastGvId = -1 aapsLogger.info(LTag.NSCLIENT, "Ignoring GlucoseValue. Only NS id changed ID: ${gv.first.id} HistoryID: ${gv.second.id} ") tailCall = true } // without nsId = create new gv.first.interfaceIDs.nightscoutId == null -> nsClientPlugin.nsClientService?.dbAdd("entries", gv.first.toJson(true, dateUtil), DataSyncSelector.PairGlucoseValue(gv.first, gv.second.id), "$startId/$lastDbId") // with nsId = update else -> // gv.first.interfaceIDs.nightscoutId != null nsClientPlugin.nsClientService?.dbUpdate( "entries", gv.first.interfaceIDs.nightscoutId, gv.first.toJson(false, dateUtil), DataSyncSelector.PairGlucoseValue(gv.first, gv.second.id), "$startId/$lastDbId" ) } } else { confirmLastGlucoseValueIdIfGreater(gv.second.id) //lastGvId = -1 tailCall = true } } if (tailCall) { processChangedGlucoseValuesCompat() } } override fun confirmLastTherapyEventIdIfGreater(lastSynced: Long) { if (lastSynced > sp.getLong(R.string.key_ns_therapy_event_last_synced_id, 0)) { aapsLogger.debug(LTag.NSCLIENT, "Setting TherapyEvents data sync from $lastSynced") sp.putLong(R.string.key_ns_therapy_event_last_synced_id, lastSynced) } } // Prepared for v3 (returns all modified after) override fun changedTherapyEvents(): List<TherapyEvent> { val startId = sp.getLong(R.string.key_ns_therapy_event_last_synced_id, 0) return appRepository.getModifiedTherapyEventDataFromId(startId).blockingGet().also { aapsLogger.debug(LTag.NSCLIENT, "Loading TherapyEvents data for sync from $startId. Records ${it.size}") } } //private var lastTeId = -1L //private var lastTeTime = -1L override fun processChangedTherapyEventsCompat(): Boolean { val lastDbIdWrapped = appRepository.getLastTherapyEventIdWrapped().blockingGet() val lastDbId = if (lastDbIdWrapped is ValueWrapper.Existing) lastDbIdWrapped.value else 0L var startId = sp.getLong(R.string.key_ns_therapy_event_last_synced_id, 0) if (startId > lastDbId) { sp.putLong(R.string.key_ns_therapy_event_last_synced_id, 0) startId = 0 } //if (startId == lastTeId && dateUtil.now() - lastTeTime < 5000) return false //lastTeId = startId //lastTeTime = dateUtil.now() queueCounter.tesRemaining = lastDbId - startId appRepository.getNextSyncElementTherapyEvent(startId).blockingGet()?.let { te -> aapsLogger.info(LTag.NSCLIENT, "Loading TherapyEvents data Start: $startId ID: ${te.first.id} HistoryID: ${te.second} ") when { // only NsId changed, no need to upload te.first.onlyNsIdAdded(te.second) -> { confirmLastTherapyEventIdIfGreater(te.second.id) //lastTeId = -1 processChangedTherapyEventsCompat() aapsLogger.info(LTag.NSCLIENT, "Ignoring TherapyEvents. Only NS id changed ID: ${te.first.id} HistoryID: ${te.second.id} ") return false } // without nsId = create new te.first.interfaceIDs.nightscoutId == null -> nsClientPlugin.nsClientService?.dbAdd("treatments", te.first.toJson(true, dateUtil), DataSyncSelector.PairTherapyEvent(te.first, te.second.id), "$startId/$lastDbId") // nsId = update te.first.interfaceIDs.nightscoutId != null -> nsClientPlugin.nsClientService?.dbUpdate( "treatments", te.first.interfaceIDs.nightscoutId, te.first.toJson(false, dateUtil), DataSyncSelector.PairTherapyEvent(te.first, te.second.id), "$startId/$lastDbId" ) } return true } return false } override fun confirmLastDeviceStatusIdIfGreater(lastSynced: Long) { if (lastSynced > sp.getLong(R.string.key_ns_device_status_last_synced_id, 0)) { aapsLogger.debug(LTag.NSCLIENT, "Setting DeviceStatus data sync from $lastSynced") sp.putLong(R.string.key_ns_device_status_last_synced_id, lastSynced) } } override fun changedDeviceStatuses(): List<DeviceStatus> { val startId = sp.getLong(R.string.key_ns_device_status_last_synced_id, 0) return appRepository.getModifiedDeviceStatusDataFromId(startId).blockingGet().also { aapsLogger.debug(LTag.NSCLIENT, "Loading DeviceStatus data for sync from $startId. Records ${it.size}") } } //private var lastDsId = -1L //private var lastDsTime = -1L override fun processChangedDeviceStatusesCompat(): Boolean { val lastDbIdWrapped = appRepository.getLastDeviceStatusIdWrapped().blockingGet() val lastDbId = if (lastDbIdWrapped is ValueWrapper.Existing) lastDbIdWrapped.value else 0L var startId = sp.getLong(R.string.key_ns_device_status_last_synced_id, 0) if (startId > lastDbId) { sp.putLong(R.string.key_ns_device_status_last_synced_id, 0) startId = 0 } //if (startId == lastDsId && dateUtil.now() - lastDsTime < 5000) return false //lastDsId = startId //lastDsTime = dateUtil.now() queueCounter.dssRemaining = lastDbId - startId appRepository.getNextSyncElementDeviceStatus(startId).blockingGet()?.let { deviceStatus -> aapsLogger.info(LTag.NSCLIENT, "Loading DeviceStatus data Start: $startId ID: ${deviceStatus.id}") when { // without nsId = create new deviceStatus.interfaceIDs.nightscoutId == null -> nsClientPlugin.nsClientService?.dbAdd("devicestatus", deviceStatus.toJson(dateUtil), deviceStatus, "$startId/$lastDbId") // with nsId = ignore deviceStatus.interfaceIDs.nightscoutId != null -> Any() } return true } return false } override fun confirmLastTemporaryBasalIdIfGreater(lastSynced: Long) { if (lastSynced > sp.getLong(R.string.key_ns_temporary_basal_last_synced_id, 0)) { aapsLogger.debug(LTag.NSCLIENT, "Setting TemporaryBasal data sync from $lastSynced") sp.putLong(R.string.key_ns_temporary_basal_last_synced_id, lastSynced) } } // Prepared for v3 (returns all modified after) override fun changedTemporaryBasals(): List<TemporaryBasal> { val startId = sp.getLong(R.string.key_ns_temporary_basal_last_synced_id, 0) return appRepository.getModifiedTemporaryBasalDataFromId(startId).blockingGet().also { aapsLogger.debug(LTag.NSCLIENT, "Loading TemporaryBasal data for sync from $startId. Records ${it.size}") } } //private var lastTbrId = -1L //private var lastTbrTime = -1L override fun processChangedTemporaryBasalsCompat(): Boolean { val lastDbIdWrapped = appRepository.getLastTemporaryBasalIdWrapped().blockingGet() val lastDbId = if (lastDbIdWrapped is ValueWrapper.Existing) lastDbIdWrapped.value else 0L var startId = sp.getLong(R.string.key_ns_temporary_basal_last_synced_id, 0) if (startId > lastDbId) { sp.putLong(R.string.key_ns_temporary_basal_last_synced_id, 0) startId = 0 } //if (startId == lastTbrId && dateUtil.now() - lastTbrTime < 5000) return false //lastTbrId = startId //lastTbrTime = dateUtil.now() queueCounter.tbrsRemaining = lastDbId - startId appRepository.getNextSyncElementTemporaryBasal(startId).blockingGet()?.let { tb -> aapsLogger.info(LTag.NSCLIENT, "Loading TemporaryBasal data Start: $startId ID: ${tb.first.id} HistoryID: ${tb.second} ") val profile = profileFunction.getProfile(tb.first.timestamp) if (profile != null) { when { // record is not valid record and we are within first sync, no need to upload tb.first.id != tb.second.id && tb.second.id <= sp.getLong(R.string.key_ns_temporary_basal_new_data_id, 0) -> { confirmLastTemporaryBasalIdIfGreater(tb.second.id) //lastTbrId = -1 processChangedTemporaryBasalsCompat() aapsLogger.info(LTag.NSCLIENT, "Ignoring TemporaryBasal. Change within first sync ID: ${tb.first.id} HistoryID: ${tb.second.id} ") return false } // only NsId changed, no need to upload tb.first.onlyNsIdAdded(tb.second) -> { confirmLastTemporaryBasalIdIfGreater(tb.second.id) //lastTbrId = -1 processChangedTemporaryBasalsCompat() aapsLogger.info(LTag.NSCLIENT, "Ignoring TemporaryBasal. Only NS id changed ID: ${tb.first.id} HistoryID: ${tb.second.id} ") return false } // without nsId = create new tb.first.interfaceIDs.nightscoutId == null -> nsClientPlugin.nsClientService?.dbAdd( "treatments", tb.first.toJson(true, profile, dateUtil), DataSyncSelector.PairTemporaryBasal(tb.first, tb.second.id), "$startId/$lastDbId" ) // with nsId = update tb.first.interfaceIDs.nightscoutId != null -> nsClientPlugin.nsClientService?.dbUpdate( "treatments", tb.first.interfaceIDs.nightscoutId, tb.first.toJson(false, profile, dateUtil), DataSyncSelector.PairTemporaryBasal(tb.first, tb.second.id), "$startId/$lastDbId" ) } return true } else { confirmLastTemporaryBasalIdIfGreater(tb.second.id) //lastTbrId = -1 processChangedTemporaryBasalsCompat() } } return false } override fun confirmLastExtendedBolusIdIfGreater(lastSynced: Long) { if (lastSynced > sp.getLong(R.string.key_ns_extended_bolus_last_synced_id, 0)) { aapsLogger.debug(LTag.NSCLIENT, "Setting ExtendedBolus data sync from $lastSynced") sp.putLong(R.string.key_ns_extended_bolus_last_synced_id, lastSynced) } } // Prepared for v3 (returns all modified after) override fun changedExtendedBoluses(): List<ExtendedBolus> { val startId = sp.getLong(R.string.key_ns_extended_bolus_last_synced_id, 0) return appRepository.getModifiedExtendedBolusDataFromId(startId).blockingGet().also { aapsLogger.debug(LTag.NSCLIENT, "Loading ExtendedBolus data for sync from $startId. Records ${it.size}") } } //private var lastEbId = -1L //private var lastEbTime = -1L override fun processChangedExtendedBolusesCompat(): Boolean { val lastDbIdWrapped = appRepository.getLastExtendedBolusIdWrapped().blockingGet() val lastDbId = if (lastDbIdWrapped is ValueWrapper.Existing) lastDbIdWrapped.value else 0L var startId = sp.getLong(R.string.key_ns_extended_bolus_last_synced_id, 0) if (startId > lastDbId) { sp.putLong(R.string.key_ns_extended_bolus_last_synced_id, 0) startId = 0 } //if (startId == lastEbId && dateUtil.now() - lastEbTime < 5000) return false //lastEbId = startId //lastEbTime = dateUtil.now() queueCounter.ebsRemaining = lastDbId - startId appRepository.getNextSyncElementExtendedBolus(startId).blockingGet()?.let { eb -> aapsLogger.info(LTag.NSCLIENT, "Loading ExtendedBolus data Start: $startId ID: ${eb.first.id} HistoryID: ${eb.second} ") val profile = profileFunction.getProfile(eb.first.timestamp) if (profile != null) { when { // record is not valid record and we are within first sync, no need to upload eb.first.id != eb.second.id && eb.second.id <= sp.getLong(R.string.key_ns_extended_bolus_new_data_id, 0) -> { confirmLastExtendedBolusIdIfGreater(eb.second.id) //lastTbrId = -1 processChangedExtendedBolusesCompat() aapsLogger.info(LTag.NSCLIENT, "Ignoring ExtendedBolus. Change within first sync ID: ${eb.first.id} HistoryID: ${eb.second.id} ") return false } // only NsId changed, no need to upload eb.first.onlyNsIdAdded(eb.second) -> { confirmLastExtendedBolusIdIfGreater(eb.second.id) //lastEbId = -1 processChangedExtendedBolusesCompat() aapsLogger.info(LTag.NSCLIENT, "Ignoring ExtendedBolus. Only NS id changed ID: ${eb.first.id} HistoryID: ${eb.second.id} ") return false } // without nsId = create new eb.first.interfaceIDs.nightscoutId == null -> nsClientPlugin.nsClientService?.dbAdd( "treatments", eb.first.toJson(true, profile, dateUtil), DataSyncSelector.PairExtendedBolus(eb.first, eb.second.id), "$startId/$lastDbId" ) // with nsId = update eb.first.interfaceIDs.nightscoutId != null -> nsClientPlugin.nsClientService?.dbUpdate( "treatments", eb.first.interfaceIDs.nightscoutId, eb.first.toJson(false, profile, dateUtil), DataSyncSelector.PairExtendedBolus(eb.first, eb.second.id), "$startId/$lastDbId" ) } return true } else { confirmLastExtendedBolusIdIfGreater(eb.second.id) //lastEbId = -1 processChangedExtendedBolusesCompat() } } return false } override fun confirmLastProfileSwitchIdIfGreater(lastSynced: Long) { if (lastSynced > sp.getLong(R.string.key_ns_profile_switch_last_synced_id, 0)) { aapsLogger.debug(LTag.NSCLIENT, "Setting ProfileSwitch data sync from $lastSynced") sp.putLong(R.string.key_ns_profile_switch_last_synced_id, lastSynced) } } override fun changedProfileSwitch(): List<ProfileSwitch> { val startId = sp.getLong(R.string.key_ns_profile_switch_last_synced_id, 0) return appRepository.getModifiedProfileSwitchDataFromId(startId).blockingGet().also { aapsLogger.debug(LTag.NSCLIENT, "Loading ProfileSwitch data for sync from $startId. Records ${it.size}") } } //private var lastPsId = -1L //private var lastPsTime = -1L override fun processChangedProfileSwitchesCompat(): Boolean { val lastDbIdWrapped = appRepository.getLastProfileSwitchIdWrapped().blockingGet() val lastDbId = if (lastDbIdWrapped is ValueWrapper.Existing) lastDbIdWrapped.value else 0L var startId = sp.getLong(R.string.key_ns_profile_switch_last_synced_id, 0) if (startId > lastDbId) { sp.putLong(R.string.key_ns_profile_switch_last_synced_id, 0) startId = 0 } //if (startId == lastPsId && dateUtil.now() - lastPsTime < 5000) return false //lastPsId = startId //lastPsTime = dateUtil.now() queueCounter.pssRemaining = lastDbId - startId appRepository.getNextSyncElementProfileSwitch(startId).blockingGet()?.let { ps -> aapsLogger.info(LTag.NSCLIENT, "Loading ProfileSwitch data Start: $startId ID: ${ps.first.id} HistoryID: ${ps.second} ") when { // only NsId changed, no need to upload ps.first.onlyNsIdAdded(ps.second) -> { confirmLastProfileSwitchIdIfGreater(ps.second.id) //lastPsId = -1 processChangedProfileSwitchesCompat() aapsLogger.info(LTag.NSCLIENT, "Ignoring ProfileSwitch. Only NS id changed ID: ${ps.first.id} HistoryID: ${ps.second.id} ") return false } // without nsId = create new ps.first.interfaceIDs.nightscoutId == null -> nsClientPlugin.nsClientService?.dbAdd("treatments", ps.first.toJson(true, dateUtil), DataSyncSelector.PairProfileSwitch(ps.first, ps.second.id), "$startId/$lastDbId") // with nsId = update ps.first.interfaceIDs.nightscoutId != null -> nsClientPlugin.nsClientService?.dbUpdate( "treatments", ps.first.interfaceIDs.nightscoutId, ps.first.toJson(false, dateUtil), DataSyncSelector.PairProfileSwitch(ps.first, ps.second.id), "$startId/$lastDbId" ) } return true } return false } override fun confirmLastEffectiveProfileSwitchIdIfGreater(lastSynced: Long) { if (lastSynced > sp.getLong(R.string.key_ns_effective_profile_switch_last_synced_id, 0)) { aapsLogger.debug(LTag.NSCLIENT, "Setting EffectiveProfileSwitch data sync from $lastSynced") sp.putLong(R.string.key_ns_effective_profile_switch_last_synced_id, lastSynced) } } override fun changedEffectiveProfileSwitch(): List<EffectiveProfileSwitch> { val startId = sp.getLong(R.string.key_ns_effective_profile_switch_last_synced_id, 0) return appRepository.getModifiedEffectiveProfileSwitchDataFromId(startId).blockingGet().also { aapsLogger.debug(LTag.NSCLIENT, "Loading EffectiveProfileSwitch data for sync from $startId. Records ${it.size}") } } //private var lastEpsId = -1L //private var lastEpsTime = -1L override fun processChangedEffectiveProfileSwitchesCompat(): Boolean { val lastDbIdWrapped = appRepository.getLastEffectiveProfileSwitchIdWrapped().blockingGet() val lastDbId = if (lastDbIdWrapped is ValueWrapper.Existing) lastDbIdWrapped.value else 0L var startId = sp.getLong(R.string.key_ns_effective_profile_switch_last_synced_id, 0) if (startId > lastDbId) { sp.putLong(R.string.key_ns_effective_profile_switch_last_synced_id, 0) startId = 0 } //if (startId == lastEpsId && dateUtil.now() - lastEpsTime < 5000) return false //lastEpsId = startId //lastEpsTime = dateUtil.now() queueCounter.epssRemaining = lastDbId - startId appRepository.getNextSyncElementEffectiveProfileSwitch(startId).blockingGet()?.let { ps -> aapsLogger.info(LTag.NSCLIENT, "Loading EffectiveProfileSwitch data Start: $startId ID: ${ps.first.id} HistoryID: ${ps.second} ") when { // only NsId changed, no need to upload ps.first.onlyNsIdAdded(ps.second) -> { confirmLastEffectiveProfileSwitchIdIfGreater(ps.second.id) //lastEpsId = -1 processChangedEffectiveProfileSwitchesCompat() aapsLogger.info(LTag.NSCLIENT, "Ignoring EffectiveProfileSwitch. Only NS id changed ID: ${ps.first.id} HistoryID: ${ps.second.id} ") return false } // without nsId = create new ps.first.interfaceIDs.nightscoutId == null -> nsClientPlugin.nsClientService?.dbAdd("treatments", ps.first.toJson(true, dateUtil), DataSyncSelector.PairEffectiveProfileSwitch(ps.first, ps.second.id), "$startId/$lastDbId") // with nsId = update ps.first.interfaceIDs.nightscoutId != null -> nsClientPlugin.nsClientService?.dbUpdate( "treatments", ps.first.interfaceIDs.nightscoutId, ps.first.toJson(false, dateUtil), DataSyncSelector.PairEffectiveProfileSwitch(ps.first, ps.second.id), "$startId/$lastDbId" ) } return true } return false } override fun confirmLastOfflineEventIdIfGreater(lastSynced: Long) { if (lastSynced > sp.getLong(R.string.key_ns_offline_event_last_synced_id, 0)) { aapsLogger.debug(LTag.NSCLIENT, "Setting OfflineEvent data sync from $lastSynced") sp.putLong(R.string.key_ns_offline_event_last_synced_id, lastSynced) } } // Prepared for v3 (returns all modified after) override fun changedOfflineEvents(): List<OfflineEvent> { val startId = sp.getLong(R.string.key_ns_offline_event_last_synced_id, 0) return appRepository.getModifiedOfflineEventsDataFromId(startId).blockingGet().also { aapsLogger.debug(LTag.NSCLIENT, "Loading OfflineEvent data for sync from $startId. Records ${it.size}") } } //private var lastOeId = -1L //private var lastOeTime = -1L override fun processChangedOfflineEventsCompat(): Boolean { val lastDbIdWrapped = appRepository.getLastOfflineEventIdWrapped().blockingGet() val lastDbId = if (lastDbIdWrapped is ValueWrapper.Existing) lastDbIdWrapped.value else 0L var startId = sp.getLong(R.string.key_ns_offline_event_last_synced_id, 0) if (startId > lastDbId) { sp.putLong(R.string.key_ns_offline_event_last_synced_id, 0) startId = 0 } //if (startId == lastOeId && dateUtil.now() - lastOeTime < 5000) return false //lastOeId = startId //lastOeTime = dateUtil.now() queueCounter.oesRemaining = lastDbId - startId appRepository.getNextSyncElementOfflineEvent(startId).blockingGet()?.let { oe -> aapsLogger.info(LTag.NSCLIENT, "Loading OfflineEvent data Start: $startId ID: ${oe.first.id} HistoryID: ${oe.second} ") when { // only NsId changed, no need to upload oe.first.onlyNsIdAdded(oe.second) -> { confirmLastOfflineEventIdIfGreater(oe.second.id) //lastOeId = -1 processChangedOfflineEventsCompat() aapsLogger.info(LTag.NSCLIENT, "Ignoring OfflineEvent. Only NS id changed ID: ${oe.first.id} HistoryID: ${oe.second.id} ") return false } // without nsId = create new oe.first.interfaceIDs.nightscoutId == null -> nsClientPlugin.nsClientService?.dbAdd("treatments", oe.first.toJson(true, dateUtil), DataSyncSelector.PairOfflineEvent(oe.first, oe.second.id), "$startId/$lastDbId") // existing with nsId = update oe.first.interfaceIDs.nightscoutId != null -> nsClientPlugin.nsClientService?.dbUpdate( "treatments", oe.first.interfaceIDs.nightscoutId, oe.first.toJson(false, dateUtil), DataSyncSelector.PairOfflineEvent(oe.first, oe.second.id), "$startId/$lastDbId" ) } return true } return false } override fun confirmLastProfileStore(lastSynced: Long) { sp.putLong(R.string.key_ns_profile_store_last_synced_timestamp, lastSynced) } override fun processChangedProfileStore() { val lastSync = sp.getLong(R.string.key_ns_profile_store_last_synced_timestamp, 0) val lastChange = sp.getLong(R.string.key_local_profile_last_change, 0) if (lastChange == 0L) return if (lastChange > lastSync) { val profileJson = localProfilePlugin.profile?.data ?: return nsClientPlugin.nsClientService?.dbAdd("profile", profileJson, DataSyncSelector.PairProfileStore(profileJson, dateUtil.now()), "") } } }
agpl-3.0
499ccdd7abb867ba47c59a77b92c3f48
51.467793
195
0.607322
4.453038
false
false
false
false
Adventech/sabbath-school-android-2
common/core/src/main/java/com/cryart/sabbathschool/core/extensions/context/ContextExt.kt
1
4079
/* * Copyright (c) 2021. Adventech <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.cryart.sabbathschool.core.extensions.context import android.content.Context import android.content.Intent import android.content.res.Configuration import android.graphics.Bitmap import android.graphics.Color import android.graphics.drawable.BitmapDrawable import android.net.Uri import androidx.browser.customtabs.CustomTabsIntent import androidx.core.app.ShareCompat import androidx.core.net.toUri import coil.imageLoader import coil.request.ImageRequest import com.cryart.sabbathschool.core.R import com.cryart.sabbathschool.core.misc.SSColorTheme import timber.log.Timber fun Context.isDarkTheme(): Boolean { return resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES } /** * Returns current color primary saved in prefs */ val Context.colorPrimary get() = Color.parseColor(SSColorTheme.getInstance(this).colorPrimary) val Context.colorPrimaryDark get() = Color.parseColor(SSColorTheme.getInstance(this).colorPrimaryDark) fun Context.launchWebUrl(url: String): Boolean { return launchWebUrl(url.toWebUri()) } fun Context.launchWebUrl(uri: Uri): Boolean { try { val intent = CustomTabsIntent.Builder() .setShowTitle(true) .setUrlBarHidingEnabled(true) .setStartAnimations(this, R.anim.slide_up, android.R.anim.fade_out) .setExitAnimations(this, android.R.anim.fade_in, R.anim.slide_down) .build() intent.launchUrl(this, uri) return true } catch (ignored: Exception) { Timber.e(ignored) } // Fall back to launching a default web browser intent. try { val intent = Intent(Intent.ACTION_VIEW, uri) if (intent.resolveActivity(packageManager) != null) { startActivity(intent) return true } } catch (ignored: Exception) { Timber.e(ignored) } // We were unable to show the web page. return false } fun String.toWebUri(): Uri { return (if (startsWith("http://") || startsWith("https://")) this else "https://$this").toUri() } object ContextHelper { @JvmStatic fun launchWebUrl(context: Context, url: String) { context.launchWebUrl(url) } } fun Context.shareContent(content: String, chooser: String = "") { val shareIntent = ShareCompat.IntentBuilder(this) .setType("text/plain") .setText(content) .intent if (shareIntent.resolveActivity(packageManager) != null) { startActivity(Intent.createChooser(shareIntent, chooser)) } } @SuppressWarnings("UNCHECKED_CAST") fun <T> Context.systemService(name: String): T { return getSystemService(name) as T } suspend fun Context.fetchBitmap(source: Any?): Bitmap? { val request = ImageRequest.Builder(this) .data(source) .build() val drawable = imageLoader.execute(request).drawable return (drawable as? BitmapDrawable)?.bitmap }
mit
9c93e65fe90c561692b7c8893390a820
32.991667
102
0.719049
4.253389
false
false
false
false
square/wire
wire-library/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/parser/FieldElement.kt
1
2796
/* * Copyright (C) 2014 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 com.squareup.wire.schema.internal.parser import com.squareup.wire.schema.Field import com.squareup.wire.schema.Location import com.squareup.wire.schema.ProtoType import com.squareup.wire.schema.internal.appendDocumentation import com.squareup.wire.schema.internal.appendOptions import com.squareup.wire.schema.internal.toEnglishLowerCase data class FieldElement( val location: Location, val label: Field.Label? = null, val type: String, val name: String, val defaultValue: String? = null, val jsonName: String? = null, val tag: Int = 0, val documentation: String = "", val options: List<OptionElement> = emptyList() ) { fun toSchema() = buildString { appendDocumentation(documentation) if (label != null) { append("${label.name.toEnglishLowerCase()} ") } append("$type $name = $tag") val optionsWithDefault = optionsWithSpecialValues() if (optionsWithDefault.isNotEmpty()) { append(' ') appendOptions(optionsWithDefault) } append(";\n") } /** * Both `default` and `json_name` are defined in the schema like options but they are actually * not options themselves as they're missing from `google.protobuf.FieldOptions`. */ private fun optionsWithSpecialValues(): List<OptionElement> { var options = if (defaultValue == null) { options } else { val protoType = ProtoType.get(type) options + OptionElement.create("default", protoType.toKind(), defaultValue) } options = if (jsonName == null) options else options + OptionElement.create("json_name", OptionElement.Kind.STRING, jsonName) return options } // Only non-repeated scalar types and Enums support default values. private fun ProtoType.toKind(): OptionElement.Kind { return when (simpleName) { "bool" -> OptionElement.Kind.BOOLEAN "string" -> OptionElement.Kind.STRING "bytes", "double", "float", "fixed32", "fixed64", "int32", "int64", "sfixed32", "sfixed64", "sint32", "sint64", "uint32", "uint64" -> OptionElement.Kind.NUMBER else -> OptionElement.Kind.ENUM } } }
apache-2.0
21c5f53c2284117d82e3633f386a3d8a
28.744681
96
0.6799
4.099707
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/caches/resolve/MultiplatformModulesAndServicesCreationTest.kt
3
5130
/* * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.caches.resolve import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.kotlin.codeMetaInfo.renderConfigurations.DiagnosticCodeMetaInfoRenderConfiguration import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.base.projectStructure.compositeAnalysis.useCompositeAnalysis import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleSourceInfo import org.jetbrains.kotlin.idea.caches.project.getIdeaModelInfosCache import org.jetbrains.kotlin.idea.caches.project.toDescriptor import org.jetbrains.kotlin.idea.codeMetaInfo.AbstractCodeMetaInfoTest import org.jetbrains.kotlin.idea.codeMetaInfo.CodeMetaInfoTestCase import org.jetbrains.kotlin.idea.codeMetaInfo.findCorrespondingFileInTestDir import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR import org.jetbrains.kotlin.idea.test.KotlinTestUtils import org.jetbrains.kotlin.idea.test.TestRoot import org.jetbrains.kotlin.idea.util.sourceRoots import org.jetbrains.kotlin.resolve.descriptorUtil.getKotlinTypeRefiner import org.jetbrains.kotlin.resolve.descriptorUtil.isTypeRefinementEnabled import org.jetbrains.kotlin.types.TypeRefinement import org.jetbrains.kotlin.types.checker.KotlinTypeRefiner import java.io.File @TestRoot("idea/tests") class MultiplatformModulesAndServicesCreationTest : AbstractCodeMetaInfoTest() { private companion object { private const val TEST_DIR_NAME_IN_TEST_DATA: String = "mppCreationOfModulesAndServices" } override fun getTestDataDirectory() = IDEA_TEST_DATA_DIR.resolve(TEST_DIR_NAME_IN_TEST_DATA) override fun getConfigurations() = listOf( DiagnosticCodeMetaInfoRenderConfiguration(), ) fun testCreationOfModulesAndServices() { val testDataDir = "testData/$TEST_DIR_NAME_IN_TEST_DATA" KotlinTestUtils.runTest(this::doRunTest, this, testDataDir) } fun doRunTest(testDataDir: String) { setupProject(File(testDataPath)) require(project.useCompositeAnalysis) { "Expected enabled composite analysis for project" } runHighlightingForModules(testDataDir) val (modulesWithKtFiles, modulesWithoutKtFiles) = partitionModulesByKtFilePresence() for (populatedModule in modulesWithKtFiles) { runModuleAssertions(populatedModule, analyzed = true) } for (absentModule in modulesWithoutKtFiles) { runModuleAssertions(absentModule, analyzed = false) } } @OptIn(TypeRefinement::class) private fun runModuleAssertions(module: ModuleSourceInfo, analyzed: Boolean) { val moduleDescriptor = module.toDescriptor() ?: throw AssertionError("Descriptor is null for module: $module") assertTrue( "Type refinement is not enabled for module $module with enabled composite analysis mode", moduleDescriptor.isTypeRefinementEnabled() ) assertTrue( "Unexpected ${if (analyzed) "" else "non-"}default type refiner for module: $module. " + "Service components should ${if (analyzed) "" else "not "}have been initialized.", (moduleDescriptor.getKotlinTypeRefiner() !is KotlinTypeRefiner.Default) == analyzed ) } private fun runHighlightingForModules(testDataDir: String) { val checker = CodeMetaInfoTestCase(getConfigurations(), checkNoDiagnosticError) for (module in ModuleManager.getInstance(project).modules) { for (sourceRoot in module.sourceRoots) { VfsUtilCore.processFilesRecursively(sourceRoot) { file -> if (!file.isKotlinFile) return@processFilesRecursively true checker.checkFile(file, file.findCorrespondingFileInTestDir(sourceRoot, File(testDataDir)), project) true } } } } private fun partitionModulesByKtFilePresence(): Pair<List<ModuleSourceInfo>, List<ModuleSourceInfo>> { val moduleSourceInfos = getIdeaModelInfosCache(project).allModules().filterIsInstance<ModuleSourceInfo>() return moduleSourceInfos.partition { ModuleRootManager.getInstance(it.module).sourceRoots.any { sourceRoot -> var kotlinSourceFileFound = false VfsUtilCore.processFilesRecursively(sourceRoot) { file -> if (file.isKotlinFile) { kotlinSourceFileFound = true return@processFilesRecursively false } true } kotlinSourceFileFound } } } private val VirtualFile.isKotlinFile: Boolean get() = this.fileType == KotlinFileType.INSTANCE }
apache-2.0
089b7dc4518e9e85faf3dafccb449769
41.75
120
0.717154
5.06917
false
true
false
false
laminr/aeroknow
app/src/main/java/biz/eventually/atpl/ui/subject/SubjectActivity.kt
1
8726
package biz.eventually.atpl.ui.subject import android.arch.lifecycle.Observer import android.arch.lifecycle.ViewModelProviders import android.content.Intent import android.os.Bundle import android.support.annotation.IntegerRes import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.Toolbar import android.view.MenuItem import android.view.View import android.view.View.GONE import android.view.View.VISIBLE import biz.eventually.atpl.AtplApplication import biz.eventually.atpl.R import biz.eventually.atpl.common.IntentIdentifier import biz.eventually.atpl.common.IntentIdentifier.Companion.REFRESH_SUBJECT import biz.eventually.atpl.data.NetworkStatus import biz.eventually.atpl.data.db.Topic import biz.eventually.atpl.data.dto.SubjectView import biz.eventually.atpl.data.dto.TopicView import biz.eventually.atpl.ui.BaseComponentActivity import biz.eventually.atpl.ui.ViewModelFactory import biz.eventually.atpl.ui.questions.QuestionRepository import biz.eventually.atpl.ui.questions.QuestionViewModel import biz.eventually.atpl.ui.questions.QuestionsActivity import biz.eventually.atpl.utils.hasInternetConnection import cn.pedant.SweetAlert.SweetAlertDialog import com.crashlytics.android.answers.Answers import com.crashlytics.android.answers.ContentViewEvent import com.google.firebase.perf.metrics.AddTrace import io.fabric.sdk.android.Fabric import kotlinx.android.synthetic.main.activity_subject.* import kotlinx.coroutines.experimental.android.UI import kotlinx.coroutines.experimental.launch import org.jetbrains.anko.doAsync import org.jetbrains.anko.uiThread import javax.inject.Inject class SubjectActivity : BaseComponentActivity() { private var mTopicViewList: List<TopicView> = listOf() private var mSourceId: Long = 0 @Inject lateinit var subjectViewModelFactory: ViewModelFactory<SubjectRepository> @Inject lateinit var questionViewModelFactory: ViewModelFactory<QuestionRepository> private lateinit var mViewModel: SubjectViewModel private lateinit var mQViewModel: QuestionViewModel private var mAdapter: SubjectAdapter = SubjectAdapter(this::onItemClick) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) AtplApplication.component.inject(this) mViewModel = ViewModelProviders.of(this, subjectViewModelFactory).get(SubjectViewModel::class.java) mQViewModel = ViewModelProviders.of(this, questionViewModelFactory).get(QuestionViewModel::class.java) Fabric.with(this, Answers()) setContentView(R.layout.activity_subject) val toolbar = findViewById<Toolbar>(R.id.toolbar) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) val sourceName = intent.extras.getString(IntentIdentifier.SOURCE_NAME) supportActionBar?.title = sourceName ?: "" mSourceId = intent.extras.getLong(IntentIdentifier.SOURCE_ID) mViewModel.setSourceId(mSourceId) mViewModel.subjects.observe(this, Observer<List<SubjectView>> { doAsync { val data = transform(it) uiThread { displaySubjects(data) } } }) mViewModel.networkStatus.observe(this, Observer<NetworkStatus> { when (it) { NetworkStatus.LOADING -> { showHideError(GONE) subject_rotate.start() } NetworkStatus.SUCCESS -> { showHideError(GONE) subject_rotate.stop() } else -> { showHideError(VISIBLE) subject_rotate.stop() } } }) mQViewModel.updateLine.observe(this, Observer<Triple<Long, Boolean, Boolean>> { it -> it?.let { val (idWeb, isSync, hasOffline) = it updateTopicLine(idWeb, isSync, hasOffline) } }) val mLayoutManager = LinearLayoutManager(applicationContext) subject_subject_list.layoutManager = mLayoutManager subject_subject_list.itemAnimator = DefaultItemAnimator() subject_subject_list.adapter = mAdapter subject_refresh.setOnClickListener { loadData() } } private fun transform(subjects: List<SubjectView>?): List<TopicView> { val topics = mutableListOf<TopicView>() val ids = mViewModel.getTopicIdWithQuestion() subjects?.forEach { t -> // header val titleTopic = Topic((t.subject.idWeb * -1), t.subject.idWeb, t.subject.name) topics.add(TopicView(titleTopic)) // line of topics topics.addAll(t.topics.map { TopicView(it, hasOfflineData = it.idWeb in ids) }) } return topics } private fun onItemClick(topic: Topic, startFirst: Boolean = false) { // Subject if (topic.idWeb < 0) { // Fabric Answer - Download data Answers.getInstance().logContentView(ContentViewEvent() .putContentName("Subject") .putContentType("Download Questions") .putContentId("Source_${mSourceId}_subject_${topic.idWeb}") .putCustomAttribute("Download offline", "${topic.idWeb}: ${topic.name}") ) mViewModel.subjects.value?.let { mQViewModel.getDataForSubject(topic.idWeb, it) } } // display questions for subject else { var openActivity = true if (!hasInternetConnection()) { if (topic.questions == 0) { openActivity = false SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE) .setTitleText(getString(R.string.msg_offline_title)) .setContentText(getString(R.string.error_offline_no_data)) .show() } } if (openActivity) { // Fabric Answer Answers.getInstance().logContentView(ContentViewEvent() .putContentName("Subject") .putContentType("Questions") .putContentId("Source_${mSourceId}_subject_${topic.idWeb}") .putCustomAttribute("Subject Name", "${topic.idWeb}: ${topic.name}") ) val intent = Intent(this, QuestionsActivity::class.java) intent.putExtra(IntentIdentifier.TOPIC, topic.idWeb) intent.putExtra(IntentIdentifier.TOPIC_STARRED, startFirst) startActivityForResult(intent, REFRESH_SUBJECT) } } } // to avoid source reloading override fun onOptionsItemSelected(item: MenuItem?): Boolean { if (item?.itemId == android.R.id.home) { onBackPressed() return true } return super.onOptionsItemSelected(item) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == REFRESH_SUBJECT && resultCode == RESULT_OK) { loadData(true) } else { mViewModel.refresh(mSourceId) } } private fun displaySubjects(topics: List<TopicView>) { mTopicViewList = topics mAdapter.bind(mTopicViewList) mAdapter.notifyDataSetChanged() showHideError(if (mTopicViewList.isEmpty()) View.VISIBLE else View.GONE) } @AddTrace(name = "loadDataSubject", enabled = true) private fun loadData(silent: Boolean = false) { if (mSourceId > 0) { mViewModel.setSourceId(mSourceId, silent) } else { showHideError(View.GONE) } } private fun updateTopicLine(topicId: Long, isSync: Boolean = false, hasOffline: Boolean = false) { launch(UI) { mAdapter.getList().forEachIndexed { index, topicDto -> if (topicDto.topic.idWeb == topicId) { topicDto.isSync = isSync topicDto.hasOfflineData = hasOffline mAdapter.notifyItemChanged(index) } } } } private fun showHideError(@IntegerRes show: Int) { subject_error.visibility = show subject_refresh.visibility = show } private fun onError() { showHideError(View.VISIBLE) } }
mit
5033d2f925998e7669816d59c19ad421
33.626984
110
0.633051
4.899495
false
false
false
false
PolymerLabs/arcs
javatests/arcs/sdk/android/storage/ResurrectionHelperTest.kt
1
4150
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.sdk.android.storage import android.app.Application import android.content.Context import android.content.Intent import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import arcs.android.common.resurrection.ResurrectionRequest import arcs.android.common.resurrection.ResurrectionRequest.Companion.EXTRA_REGISTRATION_CLASS_NAME import arcs.android.common.resurrection.ResurrectionRequest.Companion.EXTRA_REGISTRATION_NOTIFIERS import arcs.android.common.resurrection.ResurrectionRequest.Companion.EXTRA_REGISTRATION_PACKAGE_NAME import arcs.android.common.resurrection.ResurrectionRequest.Companion.EXTRA_REGISTRATION_TARGET_ID import arcs.core.storage.StorageKey import arcs.core.storage.StorageKeyManager import arcs.core.storage.keys.RamDiskStorageKey import com.google.common.truth.Truth.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.Robolectric import org.robolectric.Shadows.shadowOf @RunWith(AndroidJUnit4::class) class ResurrectionHelperTest { private var callbackCalls = mutableListOf<List<StorageKey>>() private lateinit var context: Context private lateinit var helper: ResurrectionHelper private lateinit var service: ResurrectionHelperDummyService @Before fun setUp() { StorageKeyManager.GLOBAL_INSTANCE.reset(RamDiskStorageKey) service = Robolectric.setupService(ResurrectionHelperDummyService::class.java) context = InstrumentationRegistry.getInstrumentation().targetContext callbackCalls.clear() helper = ResurrectionHelper(context) } @Test fun requestResurrection() { val storageKeys = listOf( RamDiskStorageKey("foo"), RamDiskStorageKey("bar") ) helper.requestResurrection("test", storageKeys, ResurrectionHelperDummyService::class.java) val actualIntent = shadowOf(ApplicationProvider.getApplicationContext<Application>()) .nextStartedService val expectedIntent = Intent(context, ResurrectionHelperDummyService::class.java).also { ResurrectionRequest.createDefault(context, storageKeys, "test") .populateRequestIntent(it) } assertThat(actualIntent.action).isEqualTo(expectedIntent.action) assertThat(actualIntent.getStringExtra(EXTRA_REGISTRATION_PACKAGE_NAME)) .isEqualTo(expectedIntent.getStringExtra(EXTRA_REGISTRATION_PACKAGE_NAME)) assertThat(actualIntent.getStringExtra(EXTRA_REGISTRATION_CLASS_NAME)) .isEqualTo(expectedIntent.getStringExtra(EXTRA_REGISTRATION_CLASS_NAME)) assertThat(actualIntent.getStringArrayListExtra(EXTRA_REGISTRATION_NOTIFIERS)) .containsExactlyElementsIn( expectedIntent.getStringArrayListExtra(EXTRA_REGISTRATION_NOTIFIERS) ) assertThat(actualIntent.getStringExtra(EXTRA_REGISTRATION_TARGET_ID)).isEqualTo("test") } @Test fun cancelResurrectionRequest() { helper.cancelResurrectionRequest("test", ResurrectionHelperDummyService::class.java) val actualIntent = shadowOf(ApplicationProvider.getApplicationContext<Application>()) .nextStartedService val expectedIntent = Intent(context, ResurrectionHelperDummyService::class.java).also { ResurrectionRequest.createDefault(context, emptyList(), "test") .populateUnrequestIntent(it) } assertThat(actualIntent.action).isEqualTo(expectedIntent.action) assertThat(actualIntent.getStringExtra(EXTRA_REGISTRATION_PACKAGE_NAME)) .isEqualTo(expectedIntent.getStringExtra(EXTRA_REGISTRATION_PACKAGE_NAME)) assertThat(actualIntent.getStringExtra(EXTRA_REGISTRATION_CLASS_NAME)) .isEqualTo(expectedIntent.getStringExtra(EXTRA_REGISTRATION_CLASS_NAME)) assertThat(actualIntent.getStringExtra(EXTRA_REGISTRATION_TARGET_ID)).isEqualTo("test") } }
bsd-3-clause
08fe78637134702d9ee90feb9225e1e9
41.346939
101
0.801205
4.605993
false
true
false
false
Maccimo/intellij-community
tools/intellij.ide.starter/src/com/intellij/ide/starter/android.kt
1
5990
package com.intellij.ide.starter import com.intellij.ide.starter.di.di import com.intellij.ide.starter.exec.ExecOutputRedirect import com.intellij.ide.starter.exec.exec import com.intellij.ide.starter.ide.IDETestContext import com.intellij.ide.starter.path.GlobalPaths import com.intellij.ide.starter.system.SystemInfo import com.intellij.ide.starter.utils.FileSystem import com.intellij.ide.starter.utils.HttpClient import com.intellij.ide.starter.utils.logOutput import com.intellij.ide.starter.utils.resolveInstalledJdk11 import org.gradle.internal.hash.Hashing import org.kodein.di.direct import org.kodein.di.instance import java.io.File import java.nio.file.Path import kotlin.io.path.div import kotlin.io.path.isDirectory import kotlin.time.Duration /** * Resolve platform specific android studio installer and return paths * @return Pair<InstallDir / InstallerFile> */ fun downloadAndroidStudio(): Pair<Path, File> { val ext = when { SystemInfo.isWindows -> "-windows.zip" SystemInfo.isMac -> "-mac.zip" SystemInfo.isLinux -> "-linux.tar.gz" else -> error("Not supported OS") } val downloadUrl = "https://redirector.gvt1.com/edgedl/android/studio/ide-zips/2021.1.1.11/android-studio-2021.1.1.11$ext" val asFileName = downloadUrl.split("/").last() val globalPaths by di.instance<GlobalPaths>() val zipFile = globalPaths.getCacheDirectoryFor("android-studio").resolve(asFileName) HttpClient.downloadIfMissing(downloadUrl, zipFile) val installDir = globalPaths.getCacheDirectoryFor("builds") / "AI-211" installDir.toFile().deleteRecursively() val installerFile = zipFile.toFile() return Pair(installDir, installerFile) } fun downloadLatestAndroidSdk(javaHome: Path): Path { val packages = listOf( "build-tools;28.0.3", //"cmake;3.10.2.4988404", //"docs", //"ndk;20.0.5594570", "platforms;android-28", "sources;android-28", "platform-tools" ) val sdkManager = downloadSdkManager() // we use unique home folder per installation to ensure only expected // packages are included into the SDK home path val packagesHash = Hashing.sha1().hashString(packages.joinToString("$")) val home = di.direct.instance<GlobalPaths>().getCacheDirectoryFor("android-sdk") / "sdk-roots" / "sdk-root-$packagesHash" if (home.isDirectory() && home.toFile().walk().count() > 10) return home val envVariablesWithJavaHome = System.getenv() + ("JAVA_HOME" to javaHome.toAbsolutePath().toString()) try { home.toFile().mkdirs() /// https://stackoverflow.com/questions/38096225/automatically-accept-all-sdk-licences /// sending "yes" to the process in the STDIN :( exec(presentablePurpose = "android-sdk-licenses", workDir = home, environmentVariables = envVariablesWithJavaHome, args = listOf(sdkManager.toString(), "--sdk_root=$home", "--licenses"), stderrRedirect = ExecOutputRedirect.ToStdOut("[sdkmanager-err]"), stdInBytes = "yes\n".repeat(10).toByteArray(), // it asks the confirmation at least two times timeout = Duration.minutes(15) ) //loading SDK exec(presentablePurpose = "android-sdk-loading", workDir = home, environmentVariables = envVariablesWithJavaHome, args = listOf(sdkManager.toString(), "--sdk_root=$home", "--list"), stderrRedirect = ExecOutputRedirect.ToStdOut("[sdkmanager-err]"), timeout = Duration.minutes(15) ) //loading SDK exec(presentablePurpose = "android-sdk-installing", workDir = home, environmentVariables = envVariablesWithJavaHome, args = listOf(sdkManager.toString(), "--sdk_root=$home", "--install", "--verbose") + packages, stderrRedirect = ExecOutputRedirect.ToStdOut("[sdkmanager-err]"), timeout = Duration.minutes(15) ) return home } catch (t: Throwable) { home.toFile().deleteRecursively() throw Exception("Failed to prepare Android SDK to $home. ${t.message}", t) } } private fun downloadSdkManager(): Path { val url = when { SystemInfo.isMac -> "https://dl.google.com/android/repository/commandlinetools-mac-6200805_latest.zip" SystemInfo.isWindows -> "https://dl.google.com/android/repository/commandlinetools-win-6200805_latest.zip" SystemInfo.isLinux -> "https://dl.google.com/android/repository/commandlinetools-linux-6200805_latest.zip" else -> error("Unsupported OS: ${SystemInfo.OS_NAME} ${SystemInfo.OS_VERSION}") } val name = url.split("/").last() val androidSdkCache = di.direct.instance<GlobalPaths>().getCacheDirectoryFor("android-sdk") val targetArchive = androidSdkCache / "archives" / name val targetUnpack = androidSdkCache / "builds" / name HttpClient.downloadIfMissing(url, targetArchive) FileSystem.unpackIfMissing(targetArchive, targetUnpack) val ext = if (SystemInfo.isWindows) ".bat" else "" @Suppress("SpellCheckingInspection") val sdkManager = targetUnpack.toFile().walk().first { it.endsWith("tools/bin/sdkmanager$ext") } if (SystemInfo.isMac || SystemInfo.isLinux) { sdkManager.setExecutable(true) } return sdkManager.toPath() } fun main() { downloadLatestAndroidSdk(resolveInstalledJdk11()) } fun IDETestContext.downloadAndroidPluginProject(): IDETestContext { val projectHome = resolvedProjectHome if (projectHome.toFile().name == "intellij-community-master" && !(projectHome / "android").toFile().exists()) { val scriptName = "getPlugins.sh" val script = (projectHome / scriptName).toFile() assert(script.exists()) { "File $script does not exist" } val scriptContent = script.readText() val stdout = ExecOutputRedirect.ToString() val stderr = ExecOutputRedirect.ToString() exec( "git-clone-android-plugin", workDir = projectHome, timeout = Duration.minutes(10), args = scriptContent.split(" "), stdoutRedirect = stdout, stderrRedirect = stderr ) logOutput(stdout.read().trim()) } return this }
apache-2.0
ed577f035083119adf90172ddce27069
35.975309
123
0.713856
3.998665
false
false
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/api/VimChangeGroupBase.kt
1
47894
/* * 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.api import com.maddyhome.idea.vim.KeyHandler import com.maddyhome.idea.vim.command.Argument import com.maddyhome.idea.vim.command.Command import com.maddyhome.idea.vim.command.CommandFlags 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.command.VimStateMachine.Companion.getInstance import com.maddyhome.idea.vim.common.ChangesListener import com.maddyhome.idea.vim.common.Offset import com.maddyhome.idea.vim.common.OperatedRange import com.maddyhome.idea.vim.common.TextRange import com.maddyhome.idea.vim.common.offset import com.maddyhome.idea.vim.diagnostic.debug import com.maddyhome.idea.vim.diagnostic.vimLogger import com.maddyhome.idea.vim.group.visual.VimSelection import com.maddyhome.idea.vim.handler.EditorActionHandlerBase import com.maddyhome.idea.vim.handler.Motion.AbsoluteOffset import com.maddyhome.idea.vim.helper.CharacterHelper import com.maddyhome.idea.vim.helper.CharacterHelper.charType import com.maddyhome.idea.vim.helper.inInsertMode import com.maddyhome.idea.vim.helper.inSingleCommandMode import com.maddyhome.idea.vim.helper.usesVirtualSpace import com.maddyhome.idea.vim.helper.vimStateMachine import com.maddyhome.idea.vim.listener.SelectionVimListenerSuppressor import com.maddyhome.idea.vim.mark.VimMarkConstants.MARK_CHANGE_END import com.maddyhome.idea.vim.mark.VimMarkConstants.MARK_CHANGE_POS import com.maddyhome.idea.vim.mark.VimMarkConstants.MARK_CHANGE_START import com.maddyhome.idea.vim.options.OptionConstants import com.maddyhome.idea.vim.options.OptionScope import com.maddyhome.idea.vim.register.RegisterConstants.LAST_INSERTED_TEXT_REGISTER import org.jetbrains.annotations.NonNls import java.awt.event.KeyEvent import java.util.* import javax.swing.KeyStroke import kotlin.math.abs import kotlin.math.min abstract class VimChangeGroupBase : VimChangeGroup { private var repeatLines: Int = 0 private var repeatColumn: Int = 0 private var repeatAppend: Boolean = false @JvmField protected val strokes: MutableList<Any> = ArrayList() @JvmField protected var repeatCharsCount = 0 @JvmField protected var lastStrokes: MutableList<Any>? = null @JvmField protected var oldOffset = -1 // Workaround for VIM-1546. Another solution is highly appreciated. var tabAction = false @JvmField protected var vimDocumentListener: ChangesListener? = null @JvmField protected var lastLower = true @JvmField protected var vimDocument: VimDocument? = null @JvmField protected var lastInsert: Command? = null override fun setInsertRepeat(lines: Int, column: Int, append: Boolean) { repeatLines = lines repeatColumn = column repeatAppend = append } /** * Deletes count character after the caret from the editor * * @param editor The editor to remove characters from * @param caret The caret on which the operation is performed * @param count The numbers of characters to delete. * @return true if able to delete, false if not */ override fun deleteCharacter( editor: VimEditor, caret: VimCaret, count: Int, isChange: Boolean, operatorArguments: OperatorArguments, ): Boolean { val endOffset = injector.motion.getOffsetOfHorizontalMotion(editor, caret, count, true) if (endOffset != -1) { val res = deleteText( editor, TextRange(caret.offset.point, endOffset), SelectionType.CHARACTER_WISE, caret, operatorArguments ) val pos = caret.offset.point val norm = editor.normalizeOffset(caret.getBufferPosition().line, pos, isChange) if (norm != pos || editor.offsetToVisualPosition(norm) !== injector.engineEditorHelper.inlayAwareOffsetToVisualPosition(editor, norm) ) { caret.moveToOffset(norm) } // Always move the caret. Our position might or might not have changed, but an inlay might have been moved to our // location, or deleting the character(s) might have caused us to scroll sideways in long files. Moving the caret // will make sure it's in the right place, and visible val offset = editor.normalizeOffset( caret.getBufferPosition().line, caret.offset.point, isChange ) caret.moveToOffset(offset) return res } return false } /** * Delete text from the document. This will fail if being asked to store the deleted text into a read-only * register. * * * End offset of range is exclusive * * * delete new TextRange(1, 5) * 0123456789 * Hello, xyz * .||||.... * * * end <= text.length * * @param editor The editor to delete from * @param range The range to delete * @param type The type of deletion * @return true if able to delete the text, false if not */ protected fun deleteText( editor: VimEditor, range: TextRange, type: SelectionType?, caret: VimCaret, operatorArguments: OperatorArguments, ): Boolean { var updatedRange = range // Fix for https://youtrack.jetbrains.net/issue/VIM-35 if (!range.normalize(editor.fileSize().toInt())) { updatedRange = if (range.startOffset == range.endOffset && range.startOffset == editor.fileSize() .toInt() && range.startOffset != 0 ) { TextRange(range.startOffset - 1, range.endOffset) } else { return false } } if (type == null || operatorArguments.mode.inInsertMode || caret.registerStorage.storeText(caret, editor, updatedRange, type, true) || caret != editor.primaryCaret() // sticky tape for VIM-2703 todo remove in the next release ) { val startOffsets = updatedRange.startOffsets val endOffsets = updatedRange.endOffsets for (i in updatedRange.size() - 1 downTo 0) { editor.deleteString(TextRange(startOffsets[i], endOffsets[i])) } if (type != null) { val start = updatedRange.startOffset if (editor.primaryCaret() == caret) { injector.markGroup.setMark(editor, MARK_CHANGE_POS, start) injector.markGroup.setChangeMarks(editor, TextRange(start, start + 1)) } } return true } return false } /** * Inserts text into the document * * @param editor The editor to insert into * @param caret The caret to start insertion in * @param str The text to insert */ override fun insertText(editor: VimEditor, caret: VimCaret, offset: Int, str: String) { (editor as MutableVimEditor).insertText(Offset(offset), str) caret.moveToInlayAwareOffset(offset + str.length) injector.markGroup.setMark(editor, MARK_CHANGE_POS, offset) } override fun insertText(editor: VimEditor, caret: VimCaret, str: String) { insertText(editor, caret, caret.offset.point, str) } open fun insertText(editor: VimEditor, caret: VimCaret, start: BufferPosition, str: String) { insertText(editor, caret, editor.bufferPositionToOffset(start), str) } /** * This repeats the previous insert count times * @param editor The editor to insert into * @param context The data context * @param count The number of times to repeat the previous insert */ protected open fun repeatInsertText( editor: VimEditor, context: ExecutionContext, count: Int, operatorArguments: OperatorArguments, ) { val myLastStrokes = lastStrokes ?: return for (caret in editor.nativeCarets()) { for (i in 0 until count) { for (lastStroke in myLastStrokes) { when (lastStroke) { is NativeAction -> { injector.actionExecutor.executeAction(lastStroke, context) strokes.add(lastStroke) } is EditorActionHandlerBase -> { injector.actionExecutor.executeVimAction(editor, lastStroke, context, operatorArguments) strokes.add(lastStroke) } is CharArray -> { insertText(editor, caret, String(lastStroke)) } else -> { throw RuntimeException("Unexpected stroke type: ${lastStroke.javaClass} $lastStroke") } } } } } } /** * This repeats the previous insert count times * * @param editor The editor to insert into * @param context The data context * @param count The number of times to repeat the previous insert */ override fun repeatInsert( editor: VimEditor, context: ExecutionContext, count: Int, started: Boolean, operatorArguments: OperatorArguments, ) { for (caret in editor.nativeCarets()) { if (repeatLines > 0) { val visualLine = caret.getVisualPosition().line val bufferLine = caret.getBufferPosition().line val position = editor.bufferPositionToOffset(BufferPosition(bufferLine, repeatColumn, false)) for (i in 0 until repeatLines) { if (repeatAppend && (repeatColumn < VimMotionGroupBase.LAST_COLUMN) && (editor.getVisualLineLength(visualLine + i) < repeatColumn) ) { val pad = injector.engineEditorHelper.pad(editor, context, bufferLine + i, repeatColumn) if (pad.isNotEmpty()) { val offset = editor.getLineEndOffset(bufferLine + i) insertText(editor, caret, offset, pad) } } val updatedCount = if (started) (if (i == 0) count else count + 1) else count if (repeatColumn >= VimMotionGroupBase.LAST_COLUMN) { caret.moveToOffset(injector.motion.moveCaretToLineEnd(editor, bufferLine + i, true)) repeatInsertText(editor, context, updatedCount, operatorArguments) } else if (editor.getVisualLineLength(visualLine + i) >= repeatColumn) { val visualPosition = VimVisualPosition(visualLine + i, repeatColumn, false) val inlaysCount = injector.engineEditorHelper.amountOfInlaysBeforeVisualPosition(editor, visualPosition) caret.moveToVisualPosition(VimVisualPosition(visualLine + i, repeatColumn + inlaysCount, false)) repeatInsertText(editor, context, updatedCount, operatorArguments) } } caret.moveToOffset(position) } else { repeatInsertText(editor, context, count, operatorArguments) val position = injector.motion.getOffsetOfHorizontalMotion(editor, caret, -1, false) caret.moveToOffset(position) } } repeatLines = 0 repeatColumn = 0 repeatAppend = false } protected inner class VimChangesListener : ChangesListener { override fun documentChanged(change: ChangesListener.Change) { val newFragment = change.newFragment val oldFragment = change.oldFragment val newFragmentLength = newFragment.length val oldFragmentLength = oldFragment.length // Repeat buffer limits if (repeatCharsCount > Companion.MAX_REPEAT_CHARS_COUNT) { return } // <Enter> is added to strokes as an action during processing in order to indent code properly in the repeat // command if (newFragment.startsWith("\n") && newFragment.trim { it <= ' ' }.isEmpty()) { strokes.addAll(getAdjustCaretActions(change)) oldOffset = -1 return } // Ignore multi-character indents as they should be inserted automatically while repeating <Enter> actions if (!tabAction && newFragmentLength > 1 && newFragment.trim { it <= ' ' }.isEmpty()) { return } tabAction = false strokes.addAll(getAdjustCaretActions(change)) if (oldFragmentLength > 0) { val editorDelete = injector.nativeActionManager.deleteAction if (editorDelete != null) { for (i in 0 until oldFragmentLength) { strokes.add(editorDelete) } } } if (newFragmentLength > 0) { strokes.add(newFragment.toCharArray()) } repeatCharsCount += newFragmentLength oldOffset = change.offset + newFragmentLength } private fun getAdjustCaretActions(change: ChangesListener.Change): List<EditorActionHandlerBase> { val delta: Int = change.offset - oldOffset if (oldOffset >= 0 && delta != 0) { val positionCaretActions: MutableList<EditorActionHandlerBase> = ArrayList() val motionName = if (delta < 0) "VimMotionLeftAction" else "VimMotionRightAction" val action = injector.actionExecutor.findVimAction(motionName)!! val count = abs(delta) for (i in 0 until count) { positionCaretActions.add(action) } return positionCaretActions } return emptyList() } } /** * Begin insert before the cursor position * @param editor The editor to insert into * @param context The data context */ override fun insertBeforeCursor(editor: VimEditor, context: ExecutionContext) { initInsert(editor, context, VimStateMachine.Mode.INSERT) } override fun insertAfterLineEnd(editor: VimEditor, context: ExecutionContext) { for (caret in editor.nativeCarets()) { caret.moveToOffset(injector.motion.moveCaretToCurrentLineEnd(editor, caret)) } initInsert(editor, context, VimStateMachine.Mode.INSERT) } /** * Begin insert after the cursor position * @param editor The editor to insert into * @param context The data context */ override fun insertAfterCursor(editor: VimEditor, context: ExecutionContext) { for (caret in editor.nativeCarets()) { caret.moveToOffset(injector.motion.getOffsetOfHorizontalMotion(editor, caret, 1, true)) } initInsert(editor, context, VimStateMachine.Mode.INSERT) } /** * Begin insert before the start of the current line * @param editor The editor to insert into * @param context The data context */ override fun insertLineStart(editor: VimEditor, context: ExecutionContext) { for (caret in editor.nativeCarets()) { caret.moveToOffset(injector.motion.moveCaretToCurrentLineStart(editor, caret)) } initInsert(editor, context, VimStateMachine.Mode.INSERT) } /** * Begin insert before the first non-blank on the current line * * @param editor The editor to insert into */ override fun insertBeforeFirstNonBlank(editor: VimEditor, context: ExecutionContext) { for (caret in editor.nativeCarets()) { caret.moveToOffset(injector.motion.moveCaretToCurrentLineStartSkipLeading(editor, caret)) } initInsert(editor, context, VimStateMachine.Mode.INSERT) } /** * Begin insert/replace mode * @param editor The editor to insert into * @param context The data context * @param mode The mode - indicate insert or replace */ override fun initInsert(editor: VimEditor, context: ExecutionContext, mode: VimStateMachine.Mode) { val state = getInstance(editor) for (caret in editor.nativeCarets()) { caret.vimInsertStart = editor.createLiveMarker(caret.offset, caret.offset) if (caret == editor.primaryCaret()) { injector.markGroup.setMark(editor, MARK_CHANGE_START, caret.offset.point) } } val cmd = state.executingCommand if (cmd != null && state.isDotRepeatInProgress) { state.pushModes(mode, VimStateMachine.SubMode.NONE) if (mode === VimStateMachine.Mode.REPLACE) { editor.insertMode = false } if (cmd.flags.contains(CommandFlags.FLAG_NO_REPEAT_INSERT)) { val commandState = getInstance(editor) repeatInsert( editor, context, 1, false, OperatorArguments(false, 1, commandState.mode, commandState.subMode) ) } else { val commandState = getInstance(editor) repeatInsert( editor, context, cmd.count, false, OperatorArguments(false, cmd.count, commandState.mode, commandState.subMode) ) } if (mode === VimStateMachine.Mode.REPLACE) { editor.insertMode = true } state.popModes() } else { lastInsert = cmd strokes.clear() repeatCharsCount = 0 val myVimDocument = vimDocument if (myVimDocument != null && vimDocumentListener != null) { myVimDocument.removeChangeListener(vimDocumentListener!!) } vimDocument = editor.document val myChangeListener = VimChangesListener() vimDocumentListener = myChangeListener vimDocument!!.addChangeListener(myChangeListener) oldOffset = editor.currentCaret().offset.point editor.insertMode = mode === VimStateMachine.Mode.INSERT state.pushModes(mode, VimStateMachine.SubMode.NONE) } notifyListeners(editor) } override fun runEnterAction(editor: VimEditor, context: ExecutionContext) { val state = getInstance(editor) if (!state.isDotRepeatInProgress) { // While repeating the enter action has been already executed because `initInsert` repeats the input val action = injector.nativeActionManager.enterAction if (action != null) { strokes.add(action) injector.actionExecutor.executeAction(action, context) } } } override fun runEnterAboveAction(editor: VimEditor, context: ExecutionContext) { val state = getInstance(editor) if (!state.isDotRepeatInProgress) { // While repeating the enter action has been already executed because `initInsert` repeats the input val action = injector.nativeActionManager.createLineAboveCaret if (action != null) { strokes.add(action) injector.actionExecutor.executeAction(action, context) } } } /** * Inserts previously inserted text * @param editor The editor to insert into * @param context The data context * @param exit true if insert mode should be exited after the insert, false should stay in insert mode */ override fun insertPreviousInsert( editor: VimEditor, context: ExecutionContext, exit: Boolean, operatorArguments: OperatorArguments, ) { repeatInsertText(editor, context, 1, operatorArguments) if (exit) { editor.exitInsertMode(context, operatorArguments) } } /** * Terminate insert/replace mode after the user presses Escape or Ctrl-C * * * DEPRECATED. Please, don't use this function directly. Use ModeHelper.exitInsertMode in file ModeExtensions.kt */ override fun processEscape(editor: VimEditor, context: ExecutionContext?, operatorArguments: OperatorArguments) { // Get the offset for marks before we exit insert mode - switching from insert to overtype subtracts one from the // column offset. var offset = editor.primaryCaret().offset.point val markGroup = injector.markGroup markGroup.setMark(editor, '^', offset) markGroup.setMark(editor, MARK_CHANGE_END, offset) if (getInstance(editor).mode === VimStateMachine.Mode.REPLACE) { editor.insertMode = true } var cnt = if (lastInsert != null) lastInsert!!.count else 0 if (lastInsert != null && lastInsert!!.flags.contains(CommandFlags.FLAG_NO_REPEAT_INSERT)) { cnt = 1 } if (vimDocument != null && vimDocumentListener != null) { vimDocument!!.removeChangeListener(vimDocumentListener!!) vimDocumentListener = null } lastStrokes = ArrayList(strokes) if (context != null) { injector.changeGroup.repeatInsert(editor, context, if (cnt == 0) 0 else cnt - 1, true, operatorArguments) } if (getInstance(editor).mode === VimStateMachine.Mode.INSERT) { updateLastInsertedTextRegister() } // The change pos '.' mark is the offset AFTER processing escape, and after switching to overtype offset = editor.primaryCaret().offset.point markGroup.setMark(editor, MARK_CHANGE_POS, offset) getInstance(editor).popModes() exitAllSingleCommandInsertModes(editor) } private fun updateLastInsertedTextRegister() { val textToPutRegister = StringBuilder() if (lastStrokes != null) { for (lastStroke in lastStrokes!!) { if (lastStroke is CharArray) { textToPutRegister.append(String(lastStroke)) } } } injector.registerGroup.storeTextSpecial(LAST_INSERTED_TEXT_REGISTER, textToPutRegister.toString()) } private fun exitAllSingleCommandInsertModes(editor: VimEditor) { while (editor.inSingleCommandMode) { editor.vimStateMachine.popModes() if (editor.inInsertMode) { editor.vimStateMachine.popModes() } } } /** * Processes the Enter key by running the first successful action registered for "ENTER" keystroke. * * * If this is REPLACE mode we need to turn off OVERWRITE before and then turn OVERWRITE back on after sending the * "ENTER" key. * * @param editor The editor to press "Enter" in * @param context The data context */ override fun processEnter(editor: VimEditor, context: ExecutionContext) { if (editor.vimStateMachine.mode === VimStateMachine.Mode.REPLACE) { editor.insertMode = true } val enterKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0) val actions = injector.keyGroup.getActions(editor, enterKeyStroke) for (action in actions) { if (injector.actionExecutor.executeAction(action, context)) { break } } if (editor.vimStateMachine.mode === VimStateMachine.Mode.REPLACE) { editor.insertMode = false } } /** * Performs a mode switch after change action * @param editor The editor to switch mode in * @param context The data context * @param toSwitch The mode to switch to */ override fun processPostChangeModeSwitch( editor: VimEditor, context: ExecutionContext, toSwitch: VimStateMachine.Mode, ) { if (toSwitch === VimStateMachine.Mode.INSERT) { initInsert(editor, context, VimStateMachine.Mode.INSERT) } } /** * This processes all keystrokes in Insert/Replace mode that were converted into Commands. Some of these * commands need to be saved off so the inserted/replaced text can be repeated properly later if needed. * * @param editor The editor the command was executed in * @param cmd The command that was executed */ override fun processCommand(editor: VimEditor, cmd: Command) { // return value never used here if (CommandFlags.FLAG_SAVE_STROKE in cmd.flags) { strokes.add(cmd.action) } else if (CommandFlags.FLAG_CLEAR_STROKES in cmd.flags) { clearStrokes(editor) } } /** * While in INSERT or REPLACE mode the user can enter a single NORMAL mode command and then automatically * return to INSERT or REPLACE mode. * * @param editor The editor to put into NORMAL mode for one command */ override fun processSingleCommand(editor: VimEditor) { getInstance(editor).pushModes(VimStateMachine.Mode.INSERT_NORMAL, VimStateMachine.SubMode.NONE) clearStrokes(editor) } /** * Delete from the cursor to the end of count - 1 lines down * * @param editor The editor to delete from * @param caret VimCaret on the position to start * @param count The number of lines affected * @return true if able to delete the text, false if not */ override fun deleteEndOfLine( editor: VimEditor, caret: VimCaret, count: Int, operatorArguments: OperatorArguments ): Boolean { val initialOffset = caret.offset.point val offset = injector.motion.moveCaretToRelativeLineEnd(editor, caret, count - 1, true) val lineStart = injector.motion.moveCaretToCurrentLineStart(editor, caret) var startOffset = initialOffset if (offset == initialOffset && offset != lineStart) startOffset-- // handle delete from virtual space if (offset != -1) { val rangeToDelete = TextRange(startOffset, offset) editor.nativeCarets().filter { it != caret && rangeToDelete.contains(it.offset.point) } .forEach { editor.removeCaret(it) } val res = deleteText(editor, rangeToDelete, SelectionType.CHARACTER_WISE, caret, operatorArguments) if (usesVirtualSpace) { caret.moveToOffset(startOffset) } else { val pos = injector.motion.getOffsetOfHorizontalMotion(editor, caret, -1, false) if (pos != -1) { caret.moveToOffset(pos) } } return res } return false } /** * Joins count lines together starting at the cursor. No count or a count of one still joins two lines. * * @param editor The editor to join the lines in * @param caret The caret in the first line to be joined. * @param count The number of lines to join * @param spaces If true the joined lines will have one space between them and any leading space on the second line * will be removed. If false, only the newline is removed to join the lines. * @return true if able to join the lines, false if not */ override fun deleteJoinLines( editor: VimEditor, caret: VimCaret, count: Int, spaces: Boolean, operatorArguments: OperatorArguments, ): Boolean { var myCount = count if (myCount < 2) myCount = 2 val lline = caret.getBufferPosition().line val total = editor.lineCount() return if (lline + myCount > total) { false } else deleteJoinNLines(editor, caret, lline, myCount, spaces, operatorArguments) } /** * This processes all "regular" keystrokes entered while in insert/replace mode * * @param editor The editor the character was typed into * @param context The data context * @param key The user entered keystroke * @return true if this was a regular character, false if not */ override fun processKey( editor: VimEditor, context: ExecutionContext, key: KeyStroke, ): Boolean { logger.debug { "processKey($key)" } if (key.keyChar != KeyEvent.CHAR_UNDEFINED) { type(editor, context, key.keyChar) return true } // Shift-space if (key.keyCode == 32 && key.modifiers and KeyEvent.SHIFT_DOWN_MASK != 0) { type(editor, context, ' ') return true } return false } override fun processKeyInSelectMode( editor: VimEditor, context: ExecutionContext, key: KeyStroke, ): Boolean { var res: Boolean SelectionVimListenerSuppressor.lock().use { res = processKey(editor, context, key) editor.exitSelectModeNative(false) KeyHandler.getInstance().reset(editor) if (isPrintableChar(key.keyChar) || activeTemplateWithLeftRightMotion(editor, key)) { injector.changeGroup.insertBeforeCursor(editor, context) } } return res } /** * Deletes count lines including the current line * * @param editor The editor to remove the lines from * @param count The number of lines to delete * @return true if able to delete the lines, false if not */ override fun deleteLine( editor: VimEditor, caret: VimCaret, count: Int, operatorArguments: OperatorArguments ): Boolean { val start = injector.motion.moveCaretToCurrentLineStart(editor, caret) val offset = min(injector.motion.moveCaretToRelativeLineEnd(editor, caret, count - 1, true) + 1, editor.fileSize().toInt()) if (logger.isDebug()) { logger.debug("start=$start") logger.debug("offset=$offset") } if (offset != -1) { val res = deleteText(editor, TextRange(start, offset), SelectionType.LINE_WISE, caret, operatorArguments) if (res && caret.offset.point >= editor.fileSize() && caret.offset.point != 0) { caret.moveToOffset( injector.motion.moveCaretToRelativeLineStartSkipLeading( editor, caret, -1 ) ) } return res } return false } override fun joinViaIdeaByCount(editor: VimEditor, context: ExecutionContext, count: Int): Boolean { val executions = if (count > 1) count - 1 else 1 val allowedExecution = editor.nativeCarets().any { caret: VimCaret -> val lline = caret.getBufferPosition().line val total = editor.lineCount() lline + count <= total } if (!allowedExecution) return false for (i in 0 until executions) { val joinLinesAction = injector.nativeActionManager.joinLines if (joinLinesAction != null) { injector.actionExecutor.executeAction(joinLinesAction, context) } } return true } /** * Joins all the lines selected by the current visual selection. * * @param editor The editor to join the lines in * @param caret The caret to be moved after joining * @param range The range of the visual selection * @param spaces If true the joined lines will have one space between them and any leading space on the second line * will be removed. If false, only the newline is removed to join the lines. * @return true if able to join the lines, false if not */ override fun deleteJoinRange( editor: VimEditor, caret: VimCaret, range: TextRange, spaces: Boolean, operatorArguments: OperatorArguments, ): Boolean { val startLine = editor.offsetToBufferPosition(range.startOffset).line val endLine = editor.offsetToBufferPosition(range.endOffset).line var count = endLine - startLine + 1 if (count < 2) count = 2 return deleteJoinNLines(editor, caret, startLine, count, spaces, operatorArguments) } override fun joinViaIdeaBySelections( editor: VimEditor, context: ExecutionContext, caretsAndSelections: Map<VimCaret, VimSelection>, ) { caretsAndSelections.forEach { (caret: VimCaret, range: VimSelection) -> if (!caret.isValid) return@forEach val (first, second) = range.getNativeStartAndEnd() caret.setSelection( first.offset, second.offset ) } val joinLinesAction = injector.nativeActionManager.joinLines if (joinLinesAction != null) { injector.actionExecutor.executeAction(joinLinesAction, context) } editor.nativeCarets().forEach { caret: VimCaret -> caret.removeSelection() val (line, column) = caret.getVisualPosition() if (line < 1) return@forEach val newVisualPosition = VimVisualPosition(line - 1, column, false) caret.moveToVisualPosition(newVisualPosition) } } override fun getDeleteRangeAndType( editor: VimEditor, caret: VimCaret, context: ExecutionContext, argument: Argument, isChange: Boolean, operatorArguments: OperatorArguments, ): Pair<TextRange, SelectionType>? { val range = injector.motion.getMotionRange(editor, caret, context, argument, operatorArguments) ?: return null // Delete motion commands that are not linewise become linewise if all the following are true: // 1) The range is across multiple lines // 2) There is only whitespace before the start of the range // 3) There is only whitespace after the end of the range var type: SelectionType = if (argument.motion.isLinewiseMotion()) { SelectionType.LINE_WISE } else { SelectionType.CHARACTER_WISE } val motion = argument.motion if (!isChange && !motion.isLinewiseMotion()) { val start = editor.offsetToBufferPosition(range.startOffset) val end = editor.offsetToBufferPosition(range.endOffset) if (start.line != end.line) { if (!editor.anyNonWhitespace(range.startOffset, -1) && !editor.anyNonWhitespace(range.endOffset, 1)) { type = SelectionType.LINE_WISE } } } return Pair(range, type) } /** * Delete the range of text. * * @param editor The editor to delete the text from * @param caret The caret to be moved after deletion * @param range The range to delete * @param type The type of deletion * @param isChange Is from a change action * @return true if able to delete the text, false if not */ override fun deleteRange( editor: VimEditor, caret: VimCaret, range: TextRange, type: SelectionType?, isChange: Boolean, operatorArguments: OperatorArguments, ): Boolean { val intendedColumn = caret.vimLastColumn val removeLastNewLine = removeLastNewLine(editor, range, type) val res = deleteText(editor, range, type, caret, operatorArguments) if (removeLastNewLine) { val textLength = editor.fileSize().toInt() editor.deleteString(TextRange(textLength - 1, textLength)) } if (res) { var pos = editor.normalizeOffset(range.startOffset, isChange) if (type === SelectionType.LINE_WISE) { // Reset the saved intended column cache, which has been invalidated by the caret moving due to deleted text. // This value will be used to reposition the caret if 'startofline' is false caret.vimLastColumn = intendedColumn pos = injector.motion .moveCaretToLineWithStartOfLineOption( editor, editor.offsetToBufferPosition(pos).line, caret ) } caret.moveToOffset(pos) // Ensure the intended column cache is invalidated - it will only happen automatically if the caret actually moves // If 'startofline' is true and we've just deleted text, it's likely we haven't moved caret.resetLastColumn() } return res } private fun removeLastNewLine(editor: VimEditor, range: TextRange, type: SelectionType?): Boolean { var endOffset = range.endOffset val fileSize = editor.fileSize().toInt() if (endOffset > fileSize) { check(!injector.optionService.isSet(OptionScope.GLOBAL, OptionConstants.ideastrictmodeName)) { "Incorrect offset. File size: $fileSize, offset: $endOffset" } endOffset = fileSize } return (type === SelectionType.LINE_WISE) && range.startOffset != 0 && editor.text()[endOffset - 1] != '\n' && endOffset == fileSize } /** * Delete from the cursor to the end of count - 1 lines down and enter insert mode * * @param editor The editor to change * @param caret The caret to perform action on * @param count The number of lines to change * @return true if able to delete count lines, false if not */ override fun changeEndOfLine( editor: VimEditor, caret: VimCaret, count: Int, operatorArguments: OperatorArguments ): Boolean { val res = deleteEndOfLine(editor, caret, count, operatorArguments) if (res) { caret.moveToOffset(injector.motion.moveCaretToCurrentLineEnd(editor, caret)) editor.vimChangeActionSwitchMode = VimStateMachine.Mode.INSERT } return res } /** * Delete count characters and then enter insert mode * * @param editor The editor to change * @param caret The caret to be moved * @return true if able to delete count characters, false if not */ override fun changeCharacters(editor: VimEditor, caret: VimCaret, operatorArguments: OperatorArguments): Boolean { val count = operatorArguments.count1 // TODO is it correct to use primary caret? There is a caret as an argument val len = editor.lineLength(editor.primaryCaret().getBufferPosition().line) val col = caret.getBufferPosition().column if (col + count >= len) { return changeEndOfLine(editor, caret, 1, operatorArguments) } val res = deleteCharacter(editor, caret, count, true, operatorArguments) if (res) { editor.vimChangeActionSwitchMode = VimStateMachine.Mode.INSERT } return res } /** * Clears all the keystrokes from the current insert command * * @param editor The editor to clear strokes from. */ protected fun clearStrokes(editor: VimEditor) { strokes.clear() repeatCharsCount = 0 for (caret in editor.nativeCarets()) { caret.vimInsertStart = editor.createLiveMarker(caret.offset, caret.offset) } } /** * This does the actual joining of the lines * * @param editor The editor to join the lines in * @param caret The caret on the starting line (to be moved) * @param startLine The starting buffer line * @param count The number of lines to join including startLine * @param spaces If true the joined lines will have one space between them and any leading space on the second line * will be removed. If false, only the newline is removed to join the lines. * @return true if able to join the lines, false if not */ private fun deleteJoinNLines( editor: VimEditor, caret: VimCaret, startLine: Int, count: Int, spaces: Boolean, operatorArguments: OperatorArguments, ): Boolean { // start my moving the cursor to the very end of the first line caret.moveToOffset(injector.motion.moveCaretToLineEnd(editor, startLine, true)) for (i in 1 until count) { val start = injector.motion.moveCaretToCurrentLineEnd(editor, caret) val trailingWhitespaceStart = injector.motion.moveCaretToRelativeLineEndSkipTrailing( editor, caret, 0 ) val hasTrailingWhitespace = start != trailingWhitespaceStart + 1 caret.moveToOffset(start) val offset: Int = if (spaces) { injector.motion.moveCaretToRelativeLineStartSkipLeading(editor, caret, 1) } else { injector.motion.moveCaretToLineStart(editor, caret.getBufferPosition().line + 1) } deleteText(editor, TextRange(caret.offset.point, offset), null, caret, operatorArguments) if (spaces && !hasTrailingWhitespace) { insertText(editor, caret, " ") caret.moveToOffset( injector.motion.getOffsetOfHorizontalMotion(editor, caret, -1, true) ) } } return true } private fun isPrintableChar(c: Char): Boolean { val block = Character.UnicodeBlock.of(c) return !Character.isISOControl(c) && (c != KeyEvent.CHAR_UNDEFINED) && (block != null) && block !== Character.UnicodeBlock.SPECIALS } private fun activeTemplateWithLeftRightMotion(editor: VimEditor, keyStroke: KeyStroke): Boolean { return injector.templateManager.getTemplateState(editor) != null && (keyStroke.keyCode == KeyEvent.VK_LEFT || keyStroke.keyCode == KeyEvent.VK_RIGHT) } /** * Replace text in the editor * * @param editor The editor to replace text in * @param start The start offset to change * @param end The end offset to change * @param str The new text */ override fun replaceText(editor: VimEditor, start: Int, end: Int, str: String) { (editor as MutableVimEditor).replaceString(start, end, str) val newEnd = start + str.length injector.markGroup.setChangeMarks(editor, TextRange(start, newEnd)) injector.markGroup.setMark(editor, MARK_CHANGE_POS, newEnd) } /** * Inserts a new line above the caret position * * @param editor The editor to insert into * @param caret The caret to insert above * @param col The column to indent to */ protected open fun insertNewLineAbove(editor: VimEditor, caret: VimCaret, col: Int) { if (editor.isOneLineMode()) return var firstLiner = false if (caret.getVisualPosition().line == 0) { caret.moveToOffset( injector.motion.moveCaretToCurrentLineStart( editor, caret ) ) firstLiner = true } else { // TODO: getVerticalMotionOffset returns a visual line, not the expected logical line // Also address the unguarded upcast val motion = injector.motion.getVerticalMotionOffset(editor, caret, -1) caret.moveToOffset((motion as AbsoluteOffset).offset) caret.moveToOffset(injector.motion.moveCaretToCurrentLineEnd(editor, caret)) } editor.vimChangeActionSwitchMode = VimStateMachine.Mode.INSERT insertText( editor, caret, "\n${editor.createIndentBySize(col)}" ) if (firstLiner) { // TODO: getVerticalMotionOffset returns a visual line, not the expected logical line // Also address the unguarded upcast val motion = injector.motion.getVerticalMotionOffset(editor, caret, -1) caret.moveToOffset((motion as AbsoluteOffset).offset) } } override fun changeMotion( editor: VimEditor, caret: VimCaret, context: ExecutionContext, argument: Argument, operatorArguments: OperatorArguments, ): Boolean { var count0 = operatorArguments.count0 // Vim treats cw as ce and cW as cE if cursor is on a non-blank character val motion = argument.motion val id = motion.action.id var kludge = false val bigWord = id == VIM_MOTION_BIG_WORD_RIGHT val chars = editor.text() val offset = caret.offset.point val fileSize = editor.fileSize().toInt() if (fileSize > 0 && offset < fileSize) { val charType = charType(chars[offset], bigWord) if (charType !== CharacterHelper.CharacterType.WHITESPACE) { val lastWordChar = offset >= fileSize - 1 || charType(chars[offset + 1], bigWord) !== charType if (wordMotions.contains(id) && lastWordChar && motion.count == 1) { val res = deleteCharacter(editor, caret, 1, true, operatorArguments) if (res) { editor.vimChangeActionSwitchMode = VimStateMachine.Mode.INSERT } return res } when (id) { VIM_MOTION_WORD_RIGHT -> { kludge = true motion.action = injector.actionExecutor.findVimActionOrDie(VIM_MOTION_WORD_END_RIGHT) } VIM_MOTION_BIG_WORD_RIGHT -> { kludge = true motion.action = injector.actionExecutor.findVimActionOrDie(VIM_MOTION_BIG_WORD_END_RIGHT) } VIM_MOTION_CAMEL_RIGHT -> { kludge = true motion.action = injector.actionExecutor.findVimActionOrDie(VIM_MOTION_CAMEL_END_RIGHT) } } } } if (kludge) { val cnt = operatorArguments.count1 * motion.count val pos1 = injector.searchHelper.findNextWordEnd(chars, offset, fileSize, cnt, bigWord, false) val pos2 = injector.searchHelper.findNextWordEnd(chars, pos1, fileSize, -cnt, bigWord, false) if (logger.isDebug()) { logger.debug("pos=$offset") logger.debug("pos1=$pos1") logger.debug("pos2=$pos2") logger.debug("count=" + operatorArguments.count1) logger.debug("arg.count=" + motion.count) } if (pos2 == offset) { if (operatorArguments.count1 > 1) { count0-- } else if (motion.count > 1) { motion.count = motion.count - 1 } else { motion.flags = EnumSet.noneOf(CommandFlags::class.java) } } } return if (injector.optionService.isSet( OptionScope.GLOBAL, OptionConstants.experimentalapiName, OptionConstants.experimentalapiName ) ) { val (first, second) = getDeleteRangeAndType2( editor, caret, context, argument, true, operatorArguments.withCount0(count0) ) ?: return false // ChangeGroupKt.changeRange(((IjVimEditor) editor).getEditor(), ((IjVimCaret) caret).getCaret(), deleteRangeAndType.getFirst(), deleteRangeAndType.getSecond(), ((IjExecutionContext) context).getContext()); true } else { val (first, second) = getDeleteRangeAndType( editor, caret, context, argument, true, operatorArguments.withCount0(count0) ) ?: return false changeRange( editor, caret, first, second, context, operatorArguments ) } } /** * Inserts a new line below the caret position * * @param editor The editor to insert into * @param caret The caret to insert after * @param col The column to indent to */ private fun insertNewLineBelow(editor: VimEditor, caret: VimCaret, col: Int) { if (editor.isOneLineMode()) return caret.moveToOffset(injector.motion.moveCaretToCurrentLineEnd(editor, caret)) editor.vimChangeActionSwitchMode = VimStateMachine.Mode.INSERT insertText(editor, caret, "\n${editor.createIndentBySize(col)}") } /** * Deletes the range of text and enters insert mode * * @param editor The editor to change * @param caret The caret to be moved after range deletion * @param range The range to change * @param type The type of the range * @param operatorArguments * @return true if able to delete the range, false if not */ override fun changeRange( editor: VimEditor, caret: VimCaret, range: TextRange, type: SelectionType, context: ExecutionContext, operatorArguments: OperatorArguments, ): Boolean { var col = 0 var lines = 0 if (type === SelectionType.BLOCK_WISE) { lines = getLinesCountInVisualBlock(editor, range) col = editor.offsetToBufferPosition(range.startOffset).column if (caret.vimLastColumn == VimMotionGroupBase.LAST_COLUMN) { col = VimMotionGroupBase.LAST_COLUMN } } val after = range.endOffset >= editor.fileSize() val lp = editor.offsetToBufferPosition(injector.motion.moveCaretToCurrentLineStartSkipLeading(editor, caret)) val res = deleteRange(editor, caret, range, type, true, operatorArguments) if (res) { if (type === SelectionType.LINE_WISE) { // Please don't use `getDocument().getText().isEmpty()` because it converts CharSequence into String if (editor.fileSize() == 0L) { insertBeforeCursor(editor, context) } else if (after && !editor.endsWithNewLine()) { insertNewLineBelow(editor, caret, lp.column) } else { insertNewLineAbove(editor, caret, lp.column) } } else { if (type === SelectionType.BLOCK_WISE) { setInsertRepeat(lines, col, false) } editor.vimChangeActionSwitchMode = VimStateMachine.Mode.INSERT } } else { insertBeforeCursor(editor, context) } return true } companion object { private const val MAX_REPEAT_CHARS_COUNT = 10000 private val logger = vimLogger<VimChangeGroupBase>() /** * Counts number of lines in the visual block. * * * The result includes empty and short lines which does not have explicit start position (caret). * * @param editor The editor the block was selected in * @param range The range corresponding to the selected block * @return total number of lines */ fun getLinesCountInVisualBlock(editor: VimEditor, range: TextRange): Int { val startOffsets = range.startOffsets if (startOffsets.isEmpty()) return 0 val firstStart = editor.offsetToBufferPosition(startOffsets[0]) val lastStart = editor.offsetToBufferPosition(startOffsets[range.size() - 1]) return lastStart.line - firstStart.line + 1 } protected const val HEX_START: @NonNls String = "0x" const val VIM_MOTION_BIG_WORD_RIGHT = "VimMotionBigWordRightAction" const val VIM_MOTION_WORD_RIGHT = "VimMotionWordRightAction" const val VIM_MOTION_CAMEL_RIGHT = "VimMotionCamelRightAction" const val VIM_MOTION_WORD_END_RIGHT = "VimMotionWordEndRightAction" const val VIM_MOTION_BIG_WORD_END_RIGHT = "VimMotionBigWordEndRightAction" const val VIM_MOTION_CAMEL_END_RIGHT = "VimMotionCamelEndRightAction" const val MAX_HEX_INTEGER: @NonNls String = "ffffffffffffffff" val wordMotions: Set<String> = setOf(VIM_MOTION_WORD_RIGHT, VIM_MOTION_BIG_WORD_RIGHT, VIM_MOTION_CAMEL_RIGHT) } } fun OperatedRange.toType() = when (this) { is OperatedRange.Characters -> SelectionType.CHARACTER_WISE is OperatedRange.Lines -> SelectionType.LINE_WISE is OperatedRange.Block -> SelectionType.BLOCK_WISE }
mit
6e04dfef59a98a96fef091a0c767b76f
35.338392
212
0.679417
4.411754
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/plans/PlansListFragment.kt
1
5439
package org.wordpress.android.ui.plans import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import org.wordpress.android.R import org.wordpress.android.WordPress import org.wordpress.android.databinding.PlansListFragmentBinding import org.wordpress.android.fluxc.model.plans.PlanOffersModel import org.wordpress.android.ui.plans.PlansViewModel.PlansListStatus.ERROR import org.wordpress.android.ui.plans.PlansViewModel.PlansListStatus.ERROR_WITH_CACHE import org.wordpress.android.ui.plans.PlansViewModel.PlansListStatus.FETCHING import org.wordpress.android.util.NetworkUtils import org.wordpress.android.util.WPSwipeToRefreshHelper import org.wordpress.android.util.helpers.SwipeToRefreshHelper import javax.inject.Inject class PlansListFragment : Fragment() { private lateinit var swipeToRefreshHelper: SwipeToRefreshHelper private lateinit var viewModel: PlansViewModel @Inject lateinit var viewModelFactory: ViewModelProvider.Factory interface PlansListInterface { fun onPlanItemClicked(plan: PlanOffersModel) fun onPlansUpdating() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.plans_list_fragment, container, false) } private fun onItemClicked(item: PlanOffersModel) { viewModel.onItemClicked(item) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val nonNullActivity = requireActivity() with(PlansListFragmentBinding.bind(view)) { emptyRecyclerView.layoutManager = LinearLayoutManager(nonNullActivity, RecyclerView.VERTICAL, false) emptyRecyclerView.setEmptyView(actionableEmptyView) swipeToRefreshHelper = WPSwipeToRefreshHelper.buildSwipeToRefreshHelper(swipeRefreshLayout) { if (NetworkUtils.checkConnection(nonNullActivity)) { viewModel.onPullToRefresh() } else { swipeToRefreshHelper.isRefreshing = false } } (nonNullActivity.application as WordPress).component().inject(this@PlansListFragment) viewModel = ViewModelProvider(this@PlansListFragment, viewModelFactory).get(PlansViewModel::class.java) setObservers() viewModel.create() } } private fun PlansListFragmentBinding.reloadList(data: List<PlanOffersModel>) { setList(data) } private fun PlansListFragmentBinding.setList(list: List<PlanOffersModel>) { val adapter: PlansListAdapter if (emptyRecyclerView.adapter == null) { adapter = PlansListAdapter(requireActivity(), this@PlansListFragment::onItemClicked) emptyRecyclerView.adapter = adapter } else { adapter = emptyRecyclerView.adapter as PlansListAdapter } adapter.updateList(list) } private fun PlansListFragmentBinding.setObservers() { viewModel.plans.observe(viewLifecycleOwner, Observer { reloadList(it ?: emptyList()) }) viewModel.listStatus.observe(viewLifecycleOwner, Observer { listStatus -> if (isAdded && view != null) { swipeToRefreshHelper.isRefreshing = listStatus == FETCHING } when (listStatus) { ERROR -> { actionableEmptyView.title.text = getString(R.string.plans_loading_error_network_title) actionableEmptyView.subtitle.text = getString(R.string.plans_loading_error_no_cache_subtitle) actionableEmptyView.button.visibility = View.GONE } ERROR_WITH_CACHE -> { actionableEmptyView.title.text = getString(R.string.plans_loading_error_network_title) actionableEmptyView.subtitle.text = getString(R.string.plans_loading_error_with_cache_subtitle) actionableEmptyView.button.visibility = View.VISIBLE actionableEmptyView.button.setOnClickListener { viewModel.onShowCachedPlansButtonClicked() } } FETCHING -> { if (activity is PlansListInterface) { (activity as PlansListInterface).onPlansUpdating() } } else -> { // show generic error in case there are no plans to show for any reason actionableEmptyView.title.text = getString(R.string.plans_loading_error_no_plans_title) actionableEmptyView.subtitle.text = getString(R.string.plans_loading_error_no_plans_subtitle) actionableEmptyView.button.visibility = View.GONE } } }) viewModel.showDialog.observe(viewLifecycleOwner, Observer { if (it is PlanOffersModel && activity is PlansListInterface) { (activity as PlansListInterface).onPlanItemClicked(it) } }) } }
gpl-2.0
3d939f8c280fa047cf77070fcc57c02d
41.826772
116
0.67494
5.234841
false
false
false
false
KotlinNLP/SimpleDNN
src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/recurrent/cfn/CFNForwardHelper.kt
1
3117
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.core.layers.models.recurrent.cfn import com.kotlinnlp.simplednn.core.layers.helpers.ForwardHelper import com.kotlinnlp.simplednn.core.layers.Layer import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray /** * The helper which executes the forward on a [layer]. * * @property layer the [CFNLayer] in which the forward is executed */ internal class CFNForwardHelper<InputNDArrayType : NDArray<InputNDArrayType>>( override val layer: CFNLayer<InputNDArrayType> ) : ForwardHelper<InputNDArrayType>(layer) { /** * Forward the input to the output combining it with the parameters. * * y = inG * c + f(yPrev) * forG */ override fun forward() { val prevStateLayer = this.layer.layersWindow.getPrevState() this.setGates(prevStateLayer) // must be called before accessing to the activated values of the gates val y: DenseNDArray = this.layer.outputArray.values val c: DenseNDArray = this.layer.candidate.values val inG: DenseNDArray = this.layer.inputGate.values val forG: DenseNDArray = this.layer.forgetGate.values // y = inG * c y.assignProd(inG, c) // y += f(yPrev) * forG if (prevStateLayer != null) { val yPrev = prevStateLayer.outputArray.values this.layer.activatedPrevOutput = if (this.layer.activationFunction != null) this.layer.activationFunction.f(yPrev) else yPrev y.assignSum(this.layer.activatedPrevOutput!!.prod(forG)) } } /** * Set gates values * * inG = sigmoid(wIn (dot) x + bIn + wrIn (dot) yPrev) * forG = sigmoid(wForG (dot) x + bForG + wrForG (dot) yPrev) * c = f(wc (dot) x) */ private fun setGates(prevStateLayer: Layer<*>?) { val x: InputNDArrayType = this.layer.inputArray.values val c: DenseNDArray = this.layer.candidate.values val wc: DenseNDArray = this.layer.params.candidateWeights.values this.layer.inputGate.forward( w = this.layer.params.inputGate.weights.values, b = this.layer.params.inputGate.biases.values, x = x ) this.layer.forgetGate.forward( w = this.layer.params.forgetGate.weights.values, b = this.layer.params.forgetGate.biases.values, x = x ) c.assignDot(wc, x) if (prevStateLayer != null) { // recurrent contribution for input and forget gates val yPrev = prevStateLayer.outputArray.valuesNotActivated this.layer.inputGate.addRecurrentContribution(this.layer.params.inputGate, yPrev) this.layer.forgetGate.addRecurrentContribution(this.layer.params.forgetGate, yPrev) } this.layer.inputGate.activate() this.layer.forgetGate.activate() this.layer.candidate.activate() } }
mpl-2.0
456430df8ba10bec8fe4e84b84123f32
32.516129
105
0.691049
3.843403
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinCovariantEqualsInspection.kt
1
2717
// 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.inspections import com.intellij.codeInspection.ProblemsHolder import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtObjectDeclaration import org.jetbrains.kotlin.psi.namedFunctionVisitor import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.typeUtil.isBoolean import org.jetbrains.kotlin.types.typeUtil.isNullableAny import org.jetbrains.kotlin.util.OperatorNameConventions import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection class KotlinCovariantEqualsInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = namedFunctionVisitor(fun(function) { if (function.isTopLevel || function.isLocal) return if (function.nameAsName != OperatorNameConventions.EQUALS) return val nameIdentifier = function.nameIdentifier ?: return val classOrObject = function.containingClassOrObject ?: return if (classOrObject is KtObjectDeclaration && classOrObject.isCompanion()) return val parameter = function.valueParameters.singleOrNull() ?: return val typeReference = parameter.typeReference ?: return val type = parameter.analyze(BodyResolveMode.PARTIAL)[BindingContext.TYPE, typeReference] ?: return if (KotlinBuiltIns.isNullableAny(type)) return if (classOrObject.body?.children?.any { (it as? KtNamedFunction)?.isEquals() == true } == true) return holder.registerProblem(nameIdentifier, KotlinBundle.message("equals.should.take.any.as.its.argument")) }) private fun KtNamedFunction.isEquals(): Boolean { if (!hasModifier(KtTokens.OVERRIDE_KEYWORD)) return false if (nameAsName != OperatorNameConventions.EQUALS) return false val descriptor = this.descriptor as? FunctionDescriptor ?: return false if (descriptor.valueParameters.singleOrNull()?.type?.isNullableAny() != true) return false if (descriptor.returnType?.isBoolean() != true) return false return true } }
apache-2.0
2660a6f3a3024109e3e81639cad65fa1
53.36
158
0.783585
5.003683
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/plugin-updater/src/org/jetbrains/kotlin/idea/versions/UnsupportedAbiVersionNotificationPanelProvider.kt
1
15731
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.versions import com.intellij.icons.AllIcons import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.compiler.CompilerManager import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.IndexNotReadyException import com.intellij.openapi.project.Project import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.PopupStep import com.intellij.openapi.ui.popup.util.BaseListPopupStep import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.Ref import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.* import com.intellij.ui.EditorNotificationProvider.* import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NotNull import org.jetbrains.kotlin.idea.* import org.jetbrains.kotlin.idea.base.facet.platform.platform import org.jetbrains.kotlin.idea.base.util.createComponentActionLabel import org.jetbrains.kotlin.idea.compiler.configuration.KotlinIdePlugin import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout import org.jetbrains.kotlin.idea.projectConfiguration.KotlinNotConfiguredSuppressedModulesState import org.jetbrains.kotlin.idea.projectConfiguration.LibraryJarDescriptor import org.jetbrains.kotlin.idea.projectConfiguration.updateLibraries import org.jetbrains.kotlin.idea.update.KotlinPluginUpdaterBundle import org.jetbrains.kotlin.idea.util.application.invokeLater import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.isKotlinFileType import org.jetbrains.kotlin.metadata.deserialization.BinaryVersion import org.jetbrains.kotlin.platform.js.isJs import org.jetbrains.kotlin.platform.jvm.isJvm import java.awt.event.ComponentAdapter import java.awt.event.ComponentEvent import java.util.function.Function import javax.swing.Icon import javax.swing.JComponent import javax.swing.JLabel import javax.swing.event.HyperlinkEvent class UnsupportedAbiVersionNotificationPanelProvider : EditorNotificationProvider { private fun doCreate(fileEditor: FileEditor, project: Project, badVersionedRoots: Collection<BinaryVersionedFile<BinaryVersion>>): EditorNotificationPanel { val answer = ErrorNotificationPanel(fileEditor) val badRootFiles = badVersionedRoots.map { it.file } val badRuntimeLibraries: List<Library> = ArrayList<Library>().also { list -> project.forEachAllUsedLibraries { library -> val runtimeJar = LibraryJarDescriptor.STDLIB_JAR.findExistingJar(library)?.let { VfsUtil.getLocalFile(it) } val jsLibJar = LibraryJarDescriptor.JS_STDLIB_JAR.findExistingJar(library)?.let { VfsUtil.getLocalFile(it) } if (badRootFiles.contains(runtimeJar) || badRootFiles.contains(jsLibJar)) { list.add(library) } return@forEachAllUsedLibraries true } } val isPluginOldForAllRoots = badVersionedRoots.all { it.supportedVersion < it.version } val isPluginNewForAllRoots = badVersionedRoots.all { it.supportedVersion > it.version } when { badRuntimeLibraries.isNotEmpty() -> { val badRootsInRuntimeLibraries = findBadRootsInRuntimeLibraries(badRuntimeLibraries, badVersionedRoots) val otherBadRootsCount = badVersionedRoots.size - badRootsInRuntimeLibraries.size val text = KotlinPluginUpdaterBundle.htmlMessage( "html.b.0.choice.0.1.1.some.kotlin.runtime.librar.0.choice.0.1.y.1.ies.b.1.choice.0.1.and.one.other.jar.1.and.1.other.jars.1.choice.0.has.0.have.an.unsupported.binary.format.html", badRuntimeLibraries.size, otherBadRootsCount ) answer.text = text if (isPluginOldForAllRoots) { createUpdatePluginLink(answer) } val isPluginOldForAllRuntimeLibraries = badRootsInRuntimeLibraries.all { it.supportedVersion < it.version } val isPluginNewForAllRuntimeLibraries = badRootsInRuntimeLibraries.all { it.supportedVersion > it.version } val updateAction = when { isPluginNewForAllRuntimeLibraries -> KotlinPluginUpdaterBundle.message("button.text.update.library") isPluginOldForAllRuntimeLibraries -> KotlinPluginUpdaterBundle.message("button.text.downgrade.library") else -> KotlinPluginUpdaterBundle.message("button.text.replace.library") } val actionLabelText = "$updateAction " + KotlinPluginUpdaterBundle.message( "0.choice.0.1.1.all.kotlin.runtime.librar.0.choice.0.1.y.1.ies", badRuntimeLibraries.size ) answer.createActionLabel(actionLabelText) { ApplicationManager.getApplication().invokeLater { val newArtifactVersion = KotlinPluginLayout.standaloneCompilerVersion.artifactVersion updateLibraries(project, newArtifactVersion, badRuntimeLibraries) } } } badVersionedRoots.size == 1 -> { val badVersionedRoot = badVersionedRoots.first() val presentableName = badVersionedRoot.file.presentableName when { isPluginOldForAllRoots -> { answer.text = KotlinPluginUpdaterBundle.htmlMessage( "html.kotlin.library.b.0.b.was.compiled.with.a.newer.kotlin.compiler.and.can.t.be.read.please.update.kotlin.plugin.html", presentableName ) createUpdatePluginLink(answer) } isPluginNewForAllRoots -> answer.text = KotlinPluginUpdaterBundle.htmlMessage( "html.kotlin.library.b.0.b.has.outdated.binary.format.and.can.t.be.read.by.current.plugin.please.update.the.library.html", presentableName ) else -> { throw IllegalStateException("Bad root with compatible version found: $badVersionedRoot") } } answer.createActionLabel(KotlinPluginUpdaterBundle.message("button.text.go.to.0", presentableName)) { navigateToLibraryRoot( project, badVersionedRoot.file ) } } isPluginOldForAllRoots -> { answer.text = KotlinPluginUpdaterBundle.message("some.kotlin.libraries.attached.to.this.project.were.compiled.with.a.newer.kotlin.compiler.and.can.t.be.read.please.update.kotlin.plugin") createUpdatePluginLink(answer) } isPluginNewForAllRoots -> answer.setText( KotlinPluginUpdaterBundle.message("some.kotlin.libraries.attached.to.this.project.have.outdated.binary.format.and.can.t.be.read.by.current.plugin.please.update.found.libraries") ) else -> answer.setText(KotlinPluginUpdaterBundle.message("some.kotlin.libraries.attached.to.this.project.have.unsupported.binary.format.please.update.the.libraries.or.the.plugin")) } createShowPathsActionLabel(project, badVersionedRoots, answer, KotlinPluginUpdaterBundle.message("button.text.details")) return answer } private fun createShowPathsActionLabel( project: Project, badVersionedRoots: Collection<BinaryVersionedFile<BinaryVersion>>, answer: EditorNotificationPanel, @NlsContexts.LinkLabel labelText: String ) { answer.createComponentActionLabel(labelText) { label -> val task = { assert(!badVersionedRoots.isEmpty()) { "This action should only be called when bad roots are present" } val listPopupModel = LibraryRootsPopupModel( KotlinPluginUpdaterBundle.message("unsupported.format.plugin.version.0", KotlinIdePlugin.version), project, badVersionedRoots ) val popup = JBPopupFactory.getInstance().createListPopup(listPopupModel) popup.showUnderneathOf(label) null } DumbService.getInstance(project).tryRunReadActionInSmartMode( task, KotlinPluginUpdaterBundle.message("can.t.show.all.paths.during.index.update") ) } } private fun createUpdatePluginLink(answer: ErrorNotificationPanel) { answer.createProgressAction( KotlinPluginUpdaterBundle.message("progress.action.text.check"), KotlinPluginUpdaterBundle.message("progress.action.text.update.plugin") ) { link, updateLink -> KotlinPluginUpdater.getInstance().runCachedUpdate { pluginUpdateStatus -> when (pluginUpdateStatus) { is PluginUpdateStatus.Update -> { link.isVisible = false updateLink.isVisible = true updateLink.addHyperlinkListener(object : HyperlinkAdapter() { override fun hyperlinkActivated(e: HyperlinkEvent) { KotlinPluginUpdater.getInstance().installPluginUpdate(pluginUpdateStatus) } }) } is PluginUpdateStatus.LatestVersionInstalled -> { link.text = KotlinPluginUpdaterBundle.message("no.updates.found") } else -> {} } false // do not auto-retry update check } } } override fun collectNotificationData(project: Project, file: VirtualFile): Function<in FileEditor, out JComponent?> { if (!file.isKotlinFileType()) { return CONST_NULL } try { if ( DumbService.isDumb(project) || isUnitTestMode() || CompilerManager.getInstance(project).isExcludedFromCompilation(file) || KotlinNotConfiguredSuppressedModulesState.isSuppressed(project) ) { return CONST_NULL } val module = ModuleUtilCore.findModuleForFile(file, project) ?: return CONST_NULL val badRoots: Collection<BinaryVersionedFile<BinaryVersion>> = getLibraryRootsWithIncompatibleAbi(module) .takeUnless(Collection<BinaryVersionedFile<BinaryVersion>>::isEmpty) ?: return CONST_NULL return Function { doCreate(it, project, badRoots) } } catch (e: ProcessCanceledException) { // Ignore } catch (e: IndexNotReadyException) { DumbService.getInstance(project).runWhenSmart { updateNotifications(project) } } return CONST_NULL } private fun findBadRootsInRuntimeLibraries( badRuntimeLibraries: List<Library>, badVersionedRoots: Collection<BinaryVersionedFile<BinaryVersion>> ): ArrayList<BinaryVersionedFile<BinaryVersion>> { val badRootsInLibraries = ArrayList<BinaryVersionedFile<BinaryVersion>>() fun addToBadRoots(file: VirtualFile?) { if (file != null) { val runtimeJarBadRoot = badVersionedRoots.firstOrNull { it.file == file } if (runtimeJarBadRoot != null) { badRootsInLibraries.add(runtimeJarBadRoot) } } } badRuntimeLibraries.forEach { library -> for (descriptor in LibraryJarDescriptor.values()) { addToBadRoots(descriptor.findExistingJar(library)?.let<VirtualFile, @NotNull VirtualFile> { VfsUtil.getLocalFile(it) }) } } return badRootsInLibraries } private class LibraryRootsPopupModel( @NlsContexts.PopupTitle title: String, private val project: Project, roots: Collection<BinaryVersionedFile<BinaryVersion>> ) : BaseListPopupStep<BinaryVersionedFile<BinaryVersion>>(title, *roots.toTypedArray()) { override fun getTextFor(root: BinaryVersionedFile<BinaryVersion>): String { val relativePath = VfsUtilCore.getRelativePath(root.file, project.baseDir, '/') return KotlinPluginUpdaterBundle.message("0.1.expected.2", relativePath ?: root.file.path, root.version, root.supportedVersion) } override fun getIconFor(aValue: BinaryVersionedFile<BinaryVersion>): Icon = if (aValue.file.isDirectory) { AllIcons.Nodes.Folder } else { AllIcons.FileTypes.Archive } override fun onChosen(selectedValue: BinaryVersionedFile<BinaryVersion>, finalChoice: Boolean): PopupStep<*>? { navigateToLibraryRoot(project, selectedValue.file) return PopupStep.FINAL_CHOICE } override fun isSpeedSearchEnabled(): Boolean = true } private class ErrorNotificationPanel(fileEditor: FileEditor) : EditorNotificationPanel(fileEditor) { init { myLabel.icon = AllIcons.General.Error } fun createProgressAction(@Nls text: String, @Nls successLinkText: String, updater: (JLabel, HyperlinkLabel) -> Unit) { val label = JLabel(text) myLinksPanel.add(label) val successLink = createActionLabel(successLinkText) { } successLink.isVisible = false // Several notification panels can be created almost instantly but we want to postpone deferred checks until // panels are actually visible on screen. myLinksPanel.addComponentListener(object : ComponentAdapter() { var isUpdaterCalled = false override fun componentResized(p0: ComponentEvent?) { if (!isUpdaterCalled) { isUpdaterCalled = true updater(label, successLink) } } }) } } private fun updateNotifications(project: Project) { invokeLater { if (!project.isDisposed) { EditorNotifications.getInstance(project).updateAllNotifications() } } } companion object { private fun navigateToLibraryRoot(project: Project, root: VirtualFile) { OpenFileDescriptor(project, root).navigate(true) } } } private operator fun BinaryVersion.compareTo(other: BinaryVersion): Int { val first = this.toArray() val second = other.toArray() for (i in 0 until maxOf(first.size, second.size)) { val thisPart = first.getOrNull(i) ?: -1 val otherPart = second.getOrNull(i) ?: -1 if (thisPart != otherPart) { return thisPart - otherPart } } return 0 }
apache-2.0
b589e3816dfb96019e1e3b641bcb347c
43.817664
200
0.647066
5.195178
false
false
false
false
Yubico/yubioath-android
app/src/main/kotlin/com/yubico/yubioath/ui/main/CredentialFragment.kt
1
19203
package com.yubico.yubioath.ui.main import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.app.Activity import android.content.ActivityNotFoundException import android.content.ClipData import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build import android.os.Bundle import android.provider.MediaStore import android.view.* import android.view.animation.* import android.view.inputmethod.InputMethodManager import android.widget.AdapterView import android.widget.ImageView import android.widget.TextView import androidx.annotation.RequiresApi import androidx.annotation.StringRes import androidx.appcompat.app.AlertDialog import androidx.core.content.ContextCompat import androidx.fragment.app.ListFragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.google.android.material.snackbar.Snackbar import com.pixplicity.sharp.Sharp import com.yubico.yubikitold.application.oath.OathType import com.yubico.yubioath.R import com.yubico.yubioath.client.Code import com.yubico.yubioath.client.Credential import com.yubico.yubioath.client.CredentialData import com.yubico.yubioath.isGooglePlayAvailable import com.yubico.yubioath.startQrCodeAcitivty import com.yubico.yubioath.ui.add.AddCredentialActivity import kotlinx.android.synthetic.main.fragment_credentials.* import kotlinx.coroutines.* import org.jetbrains.anko.clipboardManager import org.jetbrains.anko.inputMethodManager import org.jetbrains.anko.toast import kotlin.coroutines.CoroutineContext import kotlin.math.min const val QR_DATA = "QR_DATA" class CredentialFragment : ListFragment(), CoroutineScope { companion object { private const val REQUEST_ADD_CREDENTIAL = 1 private const val REQUEST_SELECT_ICON = 2 private const val REQUEST_SCAN_QR = 3 private const val REQUEST_SCAN_QR_EXTERNAL = 4 } private lateinit var job: Job override val coroutineContext: CoroutineContext get() = Dispatchers.Main + job private val viewModel: OathViewModel by lazy { ViewModelProviders.of(activity!!).get(OathViewModel::class.java) } private val timerAnimation = object : Animation() { var deadline: Long = 0 init { duration = 30000 interpolator = LinearInterpolator() } override fun applyTransformation(interpolatedTime: Float, t: Transformation) { progressBar.progress = ((1.0 - interpolatedTime) * 1000).toInt() } } private var actionMode: ActionMode? = null private val adapter: CredentialAdapter by lazy { listAdapter as CredentialAdapter } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) job = Job() } override fun onDestroy() { job.cancel() super.onDestroy() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { return inflater.inflate(R.layout.fragment_credentials, container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) val actions = object : CredentialAdapter.ActionHandler { override fun select(position: Int) = selectItem(position) override fun calculate(credential: Credential) { viewModel.calculate(credential).let { job -> launch { if (viewModel.deviceInfo.value!!.persistent) { delay(100) // Delay enough to only prompt when touch is required. } jobWithClient(job, 0, job.isActive) } } } override fun copy(code: Code) { activity?.let { val clipboard = it.clipboardManager val clip = ClipData.newPlainText("OTP", code.value) clipboard.setPrimaryClip(clip) it.toast(R.string.copied) } } } listAdapter = CredentialAdapter(context!!, actions, viewModel.creds.value.orEmpty()) viewModel.filteredCreds.observe(activity!!, Observer { filteredCreds -> view?.findViewById<TextView>(android.R.id.empty)?.setText(when { viewModel.deviceInfo.value!!.persistent -> R.string.no_credentials !viewModel.searchFilter.value.isNullOrEmpty() && !viewModel.creds.value.isNullOrEmpty() -> R.string.no_match else -> R.string.swipe_and_hold }) listView.alpha = 1f swipe_clear_layout.isEnabled = !filteredCreds.isNullOrEmpty() adapter.creds = filteredCreds progressBar?.apply { val validFrom = filteredCreds.filterKeys { it.type == OathType.TOTP && it.period == 30 && !it.touch }.values.firstOrNull()?.validFrom if (validFrom != null) { val validTo = validFrom + 30000 if (!timerAnimation.hasStarted() || timerAnimation.deadline != validTo) { val now = System.currentTimeMillis() startAnimation(timerAnimation.apply { deadline = validTo duration = validTo - min(now, validFrom) startOffset = min(0, validFrom - now) }) } } else { clearAnimation() progress = 0 timerAnimation.deadline = 0 } } }) listView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ -> actionMode?.apply { if (listView.isItemChecked(position)) { finish() } else { selectItem(position) } } ?: listView.setItemChecked(position, false) } listView.onItemLongClickListener = AdapterView.OnItemLongClickListener { _, _, position, _ -> selectItem(position) true } viewModel.selectedItem?.let { selectItem(adapter.getPosition(it), false) } fab.setOnClickListener { showAddToolbar() } btn_close_toolbar_add.setOnClickListener { hideAddToolbar() } btn_scan_qr.setOnClickListener { hideAddToolbar() if (it.context.isGooglePlayAvailable()) { startQrCodeAcitivty(REQUEST_SCAN_QR) } else { tryOpeningExternalQrReader() } } btn_manual_entry.setOnClickListener { hideAddToolbar() startActivityForResult(Intent(context, AddCredentialActivity::class.java), REQUEST_ADD_CREDENTIAL) } fixSwipeClearDrawable() swipe_clear_layout.apply { //isEnabled = !listAdapter.isEmpty setOnRefreshListener { isRefreshing = false actionMode?.finish() if (viewModel.deviceInfo.value!!.persistent) { viewModel.clearCredentials() } else { listView.animate().apply { alpha(0f) duration = 195 interpolator = LinearInterpolator() setListener(object : Animator.AnimatorListener { override fun onAnimationRepeat(animation: Animator?) = Unit override fun onAnimationCancel(animation: Animator?) = Unit override fun onAnimationStart(animation: Animator?) = Unit override fun onAnimationEnd(animation: Animator?) { viewModel.clearCredentials() } }) }.start() } } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) fun handleUrlCredential(context: Context, data: String?) { if (data != null) { try { val uri = Uri.parse(data) CredentialData.fromUri(uri) startActivityForResult(Intent(Intent.ACTION_VIEW, uri, context, AddCredentialActivity::class.java), REQUEST_ADD_CREDENTIAL) } catch (e: IllegalArgumentException) { context.toast(R.string.invalid_barcode) } } else { context.toast(R.string.invalid_barcode) } } activity?.apply { if (resultCode == Activity.RESULT_OK && data != null) when (requestCode) { REQUEST_ADD_CREDENTIAL -> { toast(R.string.add_credential_success) val credential: Credential = data.getParcelableExtra(AddCredentialActivity.EXTRA_CREDENTIAL) val code: Code? = if (data.hasExtra(AddCredentialActivity.EXTRA_CODE)) data.getParcelableExtra(AddCredentialActivity.EXTRA_CODE) else null viewModel.insertCredential(credential, code) } REQUEST_SELECT_ICON -> { viewModel.selectedItem?.let { credential -> try { try { val icon = MediaStore.Images.Media.getBitmap(contentResolver, data.data) adapter.setIcon(credential, icon) } catch (e: IllegalStateException) { val svg = Sharp.loadInputStream(contentResolver.openInputStream(data.data!!)) adapter.setIcon(credential, svg.drawable) } } catch (e: Exception) { toast(R.string.invalid_image) } } actionMode?.finish() } REQUEST_SCAN_QR -> { handleUrlCredential(this, data.dataString) } REQUEST_SCAN_QR_EXTERNAL -> { handleUrlCredential(this, data.getStringExtra("SCAN_RESULT")) } } else if (requestCode == REQUEST_ADD_CREDENTIAL && resultCode == Activity.RESULT_CANCELED) { inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0) } } } private fun tryOpeningExternalQrReader() { try { startActivityForResult(Intent("com.google.zxing.client.android.SCAN").apply { putExtra("SCAN_MODE", "QR_CODE_MODE") putExtra("SAVE_HISTORY", false) }, REQUEST_SCAN_QR_EXTERNAL) } catch (e: ActivityNotFoundException) { activity?.toast(R.string.external_qr_scanner_missing) } } private fun fixSwipeClearDrawable() { //Hack that changes the drawable using reflection. swipe_clear_layout.javaClass.getDeclaredField("mCircleView").apply { isAccessible = true (get(swipe_clear_layout) as ImageView).setImageResource(R.drawable.ic_close_gray_24dp) } } private fun hideAddToolbar(showFab: Boolean = true) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //Hide toolbar val cx = (fab.left + fab.right) / 2 - toolbar_add.x.toInt() val cy = toolbar_add.height / 2 ViewAnimationUtils.createCircularReveal(toolbar_add, cx, cy, toolbar_add.width * 2f, 0f).apply { addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator?) { toolbar_add.visibility = View.INVISIBLE //Show fab if (showFab) { val deltaY = (toolbar_add.top + toolbar_add.bottom - (fab.top + fab.bottom)) / 2f fab.startAnimation(TranslateAnimation(0f, 0f, deltaY, 0f).apply { interpolator = DecelerateInterpolator() duration = 50 }) fab.visibility = View.VISIBLE } } }) }.start() } else { toolbar_add.visibility = View.INVISIBLE if (showFab) { fab.show() } } } private fun showAddToolbar() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //Hide fab val deltaY = (toolbar_add.top + toolbar_add.bottom - (fab.top + fab.bottom)) / 2f fab.startAnimation(TranslateAnimation(0f, 0f, 0f, deltaY).apply { interpolator = AccelerateInterpolator() duration = 50 setAnimationListener(object : Animation.AnimationListener { override fun onAnimationStart(animation: Animation?) = Unit override fun onAnimationRepeat(animation: Animation?) = Unit @RequiresApi(Build.VERSION_CODES.LOLLIPOP) override fun onAnimationEnd(animation: Animation?) { //Show toolbar toolbar_add.visibility = View.VISIBLE val cx = (fab.left + fab.right) / 2 - toolbar_add.x.toInt() val cy = toolbar_add.height / 2 ViewAnimationUtils.createCircularReveal(toolbar_add, cx, cy, fab.width / 2f, view!!.width * 2f).start() fab.visibility = View.INVISIBLE } }) }) } else { toolbar_add.visibility = View.VISIBLE fab.hide() } } private fun snackbar(@StringRes message: Int, duration: Int): Snackbar { return Snackbar.make(view!!, message, duration).apply { setActionTextColor(ContextCompat.getColor(context, R.color.yubicoPrimaryGreen)) //This doesn't seem to be directly styleable, unfortunately. addCallback(object : Snackbar.Callback() { override fun onDismissed(transientBottomBar: Snackbar?, event: Int) { if (!fab.isShown && !toolbar_add.isShown) fab.show() } }) if (toolbar_add.isShown) { hideAddToolbar(false) } else { fab.hide() } show() } } private fun jobWithClient(job: Job, @StringRes successMessage: Int, needsTouch: Boolean) { job.invokeOnCompletion { launch { if (!job.isCancelled && successMessage != 0) { activity?.toast(successMessage) } } } if (!viewModel.deviceInfo.value!!.persistent || needsTouch) { snackbar(R.string.swipe_and_hold, Snackbar.LENGTH_INDEFINITE).apply { job.invokeOnCompletion { dismiss() } setAction(R.string.cancel) { job.cancel() } } } } private fun selectItem(position: Int, updateViewModel: Boolean = true) { val credential = adapter.getItem(position).key if (updateViewModel) { viewModel.selectedItem = credential } activity?.let { act -> (actionMode ?: act.startActionMode(object : ActionMode.Callback { override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { when (item.itemId) { R.id.pin -> { adapter.setPinned(credential, !adapter.isPinned(credential)) actionMode?.finish() } R.id.change_icon -> { AlertDialog.Builder(act) .setTitle("Select icon") .setItems(R.array.icon_choices) { _, choice -> when (choice) { 0 -> startActivityForResult(Intent.createChooser(Intent().apply { type = "image/*" action = Intent.ACTION_GET_CONTENT }, "Select icon"), REQUEST_SELECT_ICON) 1 -> { adapter.removeIcon(credential) actionMode?.finish() } } } .setNegativeButton(R.string.cancel, null) .show() return true } R.id.delete -> viewModel.apply { selectedItem?.let { AlertDialog.Builder(act) .setTitle(R.string.delete_cred) .setMessage(R.string.delete_cred_message) .setPositiveButton(R.string.delete) { _, _ -> selectedItem = null jobWithClient(viewModel.delete(it), R.string.deleted, false) actionMode?.finish() } .setNegativeButton(R.string.cancel, null) .show() } } } return true } override fun onCreateActionMode(mode: ActionMode, menu: Menu?): Boolean { mode.menuInflater.inflate(R.menu.code_select_actions, menu) return true } override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?) = false override fun onDestroyActionMode(mode: ActionMode?) { actionMode = null listView.setItemChecked(listView.checkedItemPosition, false) viewModel.selectedItem = null } }).apply { actionMode = this })?.apply { menu.findItem(R.id.pin).setIcon(if (adapter.isPinned(credential)) R.drawable.ic_star_24dp else R.drawable.ic_star_border_24dp) title = (credential.issuer?.let { "$it: " } ?: "") + credential.name } } listView.setItemChecked(position, true) } }
bsd-2-clause
49d2fa67093659681d81d9b3b6f9a938
41.673333
158
0.531792
5.534006
false
false
false
false
WhisperSystems/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/components/settings/conversation/sounds/custom/CustomNotificationsSettingsRepository.kt
1
3905
package org.thoughtcrime.securesms.components.settings.conversation.sounds.custom import android.content.Context import android.net.Uri import androidx.annotation.WorkerThread import org.signal.core.util.concurrent.SignalExecutors import org.thoughtcrime.securesms.database.DatabaseFactory import org.thoughtcrime.securesms.database.RecipientDatabase import org.thoughtcrime.securesms.keyvalue.SignalStore import org.thoughtcrime.securesms.notifications.NotificationChannels import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.recipients.RecipientId import org.thoughtcrime.securesms.util.concurrent.SerialExecutor class CustomNotificationsSettingsRepository(context: Context) { private val context = context.applicationContext private val executor = SerialExecutor(SignalExecutors.BOUNDED) fun initialize(recipientId: RecipientId, onInitializationComplete: () -> Unit) { executor.execute { val recipient = Recipient.resolved(recipientId) val database = DatabaseFactory.getRecipientDatabase(context) if (NotificationChannels.supported() && recipient.notificationChannel != null) { database.setMessageRingtone(recipient.id, NotificationChannels.getMessageRingtone(context, recipient)) database.setMessageVibrate(recipient.id, RecipientDatabase.VibrateState.fromBoolean(NotificationChannels.getMessageVibrate(context, recipient))) NotificationChannels.ensureCustomChannelConsistency(context) } onInitializationComplete() } } fun setHasCustomNotifications(recipientId: RecipientId, hasCustomNotifications: Boolean) { executor.execute { if (hasCustomNotifications) { createCustomNotificationChannel(recipientId) } else { deleteCustomNotificationChannel(recipientId) } } } fun setMessageVibrate(recipientId: RecipientId, vibrateState: RecipientDatabase.VibrateState) { executor.execute { val recipient: Recipient = Recipient.resolved(recipientId) DatabaseFactory.getRecipientDatabase(context).setMessageVibrate(recipient.id, vibrateState) NotificationChannels.updateMessageVibrate(context, recipient, vibrateState) } } fun setCallingVibrate(recipientId: RecipientId, vibrateState: RecipientDatabase.VibrateState) { executor.execute { DatabaseFactory.getRecipientDatabase(context).setCallVibrate(recipientId, vibrateState) } } fun setMessageSound(recipientId: RecipientId, sound: Uri?) { executor.execute { val recipient: Recipient = Recipient.resolved(recipientId) val defaultValue = SignalStore.settings().messageNotificationSound val newValue: Uri? = if (defaultValue == sound) null else sound ?: Uri.EMPTY DatabaseFactory.getRecipientDatabase(context).setMessageRingtone(recipient.id, newValue) NotificationChannels.updateMessageRingtone(context, recipient, newValue) } } fun setCallSound(recipientId: RecipientId, sound: Uri?) { executor.execute { val defaultValue = SignalStore.settings().callRingtone val newValue: Uri? = if (defaultValue == sound) null else sound ?: Uri.EMPTY DatabaseFactory.getRecipientDatabase(context).setCallRingtone(recipientId, newValue) } } @WorkerThread private fun createCustomNotificationChannel(recipientId: RecipientId) { val recipient: Recipient = Recipient.resolved(recipientId) val channelId = NotificationChannels.createChannelFor(context, recipient) DatabaseFactory.getRecipientDatabase(context).setNotificationChannel(recipient.id, channelId) } @WorkerThread private fun deleteCustomNotificationChannel(recipientId: RecipientId) { val recipient: Recipient = Recipient.resolved(recipientId) DatabaseFactory.getRecipientDatabase(context).setNotificationChannel(recipient.id, null) NotificationChannels.deleteChannelFor(context, recipient) } }
gpl-3.0
d1b93d1c837cf980caf89a8f3f65568e
40.542553
152
0.788476
5.25572
false
true
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/refactoring/inline/InlineCacheTest.kt
7
2895
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.refactoring.inline import com.intellij.psi.* import com.intellij.testFramework.LightPlatformCodeInsightTestCase import junit.framework.TestCase import org.jetbrains.kotlin.idea.codeInliner.UsageReplacementStrategy import org.jetbrains.kotlin.idea.refactoring.inline.J2KInlineCache.Companion.findUsageReplacementStrategy import org.jetbrains.kotlin.idea.refactoring.inline.J2KInlineCache.Companion.setUsageReplacementStrategy import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtReferenceExpression class InlineCacheTest : LightPlatformCodeInsightTestCase() { fun `test valid value`() { val method = createJavaMethod() method.setUsageReplacementStrategy(strategy) TestCase.assertNotNull(method.findUsageReplacementStrategy(withValidation = true)) TestCase.assertNotNull(method.findUsageReplacementStrategy(withValidation = false)) } fun `test valid value after change`() { val method = createJavaMethod() method.setUsageReplacementStrategy(strategy) val originalText = method.text val body = method.body val javaExpression = createJavaDeclaration() val newElement = body?.addAfter(javaExpression, body.statements.first()) TestCase.assertTrue(originalText != method.text) newElement?.delete() TestCase.assertTrue(originalText == method.text) TestCase.assertNotNull(method.findUsageReplacementStrategy(withValidation = true)) TestCase.assertNotNull(method.findUsageReplacementStrategy(withValidation = false)) } fun `test invalid value`() { val method = createJavaMethod() method.setUsageReplacementStrategy(strategy) val originalText = method.text method.body?.statements?.firstOrNull()?.delete() TestCase.assertTrue(originalText != method.text) TestCase.assertNull(method.findUsageReplacementStrategy(withValidation = true)) TestCase.assertNotNull(method.findUsageReplacementStrategy(withValidation = false)) } private fun createJavaMethod(): PsiMethod = javaFactory.createMethodFromText( """void dummyFunction() { | int a = 4; |} """.trimMargin(), null, ) private fun createJavaDeclaration(): PsiDeclarationStatement = javaFactory.createVariableDeclarationStatement( "number", PsiType.INT, javaFactory.createExpressionFromText("1 + 3", null), ) private val javaFactory: PsiElementFactory get() = JavaPsiFacade.getElementFactory(project) private val strategy = object : UsageReplacementStrategy { override fun createReplacer(usage: KtReferenceExpression): () -> KtElement? = TODO() } }
apache-2.0
2e29164a0a55c128b3e4411187f1be7a
42.878788
120
0.733333
5.351201
false
true
false
false
GunoH/intellij-community
plugins/full-line/src/org/jetbrains/completion/full/line/utils.kt
2
2711
package org.jetbrains.completion.full.line import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.util.NlsSafe import com.intellij.psi.PsiFile import com.intellij.util.ExceptionUtil import org.jetbrains.completion.full.line.providers.CloudExceptionWithCustomRegistry import java.net.SocketException import java.net.SocketTimeoutException import java.net.UnknownHostException import java.util.concurrent.* fun <T> Future<T>.awaitWithCheckCanceled(start: Long, timeout: Int, indicator: ProgressIndicator): T { while (true) { if (System.currentTimeMillis() - start > timeout) { throw TimeoutException("Completion timeout exceeded") } indicator.checkCanceled() try { return get(10, TimeUnit.MILLISECONDS) } catch (ignore: TimeoutException) { } catch (e: Throwable) { val cause = e.cause if (cause is ProcessCanceledException) { throw (cause as ProcessCanceledException?)!! } if (cause is CancellationException) { throw ProcessCanceledException(cause) } ExceptionUtil.rethrowUnchecked(e) throw RuntimeException(e) } } } // Completion Contributor fun PsiFile.projectFilePath(): String { val projectPath = project.basePath ?: "/" val filePath = virtualFile.path return filePath.removePrefix(projectPath).removePrefix("/") } // Extract correct presentable message from exception. @NlsSafe fun Throwable.decoratedMessage(): String { return when (this) { is SocketTimeoutException, is TimeoutException -> "Connection timeout" is UnknownHostException, is SocketException -> "Can't reach completion server" is ExecutionException -> { when (cause) { null -> "Execution exception, no cause.".also { Logger.getInstance("FLCC-ExecutionException").error(this) } is CloudExceptionWithCustomRegistry -> with(cause as CloudExceptionWithCustomRegistry) { (cause?.decoratedMessage() ?: "") + "\n With custom registry `${registry.key}` value `${registry.asString()}`" } else -> with(ExceptionUtil.getRootCause(this)) { if (this is ExecutionException) "Execution exception" else decoratedMessage() } } } else -> this.localizedMessage } } fun ProjectManager.currentOpenProject() = openProjects.firstOrNull { it.isOpen } inline fun <T> measureTimeMillisWithResult(block: () -> T): Pair<Long, T> { val start = System.currentTimeMillis() val res = block() return (System.currentTimeMillis() - start) to res }
apache-2.0
c3f2c7304dd7d70d6d418b34fe7ef09a
33.75641
120
0.719292
4.666093
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionsMetadataService.kt
2
4966
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.codeInsight.intention.impl.config import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.IntentionActionBean import com.intellij.ide.ui.TopHitCache import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.components.serviceIfCreated import com.intellij.openapi.extensions.ExtensionNotApplicableException import com.intellij.openapi.extensions.ExtensionPointListener import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.util.containers.Interner import java.util.* private typealias MetaDataKey = Pair<String, String> @Service(Service.Level.APP) internal class IntentionsMetadataService { companion object { @JvmStatic fun getInstance(): IntentionsMetadataService = service() private val interner = Interner.createWeakInterner<String>() } private fun metaDataKey(categoryNames: Array<String>, familyName: String): MetaDataKey { return Pair(categoryNames.joinToString(separator = ":"), interner.intern(familyName)) } // guarded by this private val extensionMetaMap: MutableMap<IntentionActionBean, IntentionActionMetaData> // guarded by this, used only for legacy programmatically registered intentions private val dynamicRegistrationMeta: MutableList<IntentionActionMetaData> init { dynamicRegistrationMeta = ArrayList() extensionMetaMap = LinkedHashMap(IntentionManagerImpl.EP_INTENTION_ACTIONS.point.size()) IntentionManagerImpl.EP_INTENTION_ACTIONS.forEachExtensionSafe { registerMetaDataForEp(it) } IntentionManagerImpl.EP_INTENTION_ACTIONS.addExtensionPointListener(object : ExtensionPointListener<IntentionActionBean> { override fun extensionAdded(extension: IntentionActionBean, pluginDescriptor: PluginDescriptor) { // on each plugin load/unload SearchableOptionsRegistrarImpl drops the cache, so, it will be recomputed later on demand registerMetaDataForEp(extension) serviceIfCreated<TopHitCache>()?.invalidateCachedOptions(IntentionsOptionsTopHitProvider::class.java) } override fun extensionRemoved(extension: IntentionActionBean, pluginDescriptor: PluginDescriptor) { if (extension.categories == null) { return } unregisterMetaDataForEP(extension) serviceIfCreated<TopHitCache>()?.invalidateCachedOptions(IntentionsOptionsTopHitProvider::class.java) } }, null) } private fun registerMetaDataForEp(extension: IntentionActionBean) { val categories = extension.categories ?: return val instance = IntentionActionWrapper(extension) val descriptionDirectoryName = extension.getDescriptionDirectoryName() ?: instance.descriptionDirectoryName val metadata = try { IntentionActionMetaData(instance, extension.loaderForClass, categories, descriptionDirectoryName) } catch (ignore: ExtensionNotApplicableException) { return } synchronized(this) { extensionMetaMap.put(extension, metadata) } } @Deprecated("Use intentionAction extension point instead") fun registerIntentionMetaData(intentionAction: IntentionAction, category: Array<String?>, descriptionDirectoryName: String) { val classLoader = if (intentionAction is IntentionActionWrapper) { intentionAction.implementationClassLoader } else { intentionAction.javaClass.classLoader } val metadata = IntentionActionMetaData(intentionAction, classLoader, category, descriptionDirectoryName) synchronized(this) { // not added as searchable option - this method is deprecated and intentionAction extension point must be used instead dynamicRegistrationMeta.add(metadata) } } @Synchronized fun getMetaData(): List<IntentionActionMetaData> { if (dynamicRegistrationMeta.isEmpty()) return java.util.List.copyOf(extensionMetaMap.values) return java.util.List.copyOf(extensionMetaMap.values + dynamicRegistrationMeta) } fun getUniqueMetadata(): List<IntentionActionMetaData> { val allIntentions = getMetaData() val unique = LinkedHashMap<MetaDataKey, IntentionActionMetaData>(allIntentions.size) for (metadata in allIntentions) { val key = try { metaDataKey(metadata.myCategory, metadata.family) } catch (ignore: ExtensionNotApplicableException) { continue } unique[key] = metadata } return unique.values.toList() } @Synchronized fun unregisterMetaData(intentionAction: IntentionAction) { dynamicRegistrationMeta.removeIf { meta -> meta.action === intentionAction } } @Synchronized private fun unregisterMetaDataForEP(extension: IntentionActionBean) { extensionMetaMap.remove(extension) } }
apache-2.0
20b7728d027d69c560110b949f3e03f0
39.056452
127
0.76178
5.156802
false
false
false
false
GunoH/intellij-community
python/src/com/jetbrains/python/sdk/flavors/WinAppxTools.kt
9
5768
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.sdk.flavors import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.SystemInfo import com.sun.jna.platform.win32.Kernel32 import com.sun.jna.platform.win32.Kernel32.* import com.sun.jna.platform.win32.Ntifs import com.sun.jna.platform.win32.WinioctlUtil import com.sun.jna.ptr.IntByReference import java.io.File import java.io.FilenameFilter import java.nio.ByteBuffer /** * AppX packages installed to AppX volume (see ``Get-AppxDefaultVolume``, ``Get-AppxPackage``). * They can't be executed nor read. * * At the same time, **reparse point** is created somewhere in `%LOCALAPPDATA%`. * This point has tag ``IO_REPARSE_TAG_APPEXECLINK`` and it also added to `PATH` * * Their attributes are also inaccessible. [File#exists] returns false. * But when executed, they are processed by NTFS filter and redirected to their real location in AppX volume. * * There may be ``python.exe`` there, but it may point to Windows Store (so it can be installed when accessed) or to the real python. * There is no Java API to see reparse point destination, so we use JNA. * This tool returns AppX name (either ``PythonSoftwareFoundation...`` or ``DesktopAppInstaller..``). * We use it to check if ``python.exe`` is real python or WindowsStore mock. */ /** * When product of AppX reparse point contains this word, that means it is a link to the store */ private const val storeMarker = "DesktopAppInstaller" /** * Files in [userAppxFolder] that matches [filePattern] and contains [expectedProduct]] in their product name. * For example: ``PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0``. * There may be several files linked to this product, we need only first. * And for 3.7 there could be ``PythonSoftwareFoundation.Python.3.7_(SOME_OTHER_UID)``. */ fun getAppxFiles(expectedProduct: String, filePattern: Regex): Collection<File> = userAppxFolder?.listFiles(FilenameFilter { _, name -> filePattern.matches(name) }) ?.sortedBy { it.nameWithoutExtension } ?.mapNotNull { file -> file.appxProduct?.let { product -> Pair(product, file) } } ?.toMap() ?.filterKeys { expectedProduct in it } ?.values ?: emptyList() /** * If file is AppX reparse point link -- return its product name */ val File.appxProduct: String? get() { if (parentFile?.equals(userAppxFolder) != true) return null return getAppxTag(absolutePath)?.let { if (storeMarker !in it) it else null } } /** * Path to ``%LOCALAPPDATA%\Microsoft\WindowsApps`` */ private val userAppxFolder = if (!SystemInfo.isWin10OrNewer) { null } else { System.getenv("LOCALAPPDATA")?.let { localappdata -> val appsPath = File(localappdata, "Microsoft//WindowsApps") if (appsPath.exists()) appsPath else null } } // https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-fscc/c8e77b37-3909-4fe6-a4ea-2b9d423b1ee4 private const val IO_REPARSE_TAG_APPEXECLINK = 0x8000001B /** * AppX apps are installed in "C:\Program Files\WindowsApps\". You can't run them directly. Instead, you must use reparse point from "%LOCALAPPDATA%\Microsoft\WindowsApps" (this folder is under the %PATH%) Reparse point is the special structure on NTFS level that stores "reparse tag" (type) and some type-specific data. When a user accesses such files, Windows redirects the request to the appropriate target. So, files in "%LOCALAPPDATA%\Microsoft\WindowsApps" are reparse points to AppX apps, and AppX can only be launched via them. But for Python, there can be a reparse point that points to Windows store, so Store is opened when Python is not installed. There is no official way to tell if "python.exe" points to AppX python or AppX "Windows Store". MS provides API (via DeviceIOControl) to read reparse point structure. There is also a reparse point tag for "AppX link" in SDK. Reparse data is undocumented, but it is just an array of wide chars with some unprintable chars at the beginning. This tool reads reparse point info and tries to fetch AppX name, so we can see if it points to Store or not. See https://youtrack.jetbrains.com/issue/PY-43082 Output is unicode 16-LE */ private fun getAppxTag(path: String): String? { if (!SystemInfo.isWin10OrNewer) return null val kernel = INSTANCE val logger = Logger.getInstance(Kernel32::class.java) val file = kernel.CreateFile(path, GENERIC_READ, FILE_SHARE_READ, null, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, null) if (file == INVALID_HANDLE_VALUE) { logger.warn("Invalid handle for $path") return null } val buffer = Ntifs.REPARSE_DATA_BUFFER() val bytesRead = IntByReference() if (!kernel.DeviceIoControl(file, WinioctlUtil.FSCTL_GET_REPARSE_POINT, null, 0, buffer.pointer, buffer.size(), bytesRead, null)) { logger.warn("DeviceIoControl error ${kernel.GetLastError()}") return null } if (bytesRead.value < 1) { logger.warn("0 bytes read") return null } buffer.read() if (buffer.ReparseTag != IO_REPARSE_TAG_APPEXECLINK.toInt()) { logger.warn("Wrong tag ${buffer.ReparseTag}") return null } // output is array of LE 2 bytes chars: \0\0\0[text]\0[junk] val charBuffer = Charsets.UTF_16LE.decode(ByteBuffer.wrap(buffer.u.genericReparseBuffer.DataBuffer)) var from = 0 var to = 0 var startFound = false for ((i, char) in charBuffer.withIndex()) { val validChar = Character.getType(char) != Character.CONTROL.toInt() if (validChar && !startFound) { from = i startFound = true } if (!validChar && startFound) { to = i break } } return charBuffer.substring(from, to) }
apache-2.0
42d22a766001af7d35555d42b5d47244
39.342657
140
0.725902
3.578164
false
false
false
false
GunoH/intellij-community
plugins/toml/core/src/main/kotlin/org/toml/lang/lexer/TomlEscapeLexer.kt
9
3859
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.toml.lang.lexer import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.StringEscapesTokenTypes import com.intellij.psi.tree.IElementType import com.intellij.util.text.CharArrayUtil import org.toml.lang.psi.TOML_BASIC_STRINGS import org.toml.lang.psi.TomlElementTypes.BASIC_STRING import org.toml.lang.psi.TomlElementTypes.MULTILINE_BASIC_STRING class TomlEscapeLexer private constructor( private val defaultToken: IElementType, private val eol: Boolean ) : LexerBaseEx() { override fun determineTokenType(): IElementType? { // We're at the end of the string token => finish lexing if (tokenStart >= tokenEnd) { return null } // We're not inside escape sequence if (bufferSequence[tokenStart] != '\\') { return defaultToken } // \ is at the end of the string token if (tokenStart + 1 >= tokenEnd) { return StringEscapesTokenTypes.INVALID_CHARACTER_ESCAPE_TOKEN } return when (bufferSequence[tokenStart + 1]) { 'u', 'U' -> when { isValidUnicodeEscape(tokenStart, tokenEnd) -> StringEscapesTokenTypes.VALID_STRING_ESCAPE_TOKEN else -> StringEscapesTokenTypes.INVALID_UNICODE_ESCAPE_TOKEN } '\r', '\n' -> esc(eol) 'b', 't', 'n', 'f', 'r', '"', '\\' -> StringEscapesTokenTypes.VALID_STRING_ESCAPE_TOKEN else -> StringEscapesTokenTypes.INVALID_CHARACTER_ESCAPE_TOKEN } } private fun isValidUnicodeEscape(start: Int, end: Int): Boolean { return try { val value = bufferSequence.substring(start + 2, end).toInt(16) // https://github.com/toml-lang/toml/blame/92a0a60bf37093fe0a888e5c98445e707ac9375b/README.md#L296-L297 // https://unicode.org/glossary/#unicode_scalar_value value in 0..0xD7FF || value in 0xE000..0x10FFFF } catch (e: NumberFormatException) { false } } override fun locateToken(start: Int): Int { if (start >= bufferEnd) { return start } if (bufferSequence[start] == '\\') { val i = start + 1 if (i >= bufferEnd) { return bufferEnd } return when (bufferSequence[i]) { 'u' -> unicodeTokenEnd(i + 1, 4) 'U' -> unicodeTokenEnd(i + 1, 8) '\r', '\n' -> { var j = i while (j < bufferEnd && bufferSequence[j].isWhitespaceChar()) { j++ } j } else -> i + 1 } } else { val idx = CharArrayUtil.indexOf(bufferSequence, "\\", start + 1, bufferEnd) return if (idx != -1) idx else bufferEnd } } private fun unicodeTokenEnd(start: Int, expectedLength: Int): Int { for (i in start until start + expectedLength) { if (i >= bufferEnd || !StringUtil.isHexDigit(bufferSequence[i])) { return start } } return start + expectedLength } companion object { fun of(tokenType: IElementType): TomlEscapeLexer { return when (tokenType) { BASIC_STRING -> TomlEscapeLexer(BASIC_STRING, eol = false) MULTILINE_BASIC_STRING -> TomlEscapeLexer(MULTILINE_BASIC_STRING, eol = true) else -> throw IllegalArgumentException("Unsupported literal type: $tokenType") } } /** * Set of possible arguments for [of] */ val ESCAPABLE_LITERALS_TOKEN_SET = TOML_BASIC_STRINGS } }
apache-2.0
f5fff054349a62d0efce46387c346094
33.455357
115
0.567505
4.302118
false
false
false
false
GunoH/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/editor/lists/MarkdownListItemUnindentHandler.kt
9
2849
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.editor.lists import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.actionSystem.EditorActionHandler import com.intellij.psi.PsiDocumentManager import com.intellij.psi.util.parentOfType import org.intellij.plugins.markdown.editor.lists.ListRenumberUtils.renumberInBulk import org.intellij.plugins.markdown.editor.lists.ListUtils.getLineIndentRange import org.intellij.plugins.markdown.editor.lists.ListUtils.list import org.intellij.plugins.markdown.editor.lists.ListUtils.sublists import org.intellij.plugins.markdown.editor.lists.Replacement.Companion.replaceSafelyIn import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile import org.intellij.plugins.markdown.lang.psi.impl.MarkdownListItem /** * This handler decreases nesting of the current/selected list item(s), if it is nested at all. * The children (paragraphs and lists) are unindented as well. */ internal class MarkdownListItemUnindentHandler(baseHandler: EditorActionHandler?) : ListItemIndentUnindentHandlerBase(baseHandler) { override fun doIndentUnindent(item: MarkdownListItem, file: MarkdownFile, document: Document): Boolean { val outerItem = item.parentOfType<MarkdownListItem>() if (outerItem == null) { return removeLeadingSpaces(item, document) } decreaseNestingLevel(item, outerItem, file, document) return true } private fun removeLeadingSpaces(item: MarkdownListItem, document: Document): Boolean { val itemInfo = ListItemInfo(item, document) val indentRange = document.getLineIndentRange(itemInfo.lines.first) if (!indentRange.isEmpty) { itemInfo.changeIndent(0).replaceSafelyIn(document) } return !indentRange.isEmpty } private fun decreaseNestingLevel(item: MarkdownListItem, outerItem: MarkdownListItem, file: MarkdownFile, document: Document) { val itemInfo = ListItemInfo(item, document) val outerInfo = ListItemInfo(outerItem, document) val newSiblingsIndent = itemInfo.indentInfo.with(indent = outerInfo.indentInfo.indent).subItemIndent() for (siblingLine in outerInfo.lines.last downTo (itemInfo.lines.last + 1)) { itemInfo.indentInfo.changeLineIndent(siblingLine, newSiblingsIndent, document, file)?.apply(document) } itemInfo.changeIndent(outerInfo.indentInfo.indent).replaceSafelyIn(document) } override fun updateNumbering(item: MarkdownListItem, file: MarkdownFile, document: Document) { item.list.renumberInBulk(document, recursive = false, restart = false) PsiDocumentManager.getInstance(file.project).commitDocument(document) item.sublists.firstOrNull()?.renumberInBulk(document, recursive = false, restart = true) } }
apache-2.0
2f2f6bf41a2e3d345bb07225026e95dc
44.951613
140
0.791155
4.303625
false
false
false
false
carrotengineer/Warren
src/main/kotlin/engineer/carrot/warren/warren/handler/rpl/Rpl471Handler.kt
2
1204
package engineer.carrot.warren.warren.handler.rpl import engineer.carrot.warren.kale.IKaleHandler import engineer.carrot.warren.kale.irc.message.rfc1459.rpl.Rpl471Message import engineer.carrot.warren.warren.loggerFor import engineer.carrot.warren.warren.state.CaseMappingState import engineer.carrot.warren.warren.state.JoiningChannelLifecycle import engineer.carrot.warren.warren.state.JoiningChannelsState class Rpl471Handler(val channelsState: JoiningChannelsState, val caseMappingState: CaseMappingState) : IKaleHandler<Rpl471Message> { private val LOGGER = loggerFor<Rpl471Handler>() override val messageType = Rpl471Message::class.java override fun handle(message: Rpl471Message, tags: Map<String, String?>) { val channel = channelsState[message.channel] if (channel == null) { LOGGER.warn("got a full channel reply for a channel we don't think we're joining: $message") LOGGER.trace("channels state: $channelsState") return } LOGGER.warn("channel is full, failed to join: $channel") channel.status = JoiningChannelLifecycle.FAILED LOGGER.trace("new channels state: $channelsState") } }
isc
17cb1165ec7f4bee534aeb848307eb89
36.625
132
0.745847
4.426471
false
false
false
false
airbnb/lottie-android
sample/src/main/kotlin/com/airbnb/lottie/samples/views/AnimationItemView.kt
1
1518
package com.airbnb.lottie.samples.views import android.content.Context import android.util.AttributeSet import android.widget.FrameLayout import androidx.annotation.ColorInt import com.airbnb.epoxy.ModelProp import com.airbnb.epoxy.ModelView import com.airbnb.epoxy.TextProp import com.airbnb.lottie.samples.R import com.airbnb.lottie.samples.databinding.ItemViewShowcaseAnimationBinding import com.airbnb.lottie.samples.utils.setImageUrl import com.airbnb.lottie.samples.utils.viewBinding @ModelView(autoLayout = ModelView.Size.MATCH_WIDTH_WRAP_HEIGHT) class AnimationItemView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : FrameLayout(context, attrs, defStyleAttr) { private val binding: ItemViewShowcaseAnimationBinding by viewBinding() @ModelProp fun setPreviewUrl(url: String?) { binding.imageView.setImageUrl(url) } @TextProp fun setTitle(title: CharSequence?) { binding.titleView.text = title } @ModelProp fun setPreviewBackgroundColor(@ColorInt bgColor: Int?) { if (bgColor == null) { binding.imageView.setBackgroundResource(R.color.loading_placeholder) binding.imageView.setImageDrawable(null) } else { binding.imageView.setBackgroundColor(bgColor) } } @ModelProp(options = [ModelProp.Option.DoNotHash]) override fun setOnClickListener(l: OnClickListener?) { binding.container.setOnClickListener(l) } }
apache-2.0
6a0dd2aec209a86dce71f0f540cde3e3
31.319149
80
0.741765
4.451613
false
false
false
false
sbrannen/junit-lambda
junit-jupiter-api/src/main/kotlin/org/junit/jupiter/api/Assertions.kt
3
7988
/* * Copyright 2015-2020 the original author or authors. * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v2.0 which * accompanies this distribution and is available at * * https://www.eclipse.org/legal/epl-v20.html */ @file:API(status = EXPERIMENTAL, since = "5.1") package org.junit.jupiter.api import java.time.Duration import java.util.function.Supplier import java.util.stream.Stream import org.apiguardian.api.API import org.apiguardian.api.API.Status.EXPERIMENTAL import org.junit.jupiter.api.function.Executable import org.junit.jupiter.api.function.ThrowingSupplier /** * @see Assertions.fail */ fun fail(message: String?, throwable: Throwable? = null): Nothing = Assertions.fail<Nothing>(message, throwable) /** * @see Assertions.fail */ fun fail(message: (() -> String)?): Nothing = Assertions.fail<Nothing>(message) /** * @see Assertions.fail */ fun fail(throwable: Throwable?): Nothing = Assertions.fail<Nothing>(throwable) /** * [Stream] of functions to be executed. */ private typealias ExecutableStream = Stream<() -> Unit> private fun ExecutableStream.convert() = map { Executable(it) } /** * @see Assertions.assertAll */ fun assertAll(executables: ExecutableStream) = Assertions.assertAll(executables.convert()) /** * @see Assertions.assertAll */ fun assertAll(heading: String?, executables: ExecutableStream) = Assertions.assertAll(heading, executables.convert()) /** * [Collection] of functions to be executed. */ private typealias ExecutableCollection = Collection<() -> Unit> private fun ExecutableCollection.convert() = map { Executable(it) } /** * @see Assertions.assertAll */ fun assertAll(executables: ExecutableCollection) = Assertions.assertAll(executables.convert()) /** * @see Assertions.assertAll */ fun assertAll(heading: String?, executables: ExecutableCollection) = Assertions.assertAll(heading, executables.convert()) /** * @see Assertions.assertAll */ fun assertAll(vararg executables: () -> Unit) = assertAll(executables.toList().stream()) /** * @see Assertions.assertAll */ fun assertAll(heading: String?, vararg executables: () -> Unit) = assertAll(heading, executables.toList().stream()) /** * Example usage: * ```kotlin * val exception = assertThrows<IllegalArgumentException> { * throw IllegalArgumentException("Talk to a duck") * } * assertEquals("Talk to a duck", exception.message) * ``` * @see Assertions.assertThrows */ inline fun <reified T : Throwable> assertThrows(executable: () -> Unit): T { val throwable: Throwable? = try { executable() } catch (caught: Throwable) { caught } as? Throwable return Assertions.assertThrows(T::class.java) { if (throwable != null) { throw throwable } } } /** * Example usage: * ```kotlin * val exception = assertThrows<IllegalArgumentException>("Should throw an Exception") { * throw IllegalArgumentException("Talk to a duck") * } * assertEquals("Talk to a duck", exception.message) * ``` * @see Assertions.assertThrows */ inline fun <reified T : Throwable> assertThrows(message: String, executable: () -> Unit): T = assertThrows({ message }, executable) /** * Example usage: * ```kotlin * val exception = assertThrows<IllegalArgumentException>({ "Should throw an Exception" }) { * throw IllegalArgumentException("Talk to a duck") * } * assertEquals("Talk to a duck", exception.message) * ``` * @see Assertions.assertThrows */ inline fun <reified T : Throwable> assertThrows(noinline message: () -> String, executable: () -> Unit): T { val throwable: Throwable? = try { executable() } catch (caught: Throwable) { caught } as? Throwable return Assertions.assertThrows(T::class.java, Executable { if (throwable != null) { throw throwable } }, Supplier(message)) } /** * Example usage: * ```kotlin * val result = assertDoesNotThrow { * // Code block that is expected to not throw an exception * } * ``` * @see Assertions.assertDoesNotThrow * @param R the result type of the [executable] */ @API(status = EXPERIMENTAL, since = "5.5") fun <R> assertDoesNotThrow(executable: () -> R): R = Assertions.assertDoesNotThrow(ThrowingSupplier(executable)) /** * Example usage: * ```kotlin * val result = assertDoesNotThrow("Should not throw an exception") { * // Code block that is expected to not throw an exception * } * ``` * @see Assertions.assertDoesNotThrow * @param R the result type of the [executable] */ @API(status = EXPERIMENTAL, since = "5.5") fun <R> assertDoesNotThrow(message: String, executable: () -> R): R = assertDoesNotThrow({ message }, executable) /** * Example usage: * ```kotlin * val result = assertDoesNotThrow({ "Should not throw an exception" }) { * // Code block that is expected to not throw an exception * } * ``` * @see Assertions.assertDoesNotThrow * @param R the result type of the [executable] */ @API(status = EXPERIMENTAL, since = "5.5") fun <R> assertDoesNotThrow(message: () -> String, executable: () -> R): R = Assertions.assertDoesNotThrow(ThrowingSupplier(executable), Supplier(message)) /** * Example usage: * ```kotlin * val result = assertTimeout(Duration.seconds(1)) { * // Code block that is being timed. * } * ``` * @see Assertions.assertTimeout * @paramR the result of the [executable]. */ @API(status = EXPERIMENTAL, since = "5.5") fun <R> assertTimeout(timeout: Duration, executable: () -> R): R = Assertions.assertTimeout(timeout, executable) /** * Example usage: * ```kotlin * val result = assertTimeout(Duration.seconds(1), "Should only take one second") { * // Code block that is being timed. * } * ``` * @see Assertions.assertTimeout * @paramR the result of the [executable]. */ @API(status = EXPERIMENTAL, since = "5.5") fun <R> assertTimeout(timeout: Duration, message: String, executable: () -> R): R = Assertions.assertTimeout(timeout, executable, message) /** * Example usage: * ```kotlin * val result = assertTimeout(Duration.seconds(1), { "Should only take one second" }) { * // Code block that is being timed. * } * ``` * @see Assertions.assertTimeout * @paramR the result of the [executable]. */ @API(status = EXPERIMENTAL, since = "5.5") fun <R> assertTimeout(timeout: Duration, message: () -> String, executable: () -> R): R = Assertions.assertTimeout(timeout, executable, message) /** * Example usage: * ```kotlin * val result = assertTimeoutPreemptively(Duration.seconds(1)) { * // Code block that is being timed. * } * ``` * @see Assertions.assertTimeoutPreemptively * @paramR the result of the [executable]. */ @API(status = EXPERIMENTAL, since = "5.5") fun <R> assertTimeoutPreemptively(timeout: Duration, executable: () -> R): R = Assertions.assertTimeoutPreemptively(timeout, executable) /** * Example usage: * ```kotlin * val result = assertTimeoutPreemptively(Duration.seconds(1), "Should only take one second") { * // Code block that is being timed. * } * ``` * @see Assertions.assertTimeoutPreemptively * @paramR the result of the [executable]. */ @API(status = EXPERIMENTAL, since = "5.5") fun <R> assertTimeoutPreemptively(timeout: Duration, message: String, executable: () -> R): R = Assertions.assertTimeoutPreemptively(timeout, executable, message) /** * Example usage: * ```kotlin * val result = assertTimeoutPreemptively(Duration.seconds(1), { "Should only take one second" }) { * // Code block that is being timed. * } * ``` * @see Assertions.assertTimeoutPreemptively * @paramR the result of the [executable]. */ @API(status = EXPERIMENTAL, since = "5.5") fun <R> assertTimeoutPreemptively(timeout: Duration, message: () -> String, executable: () -> R): R = Assertions.assertTimeoutPreemptively(timeout, executable, message)
epl-1.0
0f573102b0e91420496eb088ff658313
28.260073
108
0.681272
3.792972
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/i18n/inspections/ChangeTranslationQuickFix.kt
1
2224
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.i18n.inspections import com.demonwav.mcdev.i18n.lang.gen.psi.I18nEntry import com.demonwav.mcdev.i18n.reference.I18nGotoModel import com.demonwav.mcdev.i18n.translations.identifiers.LiteralTranslationIdentifier import com.demonwav.mcdev.util.runWriteAction import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.ide.util.gotoByName.ChooseByNamePopup import com.intellij.ide.util.gotoByName.ChooseByNamePopupComponent import com.intellij.openapi.application.ModalityState import com.intellij.openapi.project.Project import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiLiteralExpression import com.intellij.util.IncorrectOperationException class ChangeTranslationQuickFix(private val name: String) : LocalQuickFix { override fun getName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { try { val literal = descriptor.psiElement as PsiLiteralExpression val translation = LiteralTranslationIdentifier().identify(literal) val popup = ChooseByNamePopup.createPopup(project, I18nGotoModel(project, translation?.regexPattern), null) popup.invoke(object : ChooseByNamePopupComponent.Callback() { override fun elementChosen(element: Any) { val selectedEntry = element as I18nEntry literal.containingFile.runWriteAction { val match = translation?.regexPattern?.matchEntire(selectedEntry.key) val insertion = if (match == null || match.groups.size <= 1) selectedEntry.key else match.groupValues[1] literal.replace(JavaPsiFacade.getInstance(project).elementFactory.createExpressionFromText("\"$insertion\"", literal.context)) } } }, ModalityState.current(), false) } catch (ignored: IncorrectOperationException) { } } override fun startInWriteAction() = false override fun getFamilyName() = name }
mit
d83367cdceb63a419bff703d572b2c38
41.769231
150
0.721223
4.877193
false
false
false
false
shaz-tech/StoreAppPuller
puller/src/main/java/com/shaz/sap/Utils.kt
1
1070
package com.shaz.sap import android.content.Context import android.net.ConnectivityManager import android.net.NetworkInfo import android.os.Build import android.os.Parcelable /** * Created by ${Shahbaz} on 04-08-2017. */ class Utils { companion object { fun isConnectedToInternet(_context: Context): Boolean { if(_context == null) return false val connectivity = _context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager connectivity.let { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val info = it.activeNetworkInfo return info?.isConnected ?: false } else { val info = it.allNetworkInfo (info != null) info.indices .filter { info[it].state == NetworkInfo.State.CONNECTED } .forEach { return true } } } return false } } }
apache-2.0
4d4363574fd4541afbdbf7aa7a843b5d
28.75
109
0.545794
5.169082
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/platform/mixin/insight/MixinImplicitUsageProvider.kt
1
1089
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.insight import com.demonwav.mcdev.platform.mixin.util.isShadow import com.intellij.codeInsight.daemon.ImplicitUsageProvider import com.intellij.psi.PsiElement import com.intellij.psi.PsiField import com.intellij.psi.PsiMethod import com.intellij.psi.PsiParameter class MixinImplicitUsageProvider : ImplicitUsageProvider { private fun isShadowField(element: PsiElement) = element is PsiField && element.isShadow private fun isParameterInShadow(element: PsiElement): Boolean { if (element !is PsiParameter) { return false } val method = element.declarationScope as? PsiMethod ?: return false return method.isShadow } override fun isImplicitUsage(element: PsiElement) = isParameterInShadow(element) override fun isImplicitRead(element: PsiElement) = isShadowField(element) override fun isImplicitWrite(element: PsiElement) = isShadowField(element) }
mit
1f0cd90dc9c607e7dd0fa7007ad71907
29.25
92
0.754821
4.338645
false
false
false
false
dhis2/dhis2-android-sdk
core/src/test/java/org/hisp/dhis/android/core/settings/internal/SettingsAppInfoManagerShould.kt
1
2911
/* * 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.settings.internal import com.google.common.truth.Truth.assertThat import com.nhaarman.mockitokotlin2.* import io.reactivex.Single import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class SettingsAppInfoManagerShould { private val settingsAppInfoCall: SettingsAppInfoCall = mock() private val settingsAppInfo = SettingsAppVersion.Valid(SettingsAppDataStoreVersion.V1_1, "unknown") private val settingAppInfoSingle: Single<SettingsAppVersion> = Single.just(settingsAppInfo) private lateinit var manager: SettingsAppInfoManager @Before fun setUp() { whenever(settingsAppInfoCall.fetch(any())) doReturn settingAppInfoSingle manager = SettingsAppInfoManagerImpl(settingsAppInfoCall) } @Test fun call_setting_info_only_if_version_is_null() { val version = manager.getDataStoreVersion().blockingGet()!! verify(settingsAppInfoCall).fetch(any()) assertThat(version).isEquivalentAccordingToCompareTo(settingsAppInfo.dataStore) val cached = manager.getDataStoreVersion().blockingGet() verifyNoMoreInteractions(settingsAppInfoCall) assertThat(cached).isEquivalentAccordingToCompareTo(settingsAppInfo.dataStore) } }
bsd-3-clause
7400993d3da8966b15ded8e03a781a0d
45.206349
103
0.770526
4.584252
false
false
false
false
McMoonLakeDev/MoonLake
API/src/main/kotlin/com/mcmoonlake/api/dsl/DSLPacketListener.kt
1
4121
/* * Copyright (C) 2016-Present The MoonLake ([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/>. */ @file:JvmName("DSLPacketListener") package com.mcmoonlake.api.dsl import com.mcmoonlake.api.packet.* import org.bukkit.plugin.Plugin open class DSLPacketScope(val plugin: Plugin) { var priority: PacketListenerPriority = PacketListenerPriority.NORMAL protected var sending: (PacketEvent) -> Unit = {} fun onSending(block: PacketEvent.() -> Unit) { sending = block } protected var receiving: (PacketEvent) -> Unit = {} fun onReceiving(block: PacketEvent.() -> Unit) { receiving = block } protected var exception: (Exception) -> Unit = {} fun onException(block: Exception.() -> Unit) { exception = block } /** * * Not recommended for external calls. * * @see [buildPacketListener] * @see [buildPacketListenerSpecified] * @see [buildPacketListenerLegacy] */ open fun get(): PacketListener = object: PacketListenerAnyAdapter(plugin, priority) { override fun onSending(event: PacketEvent) = sending(event) override fun onReceiving(event: PacketEvent) = receiving(event) override fun handlerException(ex: Exception) = exception(ex) } } class DSLPacketSpecifiedScope(plugin: Plugin) : DSLPacketScope(plugin) { var types: Array<Class<out Packet>> = emptyArray() override fun get(): PacketListener = object: PacketListenerAdapter(plugin, priority, *types) { override fun onSending(event: PacketEvent) = sending(event) override fun onReceiving(event: PacketEvent) = receiving(event) override fun handlerException(ex: Exception) = exception(ex) } } class DSLPacketLegacyScope<P: PacketBukkitLegacy, T>( plugin: Plugin ) : DSLPacketScope(plugin) where T: PacketBukkitLegacy, T: PacketLegacy { var adapter: PacketLegacyAdapter<P, T> = object: PacketLegacyAdapter<P, T>() { override val packet: Class<P> get() = throw INVALID_ADAPTER override val packetLegacy: Class<T> get() = throw INVALID_ADAPTER override val isLegacy: Boolean get() = throw INVALID_ADAPTER } companion object { private val INVALID_ADAPTER = IllegalStateException("Invalid adapter, not yet initialized.") } /** * * If the event's packet is legacy. */ val PacketEvent.isLegacy: Boolean get() = adapter.isLegacy override fun get(): PacketListener = object: PacketListenerLegacyAdapter<P, T>(plugin, priority, adapter) { override fun onSending(event: PacketEvent) = sending(event) override fun onReceiving(event: PacketEvent) = receiving(event) override fun handlerException(ex: Exception) = exception(ex) } } inline fun Plugin.buildPacketListener(block: DSLPacketScope.() -> Unit): PacketListener = DSLPacketScope(this).also(block).get() inline fun Plugin.buildPacketListenerSpecified(block: DSLPacketSpecifiedScope.() -> Unit): PacketListener = DSLPacketSpecifiedScope(this).also(block).get() inline fun <P: PacketBukkitLegacy, T> Plugin.buildPacketListenerLegacy(block: DSLPacketLegacyScope<P, T>.() -> Unit): PacketListener where T : PacketBukkitLegacy, T: PacketLegacy = DSLPacketLegacyScope<P, T>(this).also(block).get()
gpl-3.0
3d790411fa61fa3a5db3e611cfaa744d
35.794643
178
0.669012
4.351637
false
false
false
false
Talentica/AndroidWithKotlin
sensors/src/main/java/com/talentica/androidkotlin/sensors/Compass.kt
1
4142
package com.talentica.androidkotlin.sensors import android.content.Context import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import android.util.Log import android.view.animation.Animation import android.view.animation.RotateAnimation import android.widget.ImageView class Compass(context: Context) : SensorEventListener { private val sensorManager: SensorManager private val gsensor: Sensor private val msensor: Sensor private val mGravity = FloatArray(3) private val mGeomagnetic = FloatArray(3) private var azimuth = 0f private var currectAzimuth = 0f // compass arrow to rotate var arrowView: ImageView? = null init { sensorManager = context .getSystemService(Context.SENSOR_SERVICE) as SensorManager gsensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) msensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) } fun start() { sensorManager.registerListener(this, gsensor, SensorManager.SENSOR_DELAY_GAME) sensorManager.registerListener(this, msensor, SensorManager.SENSOR_DELAY_GAME) } fun stop() { sensorManager.unregisterListener(this) } override fun onSensorChanged(event: SensorEvent) { val alpha = 0.97f synchronized(this) { if (event.sensor.type == Sensor.TYPE_ACCELEROMETER) { mGravity[0] = alpha * mGravity[0] + (1 - alpha) * event.values[0] mGravity[1] = alpha * mGravity[1] + (1 - alpha) * event.values[1] mGravity[2] = alpha * mGravity[2] + (1 - alpha) * event.values[2] // mGravity = event.values; // Log.d(TAG, "GravityRaw: "+event.values.contentToString()+ " filtered: "+mGravity.contentToString()); } if (event.sensor.type == Sensor.TYPE_MAGNETIC_FIELD) { // mGeomagnetic = event.values; mGeomagnetic[0] = alpha * mGeomagnetic[0] + (1 - alpha) * event.values[0] mGeomagnetic[1] = alpha * mGeomagnetic[1] + (1 - alpha) * event.values[1] mGeomagnetic[2] = alpha * mGeomagnetic[2] + (1 - alpha) * event.values[2] // Log.d(TAG,"MagneticRaw: "+event.values.contentToString()+ " Filtered: "+mGeomagnetic.contentToString()); } val R = FloatArray(9) val I = FloatArray(9) val success = SensorManager.getRotationMatrix(R, I, mGravity, mGeomagnetic) // Log.d(TAG,"Gravity: "+mGravity.contentToString()+ " Magnetic: "+mGeomagnetic.contentToString() // + " R: "+ R.contentToString() +" I: "+ I.contentToString()); if (success) { // Log.d(TAG,"Gravity: "+mGravity.contentToString()+ " Magnetic: "+mGeomagnetic.contentToString()) Log.d(TAG," R: "+ R.contentToString() +" I: "+ I.contentToString()); val orientation = FloatArray(3) SensorManager.getOrientation(R, orientation) // Log.d(TAG, "azimuth (rad): " + azimuth); azimuth = Math.toDegrees(orientation[0].toDouble()).toFloat() // orientation azimuth = (azimuth + 360) % 360 // Log.d(TAG, "azimuth (deg): " + azimuth); adjustArrow() } } } private fun adjustArrow() { if (arrowView == null) { Log.i(TAG, "arrow view is not set") return } // Log.i(TAG, "will set rotation from " + currectAzimuth + " to " + azimuth) val an = RotateAnimation(-currectAzimuth, -azimuth, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f) currectAzimuth = azimuth an.duration = 500 an.repeatCount = 0 an.fillAfter = true arrowView!!.startAnimation(an) } override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {} companion object { private val TAG = "Compass" } }
apache-2.0
b14e717147e412ca23efc14759d55f42
37.71028
122
0.603332
4.109127
false
false
false
false
JonathanxD/CodeAPI
src/main/kotlin/com/github/jonathanxd/kores/inspect/InstructionsInspect.kt
1
4992
/* * Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores> * * The MIT License (MIT) * * Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]> * Copyright (c) contributors * * * 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.jonathanxd.kores.inspect import com.github.jonathanxd.kores.KoresPart import com.github.jonathanxd.kores.Instructions import com.github.jonathanxd.kores.base.BodyHolder import java.util.* /** * Utility to inspect [Instructions]. * * @param R Mapper type. * @property predicate Predicate check if elements match requirements. * @property inspectRootInstructions True to inspect [Instructions] and not only sub elements. * @property subPredicate Predicate to check whether a [BodyHolder] should be inspected. * @property stopPredicate Predicate to determine when the inspection should stop (`true` to stop, `false` to continue). * @property mapper Function to map processed values to another type. */ class InstructionsInspect<out R> internal constructor( val predicate: (KoresPart) -> Boolean, val inspectRootInstructions: Boolean, val subPredicate: ((BodyHolder) -> Boolean)?, val stopPredicate: (KoresPart) -> Boolean, val mapper: (KoresPart) -> R ) { /** * Inspect the [source] and return the list of elements where matches [predicate] (mapped with [mapper]). */ fun inspect(source: Instructions): List<R> { val list = ArrayList<R>() this.inspect(source, this.inspectRootInstructions, { list.add(it) }, 0) return list } /** * Inspect the [source] starting at index [start] and return the list of elements where matches [predicate] (mapped with [mapper]).. * * @throws IndexOutOfBoundsException If [start] index exceeds the [source] size. */ fun inspect(source: Instructions, start: Int): List<R> { val list = mutableListOf<R>() this.inspect(source, this.inspectRootInstructions, { list.add(it) }, start) return list } /** * Inspect [source] starting at index [start] and call [consumer] function with each * element (mapped with [mapper]) where matches [predicate]. * * @return False if inspection stopped before ending as result of [stopPredicate] returning true for an element. */ fun inspect(source: Instructions, inspect: Boolean, consumer: (R) -> Unit, start: Int): Boolean { if (start == 0 && source.size == 0) return true if (start >= source.size) throw IndexOutOfBoundsException("Start index '" + start + "' is out of bounds. Size: " + source.size + ".") for (i in start..source.size - 1) { val codePart = source[i] // Deep inspection if (codePart is BodyHolder) { if (this.subPredicate != null && this.subPredicate.invoke(codePart)) { val body = codePart.body if (!this.inspect(body, true, consumer, 0)) { return false } } } if (inspect) { if (this.predicate(codePart)) { consumer(this.mapper(codePart)) } else if (this.stopPredicate(codePart)) { return false } } } return true } companion object { /** * Creates a [InstructionsInspectBuilder] with [codePartPredicate] as matcher of elements * to collect. */ @JvmStatic fun builder(codePartPredicate: (KoresPart) -> Boolean): InstructionsInspectBuilder<KoresPart> { return InstructionsInspectBuilder.builder<KoresPart>().find(codePartPredicate) } } }
mit
6687e6d1b54ae96481c696d9aa59f656
37.10687
136
0.644231
4.567246
false
false
false
false
dkandalov/katas
kotlin/src/katas/kotlin/hamming/HammingDistance.kt
1
1953
package katas.kotlin.hamming import org.hamcrest.CoreMatchers.equalTo import org.junit.Assert.assertThat import org.junit.Test class HammingDistance { @Test fun findLongestSetOfWordsWithHammingDistanceAboveTwo() { fun distance(a: Int, b: Int): Int { var result = 0 var c = a.xor(b) while (c != 0) { if (c.and(1) == 1) { result += 1 } c = c.shr(1) } return result } assertThat(distance(0, 0), equalTo(0)) assertThat(distance(1, 1), equalTo(0)) assertThat(distance(1, 0), equalTo(1)) assertThat(distance(2, 0), equalTo(1)) assertThat(distance(3, 1), equalTo(1)) assertThat(distance(3, 0), equalTo(2)) assertThat(distance(7, 0), equalTo(3)) fun intToBinaryString(n: Int, width: Int): String { var s = "" var i = n 0.until(width).forEach { s = if (i.and(1) == 1) "1$s" else "0$s" i = i.shr(1) } return s } assertThat(intToBinaryString(0, 6), equalTo("000000")) assertThat(intToBinaryString(1, 6), equalTo("000001")) assertThat(intToBinaryString(2, 6), equalTo("000010")) assertThat(intToBinaryString(3, 6), equalTo("000011")) assertThat(intToBinaryString(1, 6), equalTo("000001")) fun search(options: List<Int>, solution: List<Int>): List<List<Int>> { val newOptions = options.filter { option -> solution.all { distance(it, option) > 2 } } if (newOptions.isEmpty()) return listOf(solution) return newOptions.flatMap { option -> search(newOptions.minus(option), solution.plus(option)) } } val solutions = search(0.until(64).toList(), listOf(0)) println(solutions.size) } }
unlicense
80d39daeeb87e168f245c4eeb63841ff
33.875
78
0.536098
4.010267
false
false
false
false
eidolon/eidolon-components
eidolon-config/src/main/kotlin/space/eidolon/component/config/parsing/Tokens.kt
2
1346
/** * This file is part of the "eidolon-components" project. * * 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. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ package space.eidolon.component.config.parsing /** * Token * * Base class for all other tokens. * * @property lexeme The value associated with the token. * @constructor Creates a token with the given lexeme. */ interface Token { val lexeme: String } data class PropertyToken(override val lexeme: String) : Token data class ArrayStartToken(override val lexeme: String = "[") : Token data class ArrayEndToken(override val lexeme: String = "]") : Token data class ObjectStartToken(override val lexeme: String = "{") : Token data class ObjectEndToken(override val lexeme: String = "}") : Token data class NullToken(override val lexeme: String = "null") : Token data class FalseToken(override val lexeme: String = "false") : Token data class TrueToken(override val lexeme: String = "true") : Token data class NumberToken(override val lexeme: String) : Token data class StringToken(override val lexeme: String) : Token
mit
99563fd3b369ce8e55952fcbf5eb1697
33.512821
75
0.744428
3.834758
false
false
false
false
securityfirst/Umbrella_android
app/src/test/java/org/secfirst/umbrella/storage/FakeTentRepository.kt
1
2603
package org.secfirst.umbrella.storage import java.io.File abstract class FakeTentRepository { companion object { fun `list of valid and invalid files`(): List<File> { val file1 = File("/travel/kidnapping/beginner/close.png") val file2 = File("/travel/.foreingkey.yml") val file3 = File("/travel/kidnapping/beginner/.foreingkey.yml") val file4 = File("/travel/kidnapping/beginner/c_checklist.yml") val file5 = File("/travel/kidnapping/.foreingkey.yml") val file6 = File("/travel/kidnapping/intermediate/.foreingkey.yml") val file7 = File("/travel/kidnapping/intermediate/s_segments.yml") val file8 = File("/travel/kidnapping/advanced/.foreingkey.yml") val file9 = File("/email/how_to_learn.md") val file10 = File("/about/.foreingkey.yml") val file11 = File("/something/hello_wrong_file.xml") val file12 = File("/form_view/f_first_form_wrong_file.yml") val files = arrayListOf<File>() files.add(file1) files.add(file2) files.add(file3) files.add(file4) files.add(file5) files.add(file6) files.add(file7) files.add(file8) files.add(file9) files.add(file10) files.add(file11) files.add(file12) return files } fun `list of valid files`(): List<File> { val file1 = File("/travel/kidnapping/intermediate/s_segments.yml") val file2 = File("/travel/kidnapping/beginner/c_checklist.yml") val file3 = File("/form_view/f_first_form.yml") val files = arrayListOf<File>() files.add(file1) files.add(file2) files.add(file3) return files } fun `valid list of element`(): List<File> { val files = arrayListOf<File>() val file1 = File("/about/.foreingkey.yml") val file2 = File("/travel/.foreingkey.yml") val file3 = File("/travel/kidnapping/.foreingkey.yml") val file4 = File("/travel/kidnapping/beginner/.foreingkey.yml") val file5 = File("/travel/kidnapping/intermediate/.foreingkey.yml") val file6 = File("/travel/kidnapping/advanced/.foreingkey.yml") files.add(file1) files.add(file2) files.add(file3) files.add(file4) files.add(file5) files.add(file6) return files } } }
gpl-3.0
f7815cd13e586cf18e72213cff463a31
35.152778
79
0.562044
3.777939
false
false
false
false
android/privacy-codelab
PhotoLog_End/src/main/java/com/example/photolog_end/PhotoGrid.kt
1
2663
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.photolog_end import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Close import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FilledTonalIconButton import androidx.compose.material3.Icon import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import java.io.File @OptIn(ExperimentalMaterial3Api::class) @Composable fun PhotoGrid( modifier: Modifier, photos: List<File>, onRemove: ((photo: File) -> Unit)? = null ) { Row(modifier) { repeat(MAX_LOG_PHOTOS_LIMIT) { index -> val file = photos.getOrNull(index) if (file == null) { Box(Modifier.weight(1f)) } else { Box( contentAlignment = Alignment.TopEnd, modifier = Modifier .weight(1f) .clip(RoundedCornerShape(10.dp)) .aspectRatio(1f) ) { AsyncImage( model = file, contentDescription = null, contentScale = ContentScale.Crop ) if (onRemove != null) { FilledTonalIconButton(onClick = { onRemove(file) }) { Icon(Icons.Filled.Close, null) } } } } Spacer(Modifier.width(8.dp)) } } }
apache-2.0
bb7fdcf4e1cab8960701c3ed6f50ef48
34.052632
77
0.637251
4.607266
false
false
false
false
sachil/Essence
app/src/main/java/xyz/sachil/essence/vm/DataViewModel.kt
1
1570
package xyz.sachil.essence.vm import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import androidx.lifecycle.viewModelScope import androidx.paging.PagedList import kotlinx.coroutines.Dispatchers import org.koin.core.component.KoinApiExtension import org.koin.core.component.inject import xyz.sachil.essence.model.net.bean.TypeData import xyz.sachil.essence.util.LoadState import xyz.sachil.essence.repository.DataRepository import xyz.sachil.essence.repository.wrap.DataRequest import xyz.sachil.essence.repository.wrap.DataResponse @KoinApiExtension open class DataViewModel : BaseViewModel(){ companion object { private const val TAG = "DataViewModel" } private val dataRepository: DataRepository by inject() private val dataRequest = MutableLiveData<DataRequest>() private val dataResponse: LiveData<DataResponse> = Transformations.map(dataRequest) { dataRepository.getTypeData(it) } val typeData: LiveData<PagedList<TypeData>> = Transformations.switchMap(dataResponse) { it.data } val state: LiveData<LoadState> = Transformations.switchMap(dataResponse) { it.loadState } fun getTypeData(category: String, type: String) { val coroutineContext = Dispatchers.IO + exceptionHandler.getHandler() dataRequest.value = DataRequest(viewModelScope, coroutineContext, category, type) } fun refresh() { dataResponse.value?.refresh?.invoke() } override fun onExceptionHandled() { } }
apache-2.0
bccd1361d31aeaded3a361fa06e84111
30.42
91
0.761783
4.714715
false
false
false
false
flesire/ontrack
ontrack-git/src/test/kotlin/net/nemerosa/ontrack/git/GitRepositoryClientImplTest.kt
1
13912
package net.nemerosa.ontrack.git import net.nemerosa.ontrack.common.Time import net.nemerosa.ontrack.git.support.GitRepo import org.junit.Test import java.util.function.Consumer import java.util.stream.Collectors import kotlin.test.assertEquals import kotlin.test.assertNotNull class GitRepositoryClientImplTest { /** * ``` * * C5 (master) * | * C4 (2.1) * |/ * * C3 * * C2 * * C1 * ``` */ @Test fun `Iterating over commits on a branch`() { GitRepo.prepare { gitInit() commit(1) commit(2) commit(3) git("checkout", "-b", "2.1") commit(4) git("checkout", "master") commit(5) log() } and { client, repo -> val c1 = repo.commitLookup("Commit 1") val messages = mutableListOf<String>() client.forEachCommitFrom("master", c1) { r -> messages.add(r.fullMessage.trim()) // Going on null } assertEquals( listOf( "Commit 1", "Commit 2", "Commit 3", "Commit 5" ), messages ) } } /** * ``` * * C5 (master) * | * C4 (2.1) * |/ * * C3 * * C2 * * C1 * ``` */ @Test fun `Iterating over commits on a branch not including the start`() { GitRepo.prepare { gitInit() commit(1) commit(2) commit(3) git("checkout", "-b", "2.1") commit(4) git("checkout", "master") commit(5) log() } and { client, repo -> val c1 = repo.commitLookup("Commit 1") val messages = mutableListOf<String>() client.forEachCommitFrom("master", c1, include = false) { r -> messages.add(r.fullMessage.trim()) // Going on null } assertEquals( listOf( "Commit 2", "Commit 3", "Commit 5" ), messages ) } } /** * ``` * * C4 (master) * | * C3 (2.1) * |/ * * C2 (2.0) * * C1 * ``` */ @Test fun `List of branches for a commit`() { GitRepo.prepare { gitInit() commit(1) git("checkout", "-b", "2.0") commit(2) git("checkout", "-b", "2.1") commit(3) git("checkout", "master") commit(4) log() } and { _, repo -> GitRepo.prepare { git("clone", repo.dir.absolutePath, ".") } and { cloneClient, cloneRepo -> cloneClient.getBranchesForCommit(cloneRepo.commitLookup("Commit 3")).apply { assertEquals(listOf("2.1"), this) } cloneClient.getBranchesForCommit(cloneRepo.commitLookup("Commit 4")).apply { assertEquals(listOf("master"), this) } cloneClient.getBranchesForCommit(cloneRepo.commitLookup("Commit 2")).apply { assertEquals(listOf("2.0", "2.1"), this) } cloneClient.getBranchesForCommit(cloneRepo.commitLookup("Commit 1")).apply { assertEquals(listOf("2.0", "2.1", "master"), this) } } } } /** * <pre> * * C4 (master) * | * C3 (2.1) * |/ * * C2 * * C1 * </pre> */ @Test fun `List of local branches with their commits`() { GitRepo.prepare { gitInit() commit(1) commit(2) git("checkout", "-b", "2.1") commit(3) git("checkout", "master") commit(4) log() } and { _, repo -> GitRepo.prepare { git("clone", repo.dir.absolutePath, ".") } and { cloneClient, _ -> val branches = cloneClient.branches assertEquals(2, branches.branches.size) assertEquals("2.1", branches.branches[0].name) assertEquals("Commit 3", branches.branches[0].commit.shortMessage) assertEquals("master", branches.branches[1].name) assertEquals("Commit 4", branches.branches[1].commit.shortMessage) } } } @Test fun `Log between HEAD and a commit ~ 1`() { GitRepo.prepare { gitInit() (1..6).forEach { commit(it) } log() } and { repoClient, repo -> val commit4 = repo.commitLookup("Commit 4") val log = repoClient.log("$commit4~1", "HEAD").collect(Collectors.toList()) assertEquals( listOf("Commit 6", "Commit 5", "Commit 4"), log.map { it.shortMessage } ) } } @Test fun `Graph between commits`() { GitRepo.prepare { gitInit() commit(1) commit(2) commit(3) tag("v3") commit(4) tag("v4") commit(5) commit(6) commit(7) tag("v7") commit(8) log() } and { repoClient, repo -> val commit4 = repo.commitLookup("Commit 4") val commit7 = repo.commitLookup("Commit 7") val log = repoClient.graph(commit7, commit4) assertEquals( listOf("Commit 7", "Commit 6", "Commit 5"), log.commits.map { it.shortMessage } ) } } /** * What is the change log for 2.2 since 2.1? * <pre> * | * C11 (v2.2, 2.2) * * | C10 * | * C9 * | * C8 * |/ * * C7 * * M6 * |\ * | * C5 (v2.1, 2.1) * * | C4 * | * C3 * |/ * * C2 * * C1 * </pre> * * We expect C4, M6, C7, C8, C10, C11 */ @Test fun `Log between tags on different branches`() { GitRepo.prepare { gitInit() commit(1) commit(2) git("checkout", "-b", "2.1") commit(3) git("checkout", "master") commit(4) git("checkout", "2.1") commit(5) tag("v2.1") git("checkout", "master") git("merge", "--no-ff", "2.1", "--message", "Merge 2.1") // M6 commit(7) git("checkout", "-b", "2.2") commit(8) commit(9) git("checkout", "master") commit(10) git("checkout", "2.2") commit(11) tag("v2.2") log() } and { repoClient, _ -> val log = repoClient.graph("v2.2", "v2.1") assertEquals( listOf("Commit 11", "Commit 9", "Commit 8", "Commit 7", "Merge 2.1", "Commit 4"), log.commits.map { it.shortMessage } ) } } /** * What is the change log for 2.2 since 2.1? * * We expect C4, C7, C8, C10, C11, Merge 2.1->2.2, C14 * * @see #prepareBranches(GitRepo) */ @Test fun `Log between tags on different hierarchical branches`() { GitRepo.prepare { prepareBranches() } and { repoClient, _ -> val log = repoClient.graph("v2.2", "v2.1") assertEquals( listOf( "Commit 14", "Merge 2.1->2.2", "Commit 11", "Commit 10", "Commit 8", "Commit 7", "Commit 4"), log.commits.map { it.shortMessage } ) } } /** * Getting the tag for a commit */ @Test fun `Tag containing a commit`() { GitRepo.prepare { prepareBranches() } withClone { client, clientRepo, _ -> client.sync(Consumer { println(it) }) // No further tag assertEquals( emptyList(), client.getTagsWhichContainCommit(clientRepo.commitLookup("Commit 13")) ) // Exact tag assertEquals( listOf("v2.2"), client.getTagsWhichContainCommit(clientRepo.commitLookup("Commit 14")) ) // Several tags, including current commit assertEquals( listOf("v2.1", "v2.2"), client.getTagsWhichContainCommit(clientRepo.commitLookup("Commit 12")) ) // Several tags assertEquals( listOf("v2.1", "v2.2"), client.getTagsWhichContainCommit(clientRepo.commitLookup("Commit 9")) ) } } @Test fun `Log between tags`() { GitRepo.prepare { gitInit() commit(1) commit(2) commit(3) tag("v3") commit(4) tag("v4") commit(5) commit(6) commit(7) tag("v7") commit(8) log() } and { client, _ -> val log = client.graph("v7", "v4") assertEquals( listOf("Commit 7", "Commit 6", "Commit 5"), log.commits.map { it.shortMessage } ) } } @Test fun `Collection of remote branches`() { GitRepo.prepare { // Initialises a Git repository gitInit() // Commits 1..4, each one a branch (1..4).forEach { commit(it) git("branch", "feature/$it", "HEAD") } // Log log() } and { _, repo -> GitRepo.prepare { git("clone", repo.dir.absolutePath, ".") } and { cloneClient, _ -> val branches = cloneClient.remoteBranches // Checks the list assertEquals( (1..4).map { "feature/$it" } + listOf("master"), branches.sorted() ) } } } @Test fun `Get tags`() { GitRepo.prepare { prepareBranches() } withClone { client, _, _ -> client.sync(Consumer { println(it) }) val expectedDate = Time.now().toLocalDate() assertEquals( listOf("v2.1", "v2.2"), client.tags.map { it.name } ) assertEquals( listOf(expectedDate, expectedDate), client.tags.map { it.time.toLocalDate() } ) } } @Test fun `Clone and fetch`() { GitRepo.prepare { // Initialises a Git repository gitInit() // Commits 1..4 (1..4).forEach { commit(it) } } withClone { clone, cloneRepo, origin -> // First sync (clone) clone.sync(Consumer { println(it) }) // Gets the commits (1..4).forEach { assertNotNull(cloneRepo.commitLookup("Commit $it")) } // Adds some commits on the origin repo origin.apply { (5..8).forEach { commit(it) } } // Second sync (fetch) clone.sync(Consumer { println(it) }) // Gets the commits (5..8).forEach { assertNotNull(cloneRepo.commitLookup("Commit $it")) } } } /** * Prepares some branches in a test repo. * <pre> * | * C14 (v2.2, 2.2) * * | C13 * | * Merge 2.1->2.2 * | |\_________________ * | | \ * | | * C12 (v2.1, 2.1) * | * C11 | * | * C10 | * |/ | * | * C9 * * C8 | * * C7 | * | | * | * C6 * | * C5 * * | C4 * | * C3 * |--------------------/ * * C2 * * C1 * </pre> */ private fun GitRepo.prepareBranches() { gitInit() commit(1) commit(2) git("checkout", "-b", "2.1") commit(3) git("checkout", "master") commit(4) git("checkout", "2.1") commit(5) commit(6) git("checkout", "master") commit(7) commit(8) git("checkout", "2.1") commit(9) git("checkout", "-b", "2.2", "master") commit(10) commit(11) git("checkout", "2.1") commit(12) tag("v2.1") git("checkout", "2.2") git("merge", "--no-ff", "2.1", "--message", "Merge 2.1->2.2") git("checkout", "master") commit(13) git("checkout", "2.2") commit(14) tag("v2.2") log() } }
mit
92d85e77980b7a87a55da897bd7453e6
26.496047
101
0.392467
4.300464
false
false
false
false
Zeyad-37/RxRedux
app/src/main/java/com/zeyad/rxredux/utils/Constants.kt
1
267
package com.zeyad.rxredux.utils object Constants { object URLS { const val API_BASE_URL = "https://api.github.com/" const val USERS = "users?since=%s" const val USER = "users/%s" const val REPOSITORIES = "users/%s/repos" } }
apache-2.0
fb1108a2f9b8f5a371c7759b617ec521
23.272727
58
0.599251
3.513158
false
false
false
false
nibarius/opera-park-android
app/src/main/java/se/barsk/park/settings/SettingsActivity.kt
1
4233
package se.barsk.park.settings import android.content.SharedPreferences import android.os.Bundle import android.text.InputType import androidx.appcompat.app.AppCompatActivity import androidx.preference.* import de.psdev.licensesdialog.LicensesDialogFragment import se.barsk.park.BuildConfig import se.barsk.park.ParkApp import se.barsk.park.R import se.barsk.park.utils.Utils /** * Activity for settings */ class SettingsActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { ParkApp.init(this) super.onCreate(savedInstanceState) } // https://stackoverflow.com/questions/26509180/no-actionbar-in-preferenceactivity-after-upgrade-to-support-library-v21 override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) val fragment = ParkPreferenceFragment() fragment.setThirdPartyClickListener { showThirdPartyList() } supportFragmentManager.beginTransaction().replace(android.R.id.content, fragment).commit() } private fun showThirdPartyList() { val fragment = LicensesDialogFragment.Builder(this) .setNotices(R.raw.notices) .setNoticesCssStyle(R.string.notices_custom_style) .setShowFullLicenseText(false) .setIncludeOwnLicense(true) .build() fragment.show(supportFragmentManager, null) } class ParkPreferenceFragment : PreferenceFragmentCompat(), SharedPreferences.OnSharedPreferenceChangeListener { private lateinit var thirdPartyListener: () -> Unit override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { preferenceManager.sharedPreferencesName = ParkApp.getSharedPreferencesFileName(requireActivity().applicationContext) setPreferencesFromResource(R.xml.preferences, rootKey) } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) = preferenceChanged(key) override fun onResume() { super.onResume() setupPreferences() preferenceScreen.sharedPreferences.registerOnSharedPreferenceChangeListener(this) } override fun onPause() { super.onPause() preferenceScreen.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this) } fun setThirdPartyClickListener(listener: () -> Unit) { thirdPartyListener = listener } private fun setupPreferences() { findPreference<PreferenceCategory>(getString(R.string.key_about_group)) ?.title = getString(R.string.settings_about_group_title, getString(R.string.app_name)) findPreference<Preference>(getString(R.string.key_version))?.title = getString(R.string.settings_version, BuildConfig.VERSION_NAME) val serverPref = findPreference<EditTextPreference>(getString(R.string.key_park_server_url)) serverPref?.setOnBindEditTextListener { editText -> editText.hint = getString(R.string.park_server_input_hint) editText.inputType = InputType.TYPE_TEXT_VARIATION_URI } findPreference<Preference>(getString(R.string.key_third_party_licenses)) ?.setOnPreferenceClickListener { thirdPartyListener() true } } private fun preferenceChanged(key: String) { when (key) { getString(R.string.key_usage_statistics) -> { ParkApp.storageManager.recordUsageStatisticsConsentChange() ParkApp.analytics.optOutToggled() } getString(R.string.key_crash_reporting) -> { ParkApp.storageManager.recordCrashReportingConsentChange() } getString(R.string.key_theme) -> { val value = findPreference<ListPreference>(key) ?.value ?: getString(R.string.default_theme) Utils.setTheme(value) } } } } }
mit
8e23c8c8140c3f782110879a6be20323
40.106796
143
0.649894
5.419974
false
false
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/internal/ui/uiDslShowcase/DemoTips.kt
3
4914
// 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.internal.ui.uiDslShowcase import com.intellij.icons.AllIcons import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.util.Disposer import com.intellij.ui.dsl.builder.* import com.intellij.ui.dsl.gridLayout.HorizontalAlign import com.intellij.ui.dsl.gridLayout.VerticalAlign import com.intellij.util.ui.JBUI @Suppress("DialogTitleCapitalization") @Demo(title = "Tips", description = "Here are some useful tips and tricks", scrollbar = true) fun demoTips(parentDisposable: Disposable): DialogPanel { val panel = panel { row { label("Bold text") .bold() }.rowComment("Use Cell.bold method for bold text, works for any component") row { textField() .columns(COLUMNS_MEDIUM) }.rowComment("Configure width of textField, comboBox and textArea by columns method") row { textField() .text("Initialized text") }.rowComment("Set initial text of text component by text method") row("intTextField(0..1000, 100):") { intTextField(0..1000, 100) .text("500") }.rowComment("Use Row.intTextField for input integer numbers. There is value validation, range validation and " + "supported up/down keys") row("Some text") { textField() .resizableColumn() link("Config...") {} link("About") {} }.rowComment("Use Cell.resizableColumn if column should occupy whole free space. Remaining cells are adjusted to the right") row { text("If needed text color of Row.text() can be changed to comment color with the following code:<br>" + "foreground = JBUI.CurrentTheme.ContextHelp.FOREGROUND<br>" + "It differs from Row.comment() because comments can use smaller font size on macOS and Linux") .applyToComponent { foreground = JBUI.CurrentTheme.ContextHelp.FOREGROUND } } group("Use Row.cell() to disable expanding components on whole width") { row("Row 1:") { textField() .gap(RightGap.SMALL) .resizableColumn() .horizontalAlign(HorizontalAlign.FILL) val action = object : DumbAwareAction(AllIcons.Actions.QuickfixOffBulb) { override fun actionPerformed(e: AnActionEvent) { } } actionButton(action) }.layout(RowLayout.PARENT_GRID) row("Row 2:") { textField() .gap(RightGap.SMALL) .horizontalAlign(HorizontalAlign.FILL) cell() }.layout(RowLayout.PARENT_GRID) .rowComment("Last textField occupies only one column like the previous textField") } group("Use Panel.row(EMPTY_LABEL) if label is empty") { row("Row 1:") { textField() } row(EMPTY_LABEL) { textField() }.rowComment("""Don't use row(""), because it creates unnecessary label component in layout""") } group("Use Cell.widthGroup to use the same width") { row { textField().widthGroup("GroupName") } row { button("Button") {}.widthGroup("GroupName") }.rowComment("All components from the same width group will have the same width equals to maximum width from the group. Cannot be used together with HorizontalAlign.FILL") } row { panel { group("No default radio button") { var value = 0 buttonsGroup { row { radioButton("Value = 1", 1) } row { radioButton("Value = 2", 2) .comment("Initial bounded value is 0, RadioButtons in the group are deselected by default", maxLineLength = 40) } }.bind({ value }, { value = it }) } }.gap(RightGap.COLUMNS) .verticalAlign(VerticalAlign.TOP) .resizableColumn() panel { group("Default radio button") { var value = 0 buttonsGroup { row { radioButton("Value = 1", 1) } row { radioButton("Value = 2, isSelected = true", 2) .applyToComponent { isSelected = true } .comment("Initial bounded value is 0, this RadioButton is selected because initial bound variable value is not equal to values of RadioButton in the group and isSelected = true", maxLineLength = 40) } }.bind({ value }, { value = it }) } }.verticalAlign(VerticalAlign.TOP) .resizableColumn() } } val disposable = Disposer.newDisposable() panel.registerValidators(disposable) Disposer.register(parentDisposable, disposable) return panel }
apache-2.0
57cdcf0999155132b8e5216a7b633a4d
35.4
214
0.633903
4.666667
false
false
false
false
google/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/sam/samConversion.kt
3
8615
// 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.groovy.lang.sam import com.intellij.openapi.util.registry.Registry import com.intellij.psi.* import com.intellij.psi.CommonClassNames.JAVA_LANG_OBJECT import com.intellij.psi.impl.source.resolve.graphInference.FunctionalInterfaceParameterizationUtil import com.intellij.psi.impl.source.resolve.graphInference.constraints.ConstraintFormula import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.MethodSignature import com.intellij.psi.util.TypeConversionUtil import com.intellij.util.castSafelyTo import org.jetbrains.plugins.groovy.config.GroovyConfigUtils import org.jetbrains.plugins.groovy.lang.psi.api.GrFunctionalExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.GrTypeConverter import org.jetbrains.plugins.groovy.lang.psi.util.GrTraitUtil.isTrait import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames import org.jetbrains.plugins.groovy.lang.resolve.api.* import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.ExpectedType import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.GroovyInferenceSession import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.TypeConstraint import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.TypePositionConstraint import org.jetbrains.plugins.groovy.lang.typing.GroovyClosureType fun findSingleAbstractMethod(clazz: PsiClass): PsiMethod? = findSingleAbstractSignatureCached(clazz)?.method fun findSingleAbstractSignature(clazz: PsiClass): MethodSignature? = findSingleAbstractSignatureCached(clazz) private fun findSingleAbstractMethodAndClass(type: PsiType): Pair<PsiMethod, PsiClassType.ClassResolveResult>? { val groundType = (type as? PsiClassType)?.let { FunctionalInterfaceParameterizationUtil.getNonWildcardParameterization(it) } ?: return null val resolveResult = (groundType as PsiClassType).resolveGenerics() val samClass = resolveResult.element ?: return null val sam = findSingleAbstractMethod(samClass) ?: return null return sam to resolveResult } private fun findSingleAbstractSignatureCached(clazz: PsiClass): HierarchicalMethodSignature? { return CachedValuesManager.getCachedValue(clazz) { CachedValueProvider.Result.create(doFindSingleAbstractSignature(clazz), clazz) } } private fun doFindSingleAbstractSignature(clazz: PsiClass): HierarchicalMethodSignature? { var result: HierarchicalMethodSignature? = null for (signature in clazz.visibleSignatures) { if (!isEffectivelyAbstractMethod(signature)) continue if (result != null) return null // found another abstract method result = signature } return result } private fun isEffectivelyAbstractMethod(signature: HierarchicalMethodSignature): Boolean { val method = signature.method if (!method.hasModifierProperty(PsiModifier.ABSTRACT)) return false if (isObjectMethod(signature)) return false if (isImplementedTraitMethod(method)) return false return true } private fun isObjectMethod(signature: HierarchicalMethodSignature): Boolean { return signature.superSignatures.any { it.method.containingClass?.qualifiedName == JAVA_LANG_OBJECT } } private fun isImplementedTraitMethod(method: PsiMethod): Boolean { val clazz = method.containingClass ?: return false if (!isTrait(clazz)) return false val traitMethod = method as? GrMethod ?: return false return traitMethod.block != null } fun isSamConversionAllowed(context: PsiElement): Boolean { return GroovyConfigUtils.getInstance().isVersionAtLeast(context, GroovyConfigUtils.GROOVY2_2) } internal fun processSAMConversion(targetType: PsiType, closureType: GroovyClosureType, context: PsiElement): List<ConstraintFormula> { val constraints = mutableListOf<ConstraintFormula>() val pair = findSingleAbstractMethodAndClass(targetType) if (pair == null) { constraints.add( TypeConstraint(targetType, TypesUtil.createTypeByFQClassName(GroovyCommonClassNames.GROOVY_LANG_CLOSURE, context), context)) return constraints } val (sam, classResolveResult) = pair val groundClass = classResolveResult.element ?: return constraints val groundType = groundTypeForClosure(sam, groundClass, closureType, classResolveResult.substitutor, context) if (groundType != null) { constraints.add(TypeConstraint(targetType, groundType, context)) } return constraints } private fun returnTypeConstraint(samReturnType: PsiType?, returnType: PsiType?, context: PsiElement): ConstraintFormula? { if (returnType == null || samReturnType == null || samReturnType == PsiType.VOID) { return null } return TypeConstraint(samReturnType, returnType, context) } /** * JLS 18.5.3 * com.intellij.psi.impl.source.resolve.graphInference.FunctionalInterfaceParameterizationUtil.getFunctionalTypeExplicit */ private fun groundTypeForClosure(sam: PsiMethod, groundClass: PsiClass, closureType: GroovyClosureType, resultTypeSubstitutor : PsiSubstitutor, context: PsiElement): PsiClassType? { if (!Registry.`is`("groovy.use.explicitly.typed.closure.in.inference", true)) return null val typeParameters = groundClass.typeParameters ?: return null if (typeParameters.isEmpty()) return null val samContainingClass = sam.containingClass ?: return null val groundClassSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(samContainingClass, groundClass, PsiSubstitutor.EMPTY) // erase all ground class parameters to null, otherwise explicit closure signature will be inapplicable val erasingSubstitutor = PsiSubstitutor.createSubstitutor(typeParameters.associate { it to PsiType.NULL }) val samParameterTypes = sam.parameterList.parameters.map { it.type } val arguments = samParameterTypes.map { val withInheritance = groundClassSubstitutor.substitute(it) ExplicitRuntimeTypeArgument(withInheritance, TypeConversionUtil.erasure(erasingSubstitutor.substitute(withInheritance))) } val argumentMapping = closureType.applyTo(arguments).find { it.applicability() == Applicability.applicable } ?: return null val samSession = GroovyInferenceSession(typeParameters, PsiSubstitutor.EMPTY, context, false) argumentMapping.expectedTypes.forEach { (expectedType, argument) -> val adjustedExpectedType = adjustUntypedParameter(argument, argumentMapping.targetParameter(argument), resultTypeSubstitutor) ?: expectedType val leftType = samSession.substituteWithInferenceVariables(groundClassSubstitutor.substitute(adjustedExpectedType)) samSession.addConstraint( TypePositionConstraint(ExpectedType(leftType, GrTypeConverter.Position.METHOD_PARAMETER), samSession.substituteWithInferenceVariables(argument.type), context)) } val returnTypeConstraint = returnTypeConstraint(sam.returnType, closureType.returnType(arguments), context) if (returnTypeConstraint != null) samSession.addConstraint(returnTypeConstraint) if (!samSession.repeatInferencePhases()) { return null } val resultSubstitutor = samSession.result() val elementFactory = JavaPsiFacade.getElementFactory(context.project) return elementFactory.createType(groundClass, resultSubstitutor) } private fun adjustUntypedParameter(argument : Argument, parameter : CallParameter?, resultTypeSubstitutor: PsiSubstitutor) : PsiType? { val psi = (parameter as? PsiCallParameter)?.psi?.takeIf { it.typeElement == null } ?: return null return if (psi.typeElement == null) { resultTypeSubstitutor.substitute(argument.type) } else { null } } internal fun samDistance(closure: Argument?, samClass: PsiClass?) : Int? { if (closure !is ExpressionArgument || closure.type !is GroovyClosureType) { return null } samClass ?: return null val sam = findSingleAbstractMethod(samClass) ?: return null val argument = closure.expression.castSafelyTo<GrFunctionalExpression>() ?: return null if (argument.parameterList.isEmpty) { return 3 } if (sam.parameters.isEmpty() == argument.parameters.isEmpty()) { return 2 } else { return 3 } }
apache-2.0
3a10bb03604a5b7c7c37a26a097c4bad
45.322581
165
0.778178
4.985532
false
false
false
false
JetBrains/intellij-community
plugins/settings-sync/src/com/intellij/settingsSync/plugins/SettingsSyncPluginInstallerImpl.kt
1
4166
package com.intellij.settingsSync.plugins import com.intellij.ide.plugins.marketplace.MarketplaceRequests import com.intellij.notification.NotificationAction import com.intellij.notification.NotificationGroupManager import com.intellij.notification.NotificationType import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.ex.ApplicationEx import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.updateSettings.impl.PluginDownloader import com.intellij.settingsSync.NOTIFICATION_GROUP import com.intellij.settingsSync.SettingsSyncBundle import com.intellij.util.Consumer import com.intellij.util.concurrency.annotations.RequiresBackgroundThread internal class SettingsSyncPluginInstallerImpl(private val notifyErrors: Boolean) : SettingsSyncPluginInstaller { companion object { val LOG = logger<SettingsSyncPluginInstallerImpl>() } @RequiresBackgroundThread override fun installPlugins(pluginsToInstall: List<PluginId>) { if (pluginsToInstall.isEmpty() || ApplicationManager.getApplication().isUnitTestMode // Register TestPluginManager in Unit Test Mode ) return ApplicationManager.getApplication().invokeAndWait { val prepareRunnable = PrepareInstallationRunnable(pluginsToInstall, notifyErrors) if (ProgressManager.getInstance().runProcessWithProgressSynchronously( prepareRunnable, SettingsSyncBundle.message("installing.plugins.indicator"), true, null)) { installCollected(prepareRunnable.getInstallers()) } } } private fun installCollected(installers: List<PluginDownloader>) { var isRestartNeeded = false installers.forEach { if (!it.installDynamically(null)) { isRestartNeeded = true } LOG.info("Installed plugin ID: " + it.id.idString) } if (isRestartNeeded) notifyRestartNeeded() } private fun notifyRestartNeeded() { val notification = NotificationGroupManager.getInstance().getNotificationGroup(NOTIFICATION_GROUP) .createNotification(SettingsSyncBundle.message("plugins.sync.restart.notification.title"), SettingsSyncBundle.message("plugins.sync.restart.notification.message"), NotificationType.INFORMATION) notification.addAction(NotificationAction.create( SettingsSyncBundle.message("plugins.sync.restart.notification.action", ApplicationNamesInfo.getInstance().fullProductName), Consumer { val app = ApplicationManager.getApplication() as ApplicationEx app.restart(true) })) notification.notify(null) } private class PrepareInstallationRunnable(val pluginIds: List<PluginId>, val notifyErrors: Boolean) : Runnable { private val collectedInstallers = ArrayList<PluginDownloader>() @RequiresBackgroundThread override fun run() { val indicator = ProgressManager.getInstance().progressIndicator pluginIds.forEach { prepareToInstall(it, indicator) indicator.checkCanceled() } } @RequiresBackgroundThread private fun prepareToInstall(pluginId: PluginId, indicator: ProgressIndicator) { val descriptor = MarketplaceRequests.getInstance().getLastCompatiblePluginUpdate(pluginId, indicator = indicator) if (descriptor != null) { val downloader = PluginDownloader.createDownloader(descriptor) if (downloader.prepareToInstall(indicator)) { collectedInstallers.add(downloader) } } else { val message = SettingsSyncBundle.message("install.plugin.failed.no.compatible.notification.error.message", pluginId ) LOG.info(message) if (notifyErrors) { NotificationGroupManager.getInstance().getNotificationGroup(NOTIFICATION_GROUP) .createNotification("", message, NotificationType.ERROR) .notify(null) } } } fun getInstallers() = collectedInstallers } }
apache-2.0
254176eafefca028dd3b09c791ff2215
40.67
129
0.754921
5.438642
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/markingUtils.kt
1
6958
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.pullUp import com.intellij.openapi.util.Key import com.intellij.psi.PsiElement import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.idea.codeInsight.shorten.addToShorteningWaitSet import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.allChildren import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiverOrThis import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.calls.util.getCalleeExpressionIfAny import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.util.getExplicitReceiverValue import org.jetbrains.kotlin.types.TypeSubstitutor import org.jetbrains.kotlin.types.Variance private var KtElement.newFqName: FqName? by CopyablePsiUserDataProperty(Key.create("NEW_FQ_NAME")) private var KtElement.replaceWithTargetThis: Boolean? by CopyablePsiUserDataProperty(Key.create("REPLACE_WITH_TARGET_THIS")) private var KtElement.newTypeText: ((TypeSubstitutor) -> String?)? by CopyablePsiUserDataProperty(Key.create("NEW_TYPE_TEXT")) fun markElements( declaration: KtNamedDeclaration, context: BindingContext, sourceClassDescriptor: ClassDescriptor, targetClassDescriptor: ClassDescriptor? ): List<KtElement> { val affectedElements = ArrayList<KtElement>() declaration.accept( object : KtVisitorVoid() { private fun visitSuperOrThis(expression: KtInstanceExpressionWithLabel) { if (targetClassDescriptor == null) return val callee = expression.getQualifiedExpressionForReceiver()?.selectorExpression?.getCalleeExpressionIfAny() ?: return val calleeTarget = callee.getResolvedCall(context)?.resultingDescriptor ?: return if ((calleeTarget as? CallableMemberDescriptor)?.kind != CallableMemberDescriptor.Kind.DECLARATION) return if (calleeTarget.containingDeclaration == targetClassDescriptor) { expression.replaceWithTargetThis = true affectedElements.add(expression) } } override fun visitElement(element: PsiElement) { element.allChildren.forEach { it.accept(this) } } override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { val resolvedCall = expression.getResolvedCall(context) ?: return val receiver = resolvedCall.getExplicitReceiverValue() ?: resolvedCall.extensionReceiver ?: resolvedCall.dispatchReceiver ?: return val implicitThis = receiver.type.constructor.declarationDescriptor as? ClassDescriptor ?: return if (implicitThis.isCompanionObject && DescriptorUtils.isAncestor(sourceClassDescriptor, implicitThis, true) ) { val qualifierFqName = implicitThis.importableFqName ?: return expression.newFqName = FqName("${qualifierFqName.asString()}.${expression.getReferencedName()}") affectedElements.add(expression) } } override fun visitThisExpression(expression: KtThisExpression) { visitSuperOrThis(expression) } override fun visitSuperExpression(expression: KtSuperExpression) { visitSuperOrThis(expression) } override fun visitTypeReference(typeReference: KtTypeReference) { val oldType = context[BindingContext.TYPE, typeReference] ?: return typeReference.newTypeText = f@{ substitutor -> substitutor.substitute(oldType, Variance.INVARIANT)?.let { IdeDescriptorRenderers.SOURCE_CODE.renderType(it) } } affectedElements.add(typeReference) } } ) return affectedElements } fun applyMarking( declaration: KtNamedDeclaration, substitutor: TypeSubstitutor, targetClassDescriptor: ClassDescriptor ) { val psiFactory = KtPsiFactory(declaration.project) val targetThis = psiFactory.createExpression("this@${targetClassDescriptor.name.asString().quoteIfNeeded()}") val shorteningOptionsForThis = ShortenReferences.Options(removeThisLabels = true, removeThis = true) declaration.accept( object : KtVisitorVoid() { private fun visitSuperOrThis(expression: KtInstanceExpressionWithLabel) { expression.replaceWithTargetThis?.let { expression.replaceWithTargetThis = null val newThisExpression = expression.replace(targetThis) as KtExpression newThisExpression.getQualifiedExpressionForReceiverOrThis().addToShorteningWaitSet(shorteningOptionsForThis) } } override fun visitElement(element: PsiElement) { for (it in element.allChildren.toList()) { it.accept(this) } } override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { expression.newFqName?.let { expression.newFqName = null expression.mainReference.bindToFqName(it) } } override fun visitThisExpression(expression: KtThisExpression) { this.visitSuperOrThis(expression) } override fun visitSuperExpression(expression: KtSuperExpression) { this.visitSuperOrThis(expression) } override fun visitTypeReference(typeReference: KtTypeReference) { typeReference.newTypeText?.let f@{ typeReference.newTypeText = null val newTypeText = it(substitutor) ?: return@f (typeReference.replace(psiFactory.createType(newTypeText)) as KtElement).addToShorteningWaitSet() } } } ) } fun clearMarking(markedElements: List<KtElement>) { markedElements.forEach { it.newFqName = null it.newTypeText = null it.replaceWithTargetThis = null } }
apache-2.0
152a3dcc8a9de43ff47579ac104a7ad7
43.896774
158
0.683961
5.808013
false
false
false
false
allotria/intellij-community
platform/external-system-impl/src/com/intellij/openapi/externalSystem/autoimport/changes/AsyncFilesChangesListener.kt
2
3949
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.autoimport.changes import com.intellij.openapi.Disposable import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ModificationType import com.intellij.openapi.externalSystem.autoimport.settings.AsyncSupplier import com.intellij.openapi.externalSystem.util.PathPrefixTreeMap import com.intellij.openapi.vfs.VirtualFileManager import java.util.concurrent.ConcurrentHashMap /** * Filters and delegates files and documents events into subscribed listeners. * Allows to use heavy paths filer, that is defined by [filesProvider]. * Call sequences of [changesListener]'s functions will be skipped if change events didn't happen in watched files. */ class AsyncFilesChangesListener( private val filesProvider: AsyncSupplier<Set<String>>, private val changesListener: FilesChangesListener, private val parentDisposable: Disposable ) : FilesChangesListener { private val updatedFiles = ConcurrentHashMap<String, ModificationData>() override fun init() { updatedFiles.clear() } override fun onFileChange(path: String, modificationStamp: Long, modificationType: ModificationType) { updatedFiles[path] = ModificationData(modificationStamp, modificationType) } override fun apply() { val updatedFilesSnapshot = HashMap(updatedFiles) filesProvider.supply( { filesToWatch -> val index = PathPrefixTreeMap<Boolean>() filesToWatch.forEach { index[it] = true } val updatedWatchedFiles = updatedFilesSnapshot.flatMap { (path, modificationData) -> index.getAllAncestorKeys(path).map { it to modificationData } } if (updatedWatchedFiles.isNotEmpty()) { changesListener.init() for ((path, modificationData) in updatedWatchedFiles) { val (modificationStamp, modificationType) = modificationData changesListener.onFileChange(path, modificationStamp, modificationType) } changesListener.apply() } }, parentDisposable) } private data class ModificationData(val modificationStamp: Long, val modificationType: ModificationType) companion object { @JvmStatic fun subscribeOnDocumentsAndVirtualFilesChanges( filesProvider: AsyncSupplier<Set<String>>, listener: FilesChangesListener, parentDisposable: Disposable ) { subscribeOnVirtualFilesChanges(true, filesProvider, listener, parentDisposable) subscribeOnDocumentsChanges(true, filesProvider, listener, parentDisposable) } @JvmStatic fun subscribeOnVirtualFilesChanges( isIgnoreInternalChanges: Boolean, filesProvider: AsyncSupplier<Set<String>>, listener: FilesChangesListener, parentDisposable: Disposable ) { val changesProvider = VirtualFilesChangesProvider(isIgnoreInternalChanges) val fileManager = VirtualFileManager.getInstance() fileManager.addAsyncFileListener(changesProvider, parentDisposable) val asyncListener = AsyncFilesChangesListener(filesProvider, listener, parentDisposable) changesProvider.subscribe(asyncListener, parentDisposable) } @JvmStatic fun subscribeOnDocumentsChanges( isIgnoreExternalChanges: Boolean, filesProvider: AsyncSupplier<Set<String>>, listener: FilesChangesListener, parentDisposable: Disposable ) { val changesProvider = DocumentsChangesProvider(isIgnoreExternalChanges) val eventMulticaster = EditorFactory.getInstance().eventMulticaster eventMulticaster.addDocumentListener(changesProvider, parentDisposable) val asyncListener = AsyncFilesChangesListener(filesProvider, listener, parentDisposable) changesProvider.subscribe(asyncListener, parentDisposable) } } }
apache-2.0
4bce4a4290f19b377326a6b9cb242ff4
41.473118
140
0.762472
5.561972
false
false
false
false
leafclick/intellij-community
platform/platform-tests/testSrc/com/intellij/internal/statistics/whitelist/WhitelistBuilder.kt
1
2290
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.statistics.whitelist import com.intellij.internal.statistic.eventLog.EventLogBuildNumber import com.intellij.internal.statistic.service.fus.FUSWhitelist import com.intellij.internal.statistic.service.fus.FUSWhitelist.BuildRange import com.intellij.internal.statistic.service.fus.FUSWhitelist.VersionRange class WhitelistBuilder { private val groupIds: MutableSet<String> = HashSet() private val groupVersions: MutableMap<String, MutableList<VersionRange>> = HashMap() private val groupBuilds: MutableMap<String, MutableList<BuildRange>> = HashMap() fun addVersion(id: String, from: Int, to: Int): WhitelistBuilder { if (!groupVersions.containsKey(id)) { groupIds.add(id) groupVersions[id] = mutableListOf() } groupVersions[id]!!.add(VersionRange(from, to)) return this } fun addVersion(id: String, from: String?, to: String?): WhitelistBuilder { if (!groupVersions.containsKey(id)) { groupIds.add(id) groupVersions[id] = mutableListOf() } groupVersions[id]!!.add(VersionRange.create(from, to)) return this } fun addBuild(id: String, from: EventLogBuildNumber?, to: EventLogBuildNumber?): WhitelistBuilder { if (!groupBuilds.containsKey(id)) { groupIds.add(id) groupBuilds[id] = mutableListOf() } groupBuilds[id]!!.add(BuildRange(from, to)) return this } fun addBuild(id: String, from: String?, to: String?): WhitelistBuilder { if (!groupBuilds.containsKey(id)) { groupIds.add(id) groupBuilds[id] = mutableListOf() } groupBuilds[id]!!.add(BuildRange.create(from, to)) return this } fun build(): FUSWhitelist { val result = HashMap<String, FUSWhitelist.GroupFilterCondition>() for (groupId in groupIds) { groupBuilds.getOrDefault(groupId, emptyList<BuildRange>()) val builds: List<BuildRange> = groupBuilds.getOrDefault(groupId, emptyList()) val versions: List<VersionRange> = groupVersions.getOrDefault(groupId, emptyList()) result[groupId] = FUSWhitelist.GroupFilterCondition(builds, versions) } return FUSWhitelist.create(result) } }
apache-2.0
3e77f1429d21a3235325119e4c1081d8
37.183333
140
0.722271
4.163636
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/boxInline/lambdaTransformation/lambdaInLambdaNoInline.kt
3
1450
// FILE: 1.kt package test fun concat(suffix: String, l: (s: String) -> Unit) { l(suffix) } fun <T> noInlineFun(arg: T, f: (T) -> Unit) { f(arg) } inline fun doSmth(a: String): String { return a.toString() } // FILE: 2.kt //NO_CHECK_LAMBDA_INLINING import test.* fun test1(param: String): String { var result = "fail1" noInlineFun(param) { a -> concat("start") { result = doSmth(a).toString() } } return result } fun test11(param: String): String { var result = "fail1" noInlineFun("stub") { a -> concat("start") { result = doSmth(param).toString() } } return result } inline fun test2(crossinline param: () -> String): String { var result = "fail1" noInlineFun("stub") { a -> concat(param()) { result = doSmth(param()).toString() } } return result } inline fun test22(crossinline param: () -> String): String { var result = "fail1" {{result = param()}()}() return result } fun box(): String { if (test1("start") != "start") return "fail1: ${test1("start")}" if (test1("nostart") != "nostart") return "fail2: ${test1("nostart")}" if (test11("start") != "start") return "fail3: ${test11("start")}" if (test2({"start"}) != "start") return "fail4: ${test2({"start"})}" if (test22({"start"}) != "start") return "fail5: ${test22({"start"})}" return "OK" }
apache-2.0
87b3902583cd7b85b781df53d210275c
19.138889
74
0.546207
3.236607
false
true
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/reflection/supertypes/genericSubstitution.kt
2
907
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT import kotlin.reflect.full.allSupertypes import kotlin.test.assertEquals interface A<A1, A2> interface B<B1, B2> : A<B2, B1> interface C<C1> : B<C1, String> interface D : C<Int> interface StringList : List<String> fun box(): String { assertEquals( listOf(String::class, Int::class), D::class.allSupertypes.single { it.classifier == A::class }.arguments.map { it.type!!.classifier } ) val collectionType = StringList::class.allSupertypes.single { it.classifier == Collection::class } val arg = collectionType.arguments.single().type!! // TODO: this does not work currently because for some reason two different instances of TypeParameterDescriptor are created for List // assertEquals(String::class, arg.classifier) return "OK" }
apache-2.0
2d9f9e9229747f22ac4dba8090c51607
31.392857
137
0.706725
3.84322
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/operatorConventions/remOverModOperation.kt
2
296
class A() { var x = 5 operator fun mod(y: Int) { throw RuntimeException("mod has been called instead of rem") } operator fun rem(y: Int) { x -= y } } fun box(): String { val a = A() a % 5 if (a.x != 0) { return "Fail: a.x(${a.x}) != 0" } return "OK" }
apache-2.0
812e5497546c876657a1fff07ba30c00
15.5
93
0.489865
2.989899
false
false
false
false
smmribeiro/intellij-community
build/launch/src/com/intellij/tools/launch/impl/ClassPathBuilder.kt
1
4331
package com.intellij.tools.launch.impl import com.intellij.execution.CommandLineWrapperUtil import com.intellij.openapi.util.io.FileUtil import com.intellij.tools.launch.ModulesProvider import com.intellij.tools.launch.PathsProvider import org.jetbrains.jps.model.JpsElementFactory import org.jetbrains.jps.model.serialization.JpsModelSerializationDataService import org.jetbrains.jps.model.serialization.JpsProjectLoader import java.io.File import com.intellij.util.SystemProperties import org.apache.log4j.Logger import org.jetbrains.jps.model.java.JpsJavaClasspathKind import org.jetbrains.jps.model.java.JpsJavaExtensionService import org.jetbrains.jps.model.module.JpsModule import org.jetbrains.jps.model.module.JpsModuleDependency import java.util.* class ClassPathBuilder(private val paths: PathsProvider, private val modules: ModulesProvider) { private val logger = Logger.getLogger(ClassPathBuilder::class.java) companion object { fun createClassPathArgFile(paths: PathsProvider, classpath: List<String>): File { val launcherFolder = paths.launcherFolder if (!launcherFolder.exists()) { launcherFolder.mkdirs() } val classPathArgFile = launcherFolder.resolve("${paths.productId}Launcher_${UUID.randomUUID()}.classpath") CommandLineWrapperUtil.writeArgumentsFile(classPathArgFile, listOf("-classpath", classpath.distinct().joinToString(File.pathSeparator)), Charsets.UTF_8) return classPathArgFile } } private val model = JpsElementFactory.getInstance().createModel() ?: throw Exception("Couldn't create JpsModel") fun build(logClasspath: Boolean): File { val pathVariablesConfiguration = JpsModelSerializationDataService.getOrCreatePathVariablesConfiguration(model.global) val m2HomePath = File(SystemProperties.getUserHome()) .resolve(".m2") .resolve("repository") pathVariablesConfiguration.addPathVariable("MAVEN_REPOSITORY", m2HomePath.canonicalPath) val pathVariables = JpsModelSerializationDataService.computeAllPathVariables(model.global) JpsProjectLoader.loadProject(model.project, pathVariables, paths.sourcesRootFolder.canonicalPath) val productionOutput = paths.outputRootFolder.resolve("production") if (!productionOutput.isDirectory) { error("Production classes output directory is missing: $productionOutput") } JpsJavaExtensionService.getInstance().getProjectExtension(model.project)!!.outputUrl = "file://${FileUtil.toSystemIndependentName(paths.outputRootFolder.path)}" val modulesList = arrayListOf<String>() modulesList.add("intellij.platform.boot") modulesList.add(modules.mainModule) modulesList.addAll(modules.additionalModules) modulesList.add("intellij.configurationScript") return createClassPathArgFileForModules(modulesList, logClasspath) } private fun createClassPathArgFileForModules(modulesList: List<String>, logClasspath: Boolean): File { val classpath = mutableListOf<String>() for (moduleName in modulesList) { val module = model.project.modules.singleOrNull { it.name == moduleName } ?: throw Exception("Module $moduleName not found") if (isModuleExcluded(module)) continue classpath.addAll(getClasspathForModule(module)) } // Uncomment for big debug output // seeing as client classpath gets logged anyway, there's no need to comment this out if (logClasspath) { logger.info("Created classpath:") for (path in classpath.distinct().sorted()) { logger.info(" $path") } logger.info("-- END") } else { logger.warn("Verbose classpath logging is disabled, set logClasspath to true to see it.") } return createClassPathArgFile(paths, classpath) } private fun getClasspathForModule(module: JpsModule): List<String> { return JpsJavaExtensionService .dependencies(module) .recursively() .satisfying { if (it is JpsModuleDependency) !isModuleExcluded(it.module) else true } .includedIn(JpsJavaClasspathKind.runtime(modules.includeTestDependencies)) .classes().roots.filter { it.exists() }.map { it.path }.toList() } private fun isModuleExcluded(module: JpsModule?): Boolean { if (module == null) return true return modules.excludedModules.contains(module.name) } }
apache-2.0
509cd7677a47baa51275782278f809fe
41.058252
158
0.758485
4.888262
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/compilingEvaluator/inaccessibleMembers/selfMembers.kt
10
859
package ceMembers fun main(args: Array<String>) { A().test() } class A { public fun publicFun(): Int = 1 public val publicVal: Int = 2 protected fun protectedFun(): Int = 3 protected val protectedVal: Int = 4 @JvmField protected val protectedField: Int = 5 private fun privateFun() = 6 private val privateVal = 7 fun test() { //Breakpoint! val a = 1 } } fun <T> block(block: () -> T): T { return block() } // EXPRESSION: block { publicFun() } // RESULT: 1: I // EXPRESSION: block { publicVal } // RESULT: 2: I // EXPRESSION: block { protectedFun() } // RESULT: 3: I // EXPRESSION: block { protectedVal } // RESULT: 4: I // EXPRESSION: block { protectedField } // RESULT: 5: I // EXPRESSION: block { privateFun() } // RESULT: 6: I // EXPRESSION: block { privateVal } // RESULT: 7: I
apache-2.0
7268ac560b454e429682ad030c0e72e8
16.55102
41
0.599534
3.436
false
false
false
false
smmribeiro/intellij-community
plugins/filePrediction/src/com/intellij/filePrediction/actions/FilePredictionNextCandidatesAction.kt
10
5566
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.filePrediction.actions import com.intellij.filePrediction.FilePredictionBundle import com.intellij.filePrediction.FilePredictionNotifications import com.intellij.filePrediction.candidates.CompositeCandidateProvider import com.intellij.filePrediction.candidates.FilePredictionCandidateProvider import com.intellij.filePrediction.predictor.FilePredictionCandidate import com.intellij.filePrediction.predictor.FileUsagePredictorProvider import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.PopupStep import com.intellij.openapi.ui.popup.util.BaseListPopupStep import com.intellij.openapi.util.Iconable.ICON_FLAG_VISIBILITY import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import org.jetbrains.annotations.Nls import javax.swing.Icon import kotlin.math.round class FilePredictionNextCandidatesAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { val project = e.project if (project == null) { val message = FilePredictionBundle.message("file.prediction.predict.next.files.project.not.defined") FilePredictionNotifications.showWarning(null, message) return } val file: PsiFile? = e.getData(CommonDataKeys.PSI_FILE) val title = FilePredictionBundle.message("file.prediction.predict.next.files.process.title") ProgressManager.getInstance().run(object : Task.Backgroundable(project, title, false) { override fun run(indicator: ProgressIndicator) { val predictor = FileUsagePredictorProvider.getFileUsagePredictor(getCandidatesProvider()) val limit: Int = Registry.get("filePrediction.action.calculate.candidates").asInteger() val candidates = predictor.predictNextFile(project, file?.virtualFile, limit) ApplicationManager.getApplication().invokeLater { val toShow: Int = Registry.get("filePrediction.action.show.candidates").asInteger() showCandidates(project, e.dataContext, candidates.take(toShow)) } } }) } private fun getCandidatesProvider(): FilePredictionCandidateProvider { return CompositeCandidateProvider() } private fun showCandidates(project: Project, context: DataContext, candidates: List<FilePredictionCandidate>) { val title = FilePredictionBundle.message("file.prediction.predict.next.files.popup.title") val presentation = candidates.map { calculatePresentation(project, it) }.toList() val requestsCollectionPopup = JBPopupFactory.getInstance().createListPopup(object : BaseListPopupStep<FileCandidatePresentation>(title, presentation) { override fun getTextFor(value: FileCandidatePresentation?): String { return value?.presentableName?.let { val shortPath = StringUtil.shortenPathWithEllipsis(it, 50) "$shortPath (${roundProbability(value.original)})" } ?: super.getTextFor(value) } override fun getIconFor(value: FileCandidatePresentation?): Icon? { return value?.icon ?: super.getIconFor(value) } override fun onChosen(candidate: FileCandidatePresentation, finalChoice: Boolean): PopupStep<*>? { return doFinalStep { candidate.file?.let { FileEditorManager.getInstance(project).openFile(it, true) } } } }) requestsCollectionPopup.showInBestPositionFor(context) } private fun calculatePresentation(project: Project, candidate: FilePredictionCandidate): FileCandidatePresentation { val file = findSelectedFile(candidate) if (file == null) { return FileCandidatePresentation(file, null, candidate.path, candidate) } val psiFile = PsiManager.getInstance(project).findFile(file) val icon = psiFile?.getIcon(ICON_FLAG_VISIBILITY) return FileCandidatePresentation(file, icon, file.presentableName, candidate) } private fun roundProbability(candidate: FilePredictionCandidate): Double { val probability = candidate.probability ?: return -1.0 if (!probability.isFinite()) return -1.0 return round(probability * 100) / 100 } private fun findSelectedFile(candidate: FilePredictionCandidate?): VirtualFile? { if (candidate != null) { val url = VfsUtilCore.pathToUrl(candidate.path) return VirtualFileManager.getInstance().findFileByUrl(url) } return null } } private data class FileCandidatePresentation(val file: VirtualFile?, val icon: Icon?, @Nls val presentableName: String, val original: FilePredictionCandidate)
apache-2.0
f4dc7721b828a0ebc7775069ea62b8fa
45.008264
140
0.749371
4.903965
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/ast/MethodCallExpression.kt
6
2233
// 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.j2k.ast import com.intellij.psi.PsiElement import org.jetbrains.kotlin.j2k.CodeBuilder import org.jetbrains.kotlin.j2k.append class MethodCallExpression( val methodExpression: Expression, val argumentList: ArgumentList, val typeArguments: List<Type>, override val isNullable: Boolean ) : Expression() { override fun generateCode(builder: CodeBuilder) { builder.appendOperand(this, methodExpression).append(typeArguments, ", ", "<", ">") builder.append(argumentList) } companion object { fun buildNonNull( receiver: Expression?, methodName: String, argumentList: ArgumentList = ArgumentList.withNoPrototype(), typeArguments: List<Type> = emptyList(), dotPrototype: PsiElement? = null ): MethodCallExpression = build(receiver, methodName, argumentList, typeArguments, false, dotPrototype) fun buildNullable( receiver: Expression?, methodName: String, argumentList: ArgumentList = ArgumentList.withNoPrototype(), typeArguments: List<Type> = emptyList(), dotPrototype: PsiElement? = null ): MethodCallExpression = build(receiver, methodName, argumentList, typeArguments, true, dotPrototype) fun build( receiver: Expression?, methodName: String, argumentList: ArgumentList, typeArguments: List<Type>, isNullable: Boolean, dotPrototype: PsiElement? = null ): MethodCallExpression { val identifier = Identifier.withNoPrototype(methodName, isNullable = false) val methodExpression = if (receiver != null) QualifiedExpression(receiver, identifier, dotPrototype).assignNoPrototype() else identifier return MethodCallExpression(methodExpression, argumentList, typeArguments, isNullable) } } }
apache-2.0
7e7e1dcfe704b065ae44e9e9c0e30c82
40.351852
158
0.637259
5.830287
false
false
false
false
fabmax/kool
kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ksl/lang/KslTexelFetch.kt
1
912
package de.fabmax.kool.modules.ksl.lang import de.fabmax.kool.modules.ksl.generator.KslGenerator import de.fabmax.kool.modules.ksl.model.KslMutatedState class KslTexelFetch<T: KslTypeSampler<KslTypeFloat4>>( val sampler: KslExpression<T>, val coord: KslExpression<*>, val lod: KslScalarExpression<KslTypeInt1>?) : KslVectorExpression<KslTypeFloat4, KslTypeFloat1> { override val expressionType = KslTypeFloat4 override fun collectStateDependencies(): Set<KslMutatedState> { val deps = sampler.collectStateDependencies() + coord.collectStateDependencies() return lod?.let { deps + it.collectStateDependencies() } ?: deps } override fun generateExpression(generator: KslGenerator): String = generator.texelFetch(this) override fun toPseudoCode(): String = "${sampler.toPseudoCode()}.texelFetch(${coord.toPseudoCode()}, lod=${lod?.toPseudoCode() ?: "0"})" }
apache-2.0
81d6b1a5f9488867b463efebd1cd9121
42.428571
140
0.744518
4.089686
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/widget/AvatarStatsWidgetProvider.kt
1
6705
package com.habitrpg.android.habitica.widget import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.content.ComponentName import android.content.Context import android.content.Intent import android.view.View import android.widget.RemoteViews import com.habitrpg.android.habitica.HabiticaBaseApplication import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.helpers.HealthFormatter import com.habitrpg.android.habitica.helpers.NumberAbbreviator import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.models.user.User import com.habitrpg.android.habitica.ui.AvatarView import com.habitrpg.android.habitica.ui.activities.MainActivity import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper import io.reactivex.functions.Consumer class AvatarStatsWidgetProvider : BaseWidgetProvider() { private var appWidgetManager: AppWidgetManager? = null private var showManaBar: Boolean = true override fun layoutResourceId(): Int { return R.layout.widget_avatar_stats } private fun setUp() { if (!hasInjected) { hasInjected = true HabiticaBaseApplication.userComponent?.inject(this) } } override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) { super.onUpdate(context, appWidgetManager, appWidgetIds) this.setUp() this.appWidgetManager = appWidgetManager this.context = context userRepository?.getUser()?.firstElement()?.subscribe(Consumer<User> { this.updateData(it) }, RxErrorHandler.handleEmptyError()) } override fun configureRemoteViews(remoteViews: RemoteViews, widgetId: Int, columns: Int, rows: Int): RemoteViews { if (columns > 3) { remoteViews.setViewVisibility(R.id.avatar_view, View.VISIBLE) } else { remoteViews.setViewVisibility(R.id.avatar_view, View.GONE) } showManaBar = rows > 1 if (rows > 1) { remoteViews.setViewVisibility(R.id.mp_wrapper, View.VISIBLE) remoteViews.setViewVisibility(R.id.detail_info_view, View.VISIBLE) } else { remoteViews.setViewVisibility(R.id.mp_wrapper, View.GONE) remoteViews.setViewVisibility(R.id.detail_info_view, View.GONE) } return remoteViews } private fun updateData(user: User?) { val context = context val appWidgetManager = appWidgetManager val stats = user?.stats if (user == null || stats == null || context == null || appWidgetManager == null) { return } val thisWidget = ComponentName(context, AvatarStatsWidgetProvider::class.java) val allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget) val currentHealth = HealthFormatter.format(stats.hp ?: 0.0) val currentHealthString = HealthFormatter.formatToString(stats.hp ?: 0.0) val healthValueString = currentHealthString + "/" + stats.maxHealth val expValueString = "" + stats.exp?.toInt() + "/" + stats.toNextLevel val mpValueString = "" + stats.mp?.toInt() + "/" + stats.maxMP for (widgetId in allWidgetIds) { var remoteViews = RemoteViews(context.packageName, R.layout.widget_avatar_stats) remoteViews.setTextViewText(R.id.TV_hp_value, healthValueString) remoteViews.setTextViewText(R.id.exp_TV_value, expValueString) remoteViews.setTextViewText(R.id.mp_TV_value, mpValueString) remoteViews.setImageViewBitmap(R.id.ic_hp_header, HabiticaIconsHelper.imageOfHeartDarkBg()) remoteViews.setImageViewBitmap(R.id.ic_exp_header, HabiticaIconsHelper.imageOfExperience()) remoteViews.setImageViewBitmap(R.id.ic_mp_header, HabiticaIconsHelper.imageOfMagic()) remoteViews.setProgressBar(R.id.hp_bar, stats.maxHealth ?: 0, currentHealth.toInt(), false) remoteViews.setProgressBar(R.id.exp_bar, stats.toNextLevel ?: 0, stats.exp?.toInt() ?: 0, false) remoteViews.setProgressBar(R.id.mp_bar, stats.maxMP ?: 0, stats.mp?.toInt() ?: 0, false) remoteViews.setViewVisibility(R.id.mp_wrapper, if (showManaBar && (stats.habitClass == null || (stats.lvl ?: 0) < 10 || user.preferences?.disableClasses == true)) View.GONE else View.VISIBLE) remoteViews.setTextViewText(R.id.gold_tv, NumberAbbreviator.abbreviate(context, stats.gp ?: 0.0)) remoteViews.setTextViewText(R.id.gems_tv, (user.balance * 4).toInt().toString()) val hourGlassCount = user.hourglassCount if (hourGlassCount == 0) { remoteViews.setViewVisibility(R.id.hourglass_icon, View.GONE) remoteViews.setViewVisibility(R.id.hourglasses_tv, View.GONE) } else { remoteViews.setImageViewBitmap(R.id.hourglass_icon, HabiticaIconsHelper.imageOfHourglass()) remoteViews.setViewVisibility(R.id.hourglass_icon, View.VISIBLE) remoteViews.setTextViewText(R.id.hourglasses_tv, hourGlassCount.toString()) remoteViews.setViewVisibility(R.id.hourglasses_tv, View.VISIBLE) } remoteViews.setImageViewBitmap(R.id.gem_icon, HabiticaIconsHelper.imageOfGem()) remoteViews.setImageViewBitmap(R.id.gold_icon, HabiticaIconsHelper.imageOfGold()) remoteViews.setTextViewText(R.id.lvl_tv, context.getString(R.string.user_level, user.stats?.lvl ?: 0)) val avatarView = AvatarView(context, showBackground = true, showMount = true, showPet = true) avatarView.setAvatar(user) val finalRemoteViews = remoteViews avatarView.onAvatarImageReady(Consumer { bitmap -> finalRemoteViews.setImageViewBitmap(R.id.avatar_view, bitmap) appWidgetManager.partiallyUpdateAppWidget(allWidgetIds, finalRemoteViews) }) //If user click on life and xp: open the app val openAppIntent = Intent(context.applicationContext, MainActivity::class.java) val openApp = PendingIntent.getActivity(context, 0, openAppIntent, PendingIntent.FLAG_UPDATE_CURRENT) remoteViews.setOnClickPendingIntent(R.id.widget_main_view, openApp) val options = appWidgetManager.getAppWidgetOptions(widgetId) remoteViews = sizeRemoteViews(context, options, widgetId) appWidgetManager.updateAppWidget(widgetId, remoteViews) } } }
gpl-3.0
49c1e394d1885b7cb6bee0a6513e4907
48.037313
203
0.679493
4.583049
false
false
false
false
kickstarter/android-oss
app/src/test/java/com/kickstarter/viewmodels/PaymentMethodsViewModelTest.kt
1
10568
package com.kickstarter.viewmodels import DeletePaymentSourceMutation import com.kickstarter.KSRobolectricTestCase import com.kickstarter.libs.Environment import com.kickstarter.mock.factories.StoredCardFactory import com.kickstarter.mock.services.MockApolloClientV2 import com.kickstarter.models.Project import com.kickstarter.models.StoredCard import com.kickstarter.services.mutations.SavePaymentMethodData import io.reactivex.Observable import io.reactivex.disposables.CompositeDisposable import io.reactivex.subscribers.TestSubscriber import org.junit.After import org.junit.Test import java.util.Collections class PaymentMethodsViewModelTest : KSRobolectricTestCase() { private lateinit var vm: PaymentMethodsViewModel private val cards = TestSubscriber<List<StoredCard>>() private val dividerIsVisible = TestSubscriber<Boolean>() private val error = TestSubscriber<String>() private val progressBarIsVisible = TestSubscriber<Boolean>() private val showDeleteCardDialog = TestSubscriber<Unit>() private val successDeleting = TestSubscriber<String>() private val presentPaymentSheet = TestSubscriber<String>() private val showError = TestSubscriber<String>() private val successSaving = TestSubscriber<String>() private val compositeDisposable = CompositeDisposable() private fun setUpEnvironment(environment: Environment) { this.vm = PaymentMethodsViewModel.Factory(environment).create(PaymentMethodsViewModel::class.java) compositeDisposable.add(this.vm.outputs.error().subscribe { this.error.onNext(it) }) compositeDisposable.add(this.vm.outputs.cards().subscribe { this.cards.onNext(it) }) compositeDisposable.add(this.vm.outputs.dividerIsVisible().subscribe { this.dividerIsVisible.onNext(it) }) compositeDisposable.add(this.vm.outputs.progressBarIsVisible().subscribe { this.progressBarIsVisible.onNext(it) }) compositeDisposable.add(this.vm.outputs.showDeleteCardDialog().subscribe { this.showDeleteCardDialog.onNext(it) }) compositeDisposable.add(this.vm.outputs.successDeleting().subscribe { this.successDeleting.onNext(it) }) compositeDisposable.add(this.vm.outputs.presentPaymentSheet().subscribe { this.presentPaymentSheet.onNext(it) }) compositeDisposable.add(this.vm.outputs.showError().subscribe { this.showError.onNext(it) }) compositeDisposable.add(this.vm.outputs.successSaving().subscribe { this.successSaving.onNext(it) }) } @After fun cleanUp() { compositeDisposable.clear() } @Test fun testCards() { val card = StoredCardFactory.discoverCard() setUpEnvironment( environment().toBuilder().apolloClientV2(object : MockApolloClientV2() { override fun getStoredCards(): Observable<List<StoredCard>> { return Observable.just(Collections.singletonList(card)) } }).build() ) this.cards.assertValue(Collections.singletonList(card)) } @Test fun testDividerIsVisible_hasCards() { setUpEnvironment(environment()) this.dividerIsVisible.assertValues(true) } @Test fun testDividerIsVisible_noCards() { setUpEnvironment( environment().toBuilder().apolloClientV2(object : MockApolloClientV2() { override fun getStoredCards(): Observable<List<StoredCard>> { return Observable.just(Collections.emptyList()) } }).build() ) this.dividerIsVisible.assertValues(false) } @Test fun testErrorGettingCards() { setUpEnvironment( environment().toBuilder().apolloClientV2(object : MockApolloClientV2() { override fun getStoredCards(): Observable<List<StoredCard>> { return Observable.error(Exception("oops")) } }).build() ) this.cards.assertNoValues() this.error.assertNoValues() } @Test fun testErrorDeletingCard() { setUpEnvironment( environment().toBuilder().apolloClientV2(object : MockApolloClientV2() { override fun deletePaymentSource(paymentSourceId: String): Observable<DeletePaymentSourceMutation.Data> { return Observable.error(Throwable("eek")) } }).build() ) this.vm.inputs.deleteCardClicked("id") this.vm.confirmDeleteCardClicked() this.error.assertValue("eek") } @Test fun testProgressBarIsVisible() { setUpEnvironment(environment()) // getting the cards initially this.progressBarIsVisible.assertValues(false) this.vm.inputs.deleteCardClicked("id") this.vm.inputs.confirmDeleteCardClicked() // make the call to delete and reload the cards this.progressBarIsVisible.assertValues(false, true, false) } @Test fun testShowDeleteCardDialog() { setUpEnvironment(environment()) this.vm.inputs.deleteCardClicked("5555") this.showDeleteCardDialog.assertValueCount(1) } @Test fun testSuccess() { setUpEnvironment(environment()) this.cards.assertValueCount(1) this.vm.inputs.deleteCardClicked("id") this.vm.inputs.confirmDeleteCardClicked() this.successDeleting.assertValueCount(1) this.cards.assertValueCount(2) } @Test fun testPresentPaymentSheetSuccess() { val setupClientId = "seti_1KbABk4VvJ2PtfhKV8E7dvGe_secret_LHjfXxFl9UDucYtsL5a3WtySqjgqf5F" setUpEnvironment( environment().toBuilder().apolloClientV2(object : MockApolloClientV2() { override fun createSetupIntent(project: Project?): Observable<String> { return Observable.just(setupClientId) } }).build() ) this.vm.inputs.newCardButtonClicked() this.presentPaymentSheet.assertValue(setupClientId) this.progressBarIsVisible.assertValues(false, true, false, true, false) this.showError.assertNoValues() } @Test fun testPresentPaymentSheetError() { val errorString = "Something went wrong" setUpEnvironment( environment().toBuilder().apolloClientV2(object : MockApolloClientV2() { override fun createSetupIntent(project: Project?): Observable<String> { return Observable.error(Exception(errorString)) } }).build() ) this.vm.inputs.newCardButtonClicked() this.presentPaymentSheet.assertNoValues() this.progressBarIsVisible.assertValues(false, true, false, true, false) this.showError.assertValue(errorString) } @Test fun testSavePaymentMethodSuccess() { val setupClientId = "seti_1KbABk4VvJ2PtfhKV8E7dvGe_secret_LHjfXxFl9UDucYtsL5a3WtySqjgqf5F" val card = StoredCardFactory.visa() val cardsList = listOf(StoredCardFactory.discoverCard()) val cardsListUpdated = listOf(StoredCardFactory.discoverCard(), card) var numberOfCalls = 1 setUpEnvironment( environment().toBuilder().apolloClientV2(object : MockApolloClientV2() { override fun createSetupIntent(project: Project?): Observable<String> { return Observable.just(setupClientId) } override fun savePaymentMethod(savePaymentMethodData: SavePaymentMethodData): Observable<StoredCard> { return Observable.just(card) } override fun getStoredCards(): Observable<List<StoredCard>> { if (numberOfCalls == 1) { numberOfCalls++ return Observable.just(cardsList) } else { return Observable.just(cardsListUpdated) } } }).build() ) // - Button clicked this.vm.inputs.newCardButtonClicked() this.presentPaymentSheet.assertValue(setupClientId) this.progressBarIsVisible.assertValues(false, true, false, true, false) this.showError.assertNoValues() // - User added correct payment method to paymentSheet this.vm.inputs.savePaymentOption() this.cards.assertValueCount(2) this.cards.assertValues(cardsList, cardsListUpdated) this.progressBarIsVisible.assertValues(false, true, false, true, false, true, false, true, false) this.showError.assertNoValues() this.successSaving.assertValue(card.toString()) } @Test fun testSavePaymentMethodError() { val setupClientId = "seti_1KbABk4VvJ2PtfhKV8E7dvGe_secret_LHjfXxFl9UDucYtsL5a3WtySqjgqf5F" val cardsList = listOf(StoredCardFactory.discoverCard()) var numberOfCalls = 1 val errorString = "Something went wrong" setUpEnvironment( environment().toBuilder().apolloClientV2(object : MockApolloClientV2() { override fun createSetupIntent(project: Project?): Observable<String> { return Observable.just(setupClientId) } override fun savePaymentMethod(savePaymentMethodData: SavePaymentMethodData): Observable<StoredCard> { return Observable.error(Exception(errorString)) } override fun getStoredCards(): Observable<List<StoredCard>> { return if (numberOfCalls == 1) { numberOfCalls++ Observable.just(cardsList) } else { Observable.error(Exception(errorString)) } } }).build() ) // - Button clicked this.vm.inputs.newCardButtonClicked() this.presentPaymentSheet.assertValue(setupClientId) this.progressBarIsVisible.assertValues(false, true, false, true, false) this.showError.assertNoValues() // - User added correct payment method using paymentSheet, but some error happen during the process this.vm.inputs.savePaymentOption() this.cards.assertValueCount(1) this.cards.assertValues(cardsList) this.progressBarIsVisible.assertValues(false, true, false, true, false, true, false, true, false) this.showError.assertValues(errorString) this.successSaving.assertNoValues() } }
apache-2.0
4f888e34d140f3e3bd6d2a5c693fb2e3
37.710623
122
0.657646
5.022814
false
true
false
false
romannurik/muzei
main/src/main/java/com/google/android/apps/muzei/util/AnimatedMuzeiLogoFragment.kt
1
2869
/* * Copyright 2014 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.util import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.os.Bundle import android.util.TypedValue import android.view.View import android.view.animation.OvershootInterpolator import androidx.fragment.app.Fragment import net.nurik.roman.muzei.R import net.nurik.roman.muzei.databinding.AnimatedLogoFragmentBinding class AnimatedMuzeiLogoFragment : Fragment(R.layout.animated_logo_fragment) { private var binding: AnimatedLogoFragmentBinding by autoCleared() private val initialLogoOffset: Float by lazy { TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16f, resources.displayMetrics) } var onFillStarted: () -> Unit = {} override fun onViewCreated(view: View, savedInstanceState: Bundle?) { binding = AnimatedLogoFragmentBinding.bind(view) binding.animatedLogo.onStateChange = { state -> if (state == AnimatedMuzeiLogoView.STATE_FILL_STARTED) { binding.logoSubtitle.apply { alpha = 0f visibility = View.VISIBLE translationY = (-height).toFloat() } // Bug in older versions where set.setInterpolator didn't work val interpolator = OvershootInterpolator() val a1 = ObjectAnimator.ofFloat(binding.animatedLogo, View.TRANSLATION_Y, 0f) val a2 = ObjectAnimator.ofFloat(binding.logoSubtitle, View.TRANSLATION_Y, 0f) val a3 = ObjectAnimator.ofFloat(binding.logoSubtitle, View.ALPHA, 1f) a1.interpolator = interpolator a2.interpolator = interpolator AnimatorSet().apply { setDuration(500).playTogether(a1, a2, a3) start() } onFillStarted.invoke() } } if (savedInstanceState == null) { reset() } } fun start() { binding.animatedLogo.start() } private fun reset() { binding.animatedLogo.reset() binding.animatedLogo.translationY = initialLogoOffset binding.logoSubtitle.visibility = View.INVISIBLE } }
apache-2.0
94544551137cdffea7b323de7a5f9268
35.316456
93
0.652144
4.75
false
false
false
false
jagguli/intellij-community
plugins/settings-repository/src/git/pull.kt
2
15117
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.settingsRepository.git import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.SmartList import com.intellij.util.containers.hash.LinkedHashMap import org.eclipse.jgit.api.MergeCommand.FastForwardMode import org.eclipse.jgit.api.MergeResult import org.eclipse.jgit.api.MergeResult.MergeStatus import org.eclipse.jgit.api.errors.CheckoutConflictException import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException import org.eclipse.jgit.api.errors.JGitInternalException import org.eclipse.jgit.api.errors.NoHeadException import org.eclipse.jgit.diff.RawText import org.eclipse.jgit.diff.Sequence import org.eclipse.jgit.dircache.DirCacheCheckout import org.eclipse.jgit.internal.JGitText import org.eclipse.jgit.lib.* import org.eclipse.jgit.merge.MergeMessageFormatter import org.eclipse.jgit.merge.MergeStrategy import org.eclipse.jgit.merge.ResolveMerger import org.eclipse.jgit.merge.SquashMessageFormatter import org.eclipse.jgit.revwalk.RevWalk import org.eclipse.jgit.revwalk.RevWalkUtils import org.eclipse.jgit.transport.RemoteConfig import org.eclipse.jgit.treewalk.FileTreeIterator import org.jetbrains.settingsRepository.* import java.io.IOException import java.text.MessageFormat open class Pull(val manager: GitRepositoryManager, val indicator: ProgressIndicator?, val commitMessageFormatter: CommitMessageFormatter = IdeaCommitMessageFormatter()) { val repository = manager.repository // we must use the same StoredConfig instance during the operation val config = repository.config val remoteConfig = RemoteConfig(config, Constants.DEFAULT_REMOTE_NAME) fun pull(mergeStrategy: MergeStrategy = MergeStrategy.RECURSIVE, commitMessage: String? = null, prefetchedRefToMerge: Ref? = null): UpdateResult? { indicator?.checkCanceled() LOG.debug("Pull") val state = repository.fixAndGetState() if (!state.canCheckout()) { LOG.error("Cannot pull, repository in state ${state.description}") return null } var refToMerge = prefetchedRefToMerge ?: fetch() ?: return null val mergeResult = merge(refToMerge, mergeStrategy, commitMessage = commitMessage) val mergeStatus = mergeResult.mergeStatus if (LOG.isDebugEnabled) { LOG.debug(mergeStatus.toString()) } if (mergeStatus == MergeStatus.CONFLICTING) { return resolveConflicts(mergeResult, repository) } else if (!mergeStatus.isSuccessful) { throw IllegalStateException(mergeResult.toString()) } else { return mergeResult.result } } fun fetch(prevRefUpdateResult: RefUpdate.Result? = null): Ref? { indicator?.checkCanceled() val fetchResult = repository.fetch(remoteConfig, manager.credentialsProvider, indicator.asProgressMonitor()) ?: return null if (LOG.isDebugEnabled) { printMessages(fetchResult) for (refUpdate in fetchResult.trackingRefUpdates) { LOG.debug(refUpdate.toString()) } } indicator?.checkCanceled() var hasChanges = false for (fetchRefSpec in remoteConfig.fetchRefSpecs) { val refUpdate = fetchResult.getTrackingRefUpdate(fetchRefSpec.destination) if (refUpdate == null) { LOG.debug("No ref update for $fetchRefSpec") continue } val refUpdateResult = refUpdate.result // we can have more than one fetch ref spec, but currently we don't worry about it if (refUpdateResult == RefUpdate.Result.LOCK_FAILURE || refUpdateResult == RefUpdate.Result.IO_FAILURE) { if (prevRefUpdateResult == refUpdateResult) { throw IOException("Ref update result ${refUpdateResult.name()}, we have already tried to fetch again, but no luck") } LOG.warn("Ref update result ${refUpdateResult.name()}, trying again after 500 ms") Thread.sleep(500) return fetch(refUpdateResult) } if (!(refUpdateResult == RefUpdate.Result.FAST_FORWARD || refUpdateResult == RefUpdate.Result.NEW || refUpdateResult == RefUpdate.Result.FORCED)) { throw UnsupportedOperationException("Unsupported ref update result") } if (!hasChanges) { hasChanges = refUpdateResult != RefUpdate.Result.NO_CHANGE } } if (!hasChanges) { LOG.debug("No remote changes") return null } return fetchResult.getAdvertisedRef(config.getRemoteBranchFullName()) ?: throw IllegalStateException("Could not get advertised ref") } fun merge(unpeeledRef: Ref, mergeStrategy: MergeStrategy = MergeStrategy.RECURSIVE, commit: Boolean = true, fastForwardMode: FastForwardMode = FastForwardMode.FF, squash: Boolean = false, forceMerge: Boolean = false, commitMessage: String? = null): MergeResultEx { indicator?.checkCanceled() val head = repository.getRef(Constants.HEAD) ?: throw NoHeadException(JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported) // handle annotated tags val ref = repository.peel(unpeeledRef) val objectId = ref.peeledObjectId ?: ref.objectId // Check for FAST_FORWARD, ALREADY_UP_TO_DATE val revWalk = RevWalk(repository) var dirCacheCheckout: DirCacheCheckout? = null try { val srcCommit = revWalk.lookupCommit(objectId) val headId = head.objectId if (headId == null) { revWalk.parseHeaders(srcCommit) dirCacheCheckout = DirCacheCheckout(repository, repository.lockDirCache(), srcCommit.tree) dirCacheCheckout.setFailOnConflict(true) dirCacheCheckout.checkout() val refUpdate = repository.updateRef(head.target.name) refUpdate.setNewObjectId(objectId) refUpdate.setExpectedOldObjectId(null) refUpdate.setRefLogMessage("initial pull", false) if (refUpdate.update() != RefUpdate.Result.NEW) { throw NoHeadException(JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported) } return MergeResultEx(MergeStatus.FAST_FORWARD, arrayOf<ObjectId?>(null, srcCommit), ImmutableUpdateResult(dirCacheCheckout.updated.keySet(), dirCacheCheckout.removed)) } val refLogMessage = StringBuilder("merge ") refLogMessage.append(ref.name) val headCommit = revWalk.lookupCommit(headId) if (!forceMerge && revWalk.isMergedInto(srcCommit, headCommit)) { return MergeResultEx(MergeStatus.ALREADY_UP_TO_DATE, arrayOf<ObjectId?>(headCommit, srcCommit), EMPTY_UPDATE_RESULT) //return MergeResult(headCommit, srcCommit, array(headCommit, srcCommit), MergeStatus.ALREADY_UP_TO_DATE, mergeStrategy, null) } else if (!forceMerge && fastForwardMode != FastForwardMode.NO_FF && revWalk.isMergedInto(headCommit, srcCommit)) { // FAST_FORWARD detected: skip doing a real merge but only update HEAD refLogMessage.append(": ").append(MergeStatus.FAST_FORWARD) dirCacheCheckout = DirCacheCheckout(repository, headCommit.tree, repository.lockDirCache(), srcCommit.tree) dirCacheCheckout.setFailOnConflict(true) dirCacheCheckout.checkout() val mergeStatus: MergeStatus if (squash) { mergeStatus = MergeStatus.FAST_FORWARD_SQUASHED val squashedCommits = RevWalkUtils.find(revWalk, srcCommit, headCommit) repository.writeSquashCommitMsg(SquashMessageFormatter().format(squashedCommits, head)) } else { updateHead(refLogMessage, srcCommit, headId, repository) mergeStatus = MergeStatus.FAST_FORWARD } return MergeResultEx(mergeStatus, arrayOf<ObjectId?>(headCommit, srcCommit), ImmutableUpdateResult(dirCacheCheckout.updated.keySet(), dirCacheCheckout.removed)) } else { if (fastForwardMode == FastForwardMode.FF_ONLY) { return MergeResultEx(MergeStatus.ABORTED, arrayOf<ObjectId?>(headCommit, srcCommit), EMPTY_UPDATE_RESULT) } val mergeMessage: String if (squash) { mergeMessage = "" repository.writeSquashCommitMsg(SquashMessageFormatter().format(RevWalkUtils.find(revWalk, srcCommit, headCommit), head)) } else { mergeMessage = commitMessageFormatter.mergeMessage(listOf(ref), head) repository.writeMergeCommitMsg(mergeMessage) repository.writeMergeHeads(listOf(ref.objectId)) } val merger = mergeStrategy.newMerger(repository) val noProblems: Boolean var lowLevelResults: Map<String, org.eclipse.jgit.merge.MergeResult<out Sequence>>? = null var failingPaths: Map<String, ResolveMerger.MergeFailureReason>? = null var unmergedPaths: List<String>? = null if (merger is ResolveMerger) { merger.commitNames = arrayOf("BASE", "HEAD", ref.name) merger.setWorkingTreeIterator(FileTreeIterator(repository)) noProblems = merger.merge(headCommit, srcCommit) lowLevelResults = merger.mergeResults failingPaths = merger.failingPaths unmergedPaths = merger.unmergedPaths } else { noProblems = merger.merge(headCommit, srcCommit) } refLogMessage.append(": Merge made by ") refLogMessage.append(if (revWalk.isMergedInto(headCommit, srcCommit)) "recursive" else mergeStrategy.name) refLogMessage.append('.') var result = if (merger is ResolveMerger) ImmutableUpdateResult(merger.toBeCheckedOut.keySet(), merger.toBeDeleted) else null if (noProblems) { // ResolveMerger does checkout if (merger !is ResolveMerger) { dirCacheCheckout = DirCacheCheckout(repository, headCommit.tree, repository.lockDirCache(), merger.resultTreeId) dirCacheCheckout.setFailOnConflict(true) dirCacheCheckout.checkout() result = ImmutableUpdateResult(dirCacheCheckout.updated.keySet(), dirCacheCheckout.removed) } var mergeStatus: MergeResult.MergeStatus? = null if (!commit && squash) { mergeStatus = MergeResult.MergeStatus.MERGED_SQUASHED_NOT_COMMITTED } if (!commit && !squash) { mergeStatus = MergeResult.MergeStatus.MERGED_NOT_COMMITTED } if (commit && !squash) { repository.commit(commitMessage, refLogMessage.toString()).id mergeStatus = MergeResult.MergeStatus.MERGED } if (commit && squash) { mergeStatus = MergeResult.MergeStatus.MERGED_SQUASHED } return MergeResultEx(mergeStatus!!, arrayOf(headCommit.id, srcCommit.id), result!!) } else if (failingPaths == null) { repository.writeMergeCommitMsg(MergeMessageFormatter().formatWithConflicts(mergeMessage, unmergedPaths)) return MergeResultEx(MergeResult.MergeStatus.CONFLICTING, arrayOf(headCommit.id, srcCommit.id), result!!, lowLevelResults) } else { repository.writeMergeCommitMsg(null) repository.writeMergeHeads(null) return MergeResultEx(MergeResult.MergeStatus.FAILED, arrayOf(headCommit.id, srcCommit.id), result!!, lowLevelResults) } } } catch (e: org.eclipse.jgit.errors.CheckoutConflictException) { throw CheckoutConflictException(dirCacheCheckout?.conflicts ?: listOf(), e) } finally { revWalk.close() } } } class MergeResultEx(val mergeStatus: MergeStatus, val mergedCommits: Array<ObjectId?>, val result: ImmutableUpdateResult, val conflicts: Map<String, org.eclipse.jgit.merge.MergeResult<out Sequence>>? = null) private fun updateHead(refLogMessage: StringBuilder, newHeadId: ObjectId, oldHeadID: ObjectId, repository: Repository) { val refUpdate = repository.updateRef(Constants.HEAD) refUpdate.setNewObjectId(newHeadId) refUpdate.setRefLogMessage(refLogMessage.toString(), false) refUpdate.setExpectedOldObjectId(oldHeadID) val rc = refUpdate.update() when (rc) { RefUpdate.Result.NEW, RefUpdate.Result.FAST_FORWARD -> return RefUpdate.Result.REJECTED, RefUpdate.Result.LOCK_FAILURE -> throw ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, refUpdate.ref, rc) else -> throw JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed, Constants.HEAD, newHeadId.toString(), rc)) } } private fun resolveConflicts(mergeResult: MergeResultEx, repository: Repository): MutableUpdateResult { assert(mergeResult.mergedCommits.size() == 2) val conflicts = mergeResult.conflicts!! val mergeProvider = JGitMergeProvider(repository, conflicts, { path, index -> val rawText = get(path)!!.getSequences().get(index) as RawText // RawText.EMPTY_TEXT if content is null - deleted if (rawText == RawText.EMPTY_TEXT) null else rawText.content }) val mergedFiles = resolveConflicts(mergeProvider, conflictsToVirtualFiles(conflicts), repository) return mergeResult.result.toMutable().addChanged(mergedFiles) } private fun resolveConflicts(mergeProvider: JGitMergeProvider<out Any>, unresolvedFiles: MutableList<VirtualFile>, repository: Repository): List<String> { val mergedFiles = SmartList<String>() while (true) { val resolvedFiles = resolveConflicts(unresolvedFiles, mergeProvider) for (file in resolvedFiles) { mergedFiles.add(file.path) } if (resolvedFiles.size() == unresolvedFiles.size()) { break } else { unresolvedFiles.removeAll(mergedFiles) } } // merge commit template will be used, so, we don't have to specify commit message explicitly repository.commit() return mergedFiles } internal fun Repository.fixAndGetState(): RepositoryState { var state = repositoryState if (state == RepositoryState.MERGING) { resolveUnmergedConflicts(this) // compute new state state = repositoryState } return state } internal fun resolveUnmergedConflicts(repository: Repository) { val conflicts = LinkedHashMap<String, Array<ByteArray?>>() repository.newObjectReader().use { reader -> val dirCache = repository.readDirCache() for (i in 0..(dirCache.entryCount - 1)) { val entry = dirCache.getEntry(i) if (!entry.isMerged) { conflicts.getOrPut(entry.pathString, { arrayOfNulls<ByteArray>(3) })[entry.stage - 1] = reader.open(entry.objectId, Constants.OBJ_BLOB).cachedBytes } } } resolveConflicts(JGitMergeProvider(repository, conflicts, { path, index -> get(path)!!.get(index) }), conflictsToVirtualFiles(conflicts), repository) }
apache-2.0
006250c4db7c29e89be4ae04fb1efb87
42.442529
207
0.71628
4.693263
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractClass/ui/KotlinExtractSuperDialogBase.kt
1
7317
// 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.refactoring.introduce.extractClass.ui import com.intellij.psi.PsiComment import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.classMembers.MemberInfoChange import com.intellij.refactoring.extractSuperclass.JavaExtractSuperBaseDialog import com.intellij.refactoring.util.DocCommentPolicy import com.intellij.refactoring.util.RefactoringMessageUtil import com.intellij.ui.components.JBLabel import com.intellij.util.ui.FormBuilder import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.core.unquote import org.jetbrains.kotlin.idea.core.util.onTextChange import org.jetbrains.kotlin.idea.refactoring.introduce.extractClass.ExtractSuperInfo import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberInfo import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberSelectionPanel import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinUsesAndInterfacesDependencyMemberInfoModel import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.psiUtil.isIdentifier import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded import java.awt.BorderLayout import javax.swing.* abstract class KotlinExtractSuperDialogBase( protected val originalClass: KtClassOrObject, protected val targetParent: PsiElement, private val conflictChecker: (KotlinExtractSuperDialogBase) -> Boolean, private val isExtractInterface: Boolean, refactoringName: String, private val refactoring: (ExtractSuperInfo) -> Unit ) : JavaExtractSuperBaseDialog(originalClass.project, originalClass.toLightClass()!!, emptyList(), refactoringName) { private var initComplete: Boolean = false private lateinit var memberInfoModel: MemberInfoModelBase val selectedMembers: List<KotlinMemberInfo> get() = memberInfoModel.memberInfos.filter { it.isChecked } private val fileNameField = JTextField() open class MemberInfoModelBase( originalClass: KtClassOrObject, val memberInfos: List<KotlinMemberInfo>, interfaceContainmentVerifier: (KtNamedDeclaration) -> Boolean ) : KotlinUsesAndInterfacesDependencyMemberInfoModel<KtNamedDeclaration, KotlinMemberInfo>( originalClass, null, false, interfaceContainmentVerifier ) { override fun isMemberEnabled(member: KotlinMemberInfo): Boolean { val declaration = member.member ?: return false return !declaration.hasModifier(KtTokens.CONST_KEYWORD) } override fun isAbstractEnabled(memberInfo: KotlinMemberInfo): Boolean { val member = memberInfo.member return !(member.hasModifier(KtTokens.INLINE_KEYWORD) || member.hasModifier(KtTokens.EXTERNAL_KEYWORD) || member.hasModifier(KtTokens.LATEINIT_KEYWORD)) } override fun isFixedAbstract(memberInfo: KotlinMemberInfo?) = true } val selectedTargetParent: PsiElement get() = if (targetParent is PsiDirectory) targetDirectory else targetParent val targetFileName: String get() = fileNameField.text private fun resetFileNameField() { if (!initComplete) return fileNameField.text = "$extractedSuperName.${KotlinFileType.EXTENSION}" } protected abstract fun createMemberInfoModel(): MemberInfoModelBase override fun getDocCommentPanelName() = KotlinBundle.message("name.kdoc.for.abstracts") override fun checkConflicts() = conflictChecker(this) override fun createActionComponent() = Box.createHorizontalBox()!! override fun createExtractedSuperNameField(): JTextField { return super.createExtractedSuperNameField().apply { onTextChange { resetFileNameField() } } } override fun createDestinationRootPanel(): JPanel? { if (targetParent !is PsiDirectory) return null val targetDirectoryPanel = super.createDestinationRootPanel() val targetFileNamePanel = JPanel(BorderLayout()).apply { border = BorderFactory.createEmptyBorder(10, 0, 0, 0) val label = JBLabel(KotlinBundle.message("label.text.target.file.name")) add(label, BorderLayout.NORTH) label.labelFor = fileNameField add(fileNameField, BorderLayout.CENTER) } val formBuilder = FormBuilder.createFormBuilder() if (targetDirectoryPanel != null) { formBuilder.addComponent(targetDirectoryPanel) } return formBuilder.addComponent(targetFileNamePanel).panel } override fun createNorthPanel(): JComponent? { return super.createNorthPanel().apply { if (targetParent !is PsiDirectory) { myPackageNameLabel.parent.remove(myPackageNameLabel) myPackageNameField.parent.remove(myPackageNameField) } } } override fun createCenterPanel(): JComponent? { memberInfoModel = createMemberInfoModel().apply { memberInfoChanged(MemberInfoChange(memberInfos)) } return JPanel(BorderLayout()).apply { val memberSelectionPanel = KotlinMemberSelectionPanel( RefactoringBundle.message(if (isExtractInterface) "members.to.form.interface" else "members.to.form.superclass"), memberInfoModel.memberInfos, RefactoringBundle.message("make.abstract") ) memberSelectionPanel.table.memberInfoModel = memberInfoModel memberSelectionPanel.table.addMemberInfoChangeListener(memberInfoModel) add(memberSelectionPanel, BorderLayout.CENTER) add(myDocCommentPanel, BorderLayout.EAST) } } override fun init() { super.init() initComplete = true resetFileNameField() } override fun preparePackage() { if (targetParent is PsiDirectory) super.preparePackage() } override fun isExtractSuperclass() = true override fun validateName(name: String): String? { return when { !name.quoteIfNeeded().isIdentifier() -> RefactoringMessageUtil.getIncorrectIdentifierMessage(name) name.unquote() == mySourceClass.name -> KotlinBundle.message("error.text.different.name.expected") else -> null } } override fun createProcessor() = null override fun executeRefactoring() { val extractInfo = ExtractSuperInfo( mySourceClass.unwrapped as KtClassOrObject, selectedMembers, if (targetParent is PsiDirectory) targetDirectory else targetParent, targetFileName, extractedSuperName.quoteIfNeeded(), isExtractInterface, DocCommentPolicy<PsiComment>(docCommentPolicy) ) refactoring(extractInfo) } }
apache-2.0
93be38a04b9c2c93f57c74fa87c56e57
38.989071
158
0.721471
5.36437
false
false
false
false
vovagrechka/fucking-everything
hot-reloadable-idea-piece-of-shit/src/main/java/Command_PhiShowStack.kt
1
10142
@file:Suppress("Unused") package vgrechka.idea.hripos import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.type.TypeFactory import vgrechka.* object MapPhizdetsStackToolIO { @Ser class Input(val projectName: String, val stack: List<FileLine>) @Ser sealed class Output(dontDeleteMe: Unit = Unit) { @Ser class Candy(val mappedStack: List<FileLine?>) : Output() @Ser class Poop(val error: String) : Output() } } fun runMapPhizdetsStackTool(con: Mumbler, stackItems: MutableList<FileLine>): MapPhizdetsStackToolIO.Output.Candy? { val toolInput = MapPhizdetsStackToolIO.Input("aps-back-php", stackItems) val om = ObjectMapper() om.typeFactory = TypeFactory .defaultInstance() .withClassLoader(object{}.javaClass.classLoader) om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL) val inputJSON = om.writeValueAsString(toolInput) // mumble(inputJSON) con.scrollToEnd() val res = OpsPile.runProcessAndWait( listOf("cmd.exe", "/c", "e:\\fegh\\_run.cmd phizdets.MapPhizdetsStackTool"), inheritIO = false, input = inputJSON) if (res.exitValue != 0) { run { // Dump output if (res.stderr.isNotBlank()) { con.barkNoln(res.stderr) if (!res.stderr.endsWith("\n")) con.bark("") } con.mumbleNoln(res.stdout) if (!res.stdout.endsWith("\n")) con.mumble("") } FuckingUtils.error("MapPhizdetsStackTool returned ${res.exitValue}, meaning 'fuck you'") return null } val out = om.readValue(res.stdout, MapPhizdetsStackToolIO.Output::class.java) return when (out) { is MapPhizdetsStackToolIO.Output.Candy -> { out } is MapPhizdetsStackToolIO.Output.Poop -> { con.bark(out.error) null } } } class Command_PhiShowStack_Params { lateinit var projectName: String lateinit var stack: List<Map<String, Any?>> } @Ser class Command_PhiShowStack : Servant<Command_PhiShowStack_Params> { override lateinit var params: Command_PhiShowStack_Params override fun serve(): Any { val spew = StringBuilder() for (item in params.stack.reversed().drop(1)) { val file = item["file"].toString() val line = item["line"].toString().toInt() spew += "$file:$line\n" } return Command_PhiMakeSenseOfPHPSpew().also { it.params = Command_PhiMakeSenseOfPHPSpew_Params().also { it.spew = spew.toString() } }.serve() } private fun oldShit(con: Mumbler) { val stackItems = mutableListOf<FileLine>() for (item in params.stack.reversed().drop(1)) { val file = item["file"].toString() val line = item["line"].toString().toInt() for (shit in APSBackPHPDevTools.interestingFiles) { if (file.contains(shit.shortName)) { stackItems += FileLine(shit.shortName, line) } } } val toolOut = runMapPhizdetsStackTool(con, stackItems) ?: return for ((i, item) in stackItems.withIndex()) { APSBackPHPDevTools.link(con, item) APSBackPHPDevTools.interestingFiles.find {it.shortName == item.file}?.let { con.mumbleNoln(" (") con.link("--1", it.fullPath + "--1", item.line) con.mumbleNoln(")") } con.mumbleNoln(" --> ") val mappedItem = toolOut.mappedStack[i] if (mappedItem == null) { con.mumbleNoln("[Obscure]") } else { APSBackPHPDevTools.link(con, mappedItem) } con.mumble("") } con.mumble("OK") } } object Command_PhiShowStackTest { @JvmStatic fun main(args: Array<String>) { HTTPPile.postJSON_bitchUnlessOK("http://localhost:12312?proc=PhiShowStack", json) } val json = """ { "projectName": "fegh", "stack": [ { "function": "{main}", "file": "\/media\/sf_phizdetsc-php\/try-shit--aps-back.php", "line": 0, "params": [] }, { "file": "\/media\/sf_phizdetsc-php\/try-shit--aps-back.php", "line": 6, "params": [], "include_filename": "\/media\/sf_phizdetsc-php\/fuck-around--aps-back.php" }, { "function": "phiExpressionStatement", "file": "\/media\/sf_phizdetsc-php\/fuck-around--aps-back.php", "line": 8286, "params": { "expr": "???" } }, { "function": "evaluate", "type": "dynamic", "class": "PhiBinaryOperation", "file": "\/media\/sf_phizdetsc-php\/phi-engine.php", "line": 1857, "params": [] }, { "function": "evaluate", "type": "dynamic", "class": "PhiInvocation", "file": "\/media\/sf_phizdetsc-php\/phi-engine.php", "line": 1472, "params": [] }, { "function": "invoke", "type": "dynamic", "class": "PhiFunction", "file": "\/media\/sf_phizdetsc-php\/phi-engine.php", "line": 2231, "params": { "receiver": "???", "args": "???" } }, { "function": "{closure:\/media\/sf_phizdetsc-php\/fuck-around--aps-back.php:4-8285}", "file": "\/media\/sf_phizdetsc-php\/phi-engine.php", "line": 320, "params": [] }, { "function": "phiExpressionStatement", "file": "\/media\/sf_phizdetsc-php\/fuck-around--aps-back.php", "line": 8283, "params": { "expr": "???" } }, { "function": "evaluate", "type": "dynamic", "class": "PhiInvocation", "file": "\/media\/sf_phizdetsc-php\/phi-engine.php", "line": 1857, "params": [] }, { "function": "invoke", "type": "dynamic", "class": "PhiFunction", "file": "\/media\/sf_phizdetsc-php\/phi-engine.php", "line": 2231, "params": { "receiver": "???", "args": "???" } }, { "function": "{closure:\/media\/sf_phizdetsc-php\/fuck-around--aps-back.php:4130-4132}", "file": "\/media\/sf_phizdetsc-php\/phi-engine.php", "line": 320, "params": [] }, { "function": "phiExpressionStatement", "file": "\/media\/sf_phizdetsc-php\/fuck-around--aps-back.php", "line": 4131, "params": { "expr": "???" } }, { "function": "evaluate", "type": "dynamic", "class": "PhiInvocation", "file": "\/media\/sf_phizdetsc-php\/phi-engine.php", "line": 1857, "params": [] }, { "function": "invoke", "type": "dynamic", "class": "PhiFunction", "file": "\/media\/sf_phizdetsc-php\/phi-engine.php", "line": 2231, "params": { "receiver": "???", "args": "???" } }, { "function": "{closure:\/media\/sf_phizdetsc-php\/fuck-around--aps-back.php:42-78}", "file": "\/media\/sf_phizdetsc-php\/phi-engine.php", "line": 320, "params": [] }, { "function": "phiVars", "file": "\/media\/sf_phizdetsc-php\/fuck-around--aps-back.php", "line": 45, "params": { "debugTag": "???", "nameValuePairs": "???" } }, { "function": "evaluate", "type": "dynamic", "class": "PhiInvocation", "file": "\/media\/sf_phizdetsc-php\/phi-engine.php", "line": 2388, "params": [] }, { "function": "invoke", "type": "dynamic", "class": "PhiFunction", "file": "\/media\/sf_phizdetsc-php\/phi-engine.php", "line": 2231, "params": { "receiver": "???", "args": "???" } }, { "function": "{closure:\/media\/sf_phizdetsc-php\/fuck-around--aps-back.php:4091-4093}", "file": "\/media\/sf_phizdetsc-php\/phi-engine.php", "line": 320, "params": [] }, { "function": "phiEvaluate", "file": "\/media\/sf_phizdetsc-php\/fuck-around--aps-back.php", "line": 4092, "params": { "expr": "???" } }, { "function": "evaluate", "type": "dynamic", "class": "PhiInvocation", "file": "\/media\/sf_phizdetsc-php\/phi-engine.php", "line": 1917, "params": [] }, { "function": "evaluate", "type": "dynamic", "class": "PhiInvocation", "file": "\/media\/sf_phizdetsc-php\/phi-engine.php", "line": 2229, "params": [] }, { "function": "evaluate", "type": "dynamic", "class": "PhiInvocation", "file": "\/media\/sf_phizdetsc-php\/phi-engine.php", "line": 2194, "params": [] }, { "function": "phiSendStack", "file": "xdebug:\/\/debug-eval", "line": 1, "params": [] } ] } """ }
apache-2.0
50e515fa67c9947f1230be0589e71797
29.456456
116
0.463518
3.960172
false
false
false
false
jwren/intellij-community
platform/lang-impl/src/com/intellij/ide/bookmark/actions/NodeDeleteAction.kt
2
1249
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.bookmark.actions import com.intellij.CommonBundle.messagePointer import com.intellij.ide.bookmark.BookmarksListProviderService import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction internal class NodeDeleteAction : DumbAwareAction(messagePointer("button.delete")) { override fun update(event: AnActionEvent) { event.presentation.isEnabledAndVisible = false val project = event.project ?: return val nodes = event.bookmarksView?.selectedNodes ?: return val provider = BookmarksListProviderService.findProvider(project) { it.canDelete(nodes) } ?: return provider.deleteActionText?.let { event.presentation.text = it } event.presentation.isEnabledAndVisible = true } override fun actionPerformed(event: AnActionEvent) { val project = event.project ?: return val view = event.bookmarksView ?: return val nodes = view.selectedNodes ?: return BookmarksListProviderService.findProvider(project) { it.canDelete(nodes) }?.performDelete(nodes, view.tree) } init { isEnabledInModalContext = true } }
apache-2.0
6937a0a98aca94b6d3a42e73b9c61f67
40.633333
120
0.773419
4.643123
false
false
false
false
ZhangQinglian/dcapp
src/main/kotlin/com/zqlite/android/diycode/device/view/notification/NotificationFragment.kt
1
9054
/* * Copyright 2017 zhangqinglian * * 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.zqlite.android.diycode.device.view.notification import android.graphics.Color import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.text.Html import android.text.Spannable import android.text.SpannableStringBuilder import android.text.Spanned import android.text.style.ForegroundColorSpan import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.zqlite.android.dclib.entiry.Notification import com.zqlite.android.diycode.R import com.zqlite.android.diycode.device.utils.CalendarUtils import com.zqlite.android.diycode.device.utils.NetworkUtils import com.zqlite.android.diycode.device.utils.Route import com.zqlite.android.diycode.device.utils.TokenStore import com.zqlite.android.diycode.device.view.BaseFragment import de.hdodenhof.circleimageview.CircleImageView import kotlinx.android.synthetic.main.fragment_notification.* /** * Created by scott on 2017/8/21. */ class NotificationFragment :BaseFragment(),NotificationContract.View { private var mPresenter : NotificationContract.Presenter?=null private val mAdapter : NotificationAdapter = NotificationAdapter() override fun onResume() { super.onResume() if(!TokenStore.shouldLogin(context)){ mPresenter!!.loadNotification() } } override fun setPresenter(presenter: NotificationContract.Presenter) { mPresenter = presenter } override fun getLayoutId(): Int { return R.layout.fragment_notification } override fun initView() { val linearLayoutManager = LinearLayoutManager(context,LinearLayoutManager.VERTICAL,false) notification_list.layoutManager = linearLayoutManager notification_list.adapter = mAdapter notification_fresh.setOnRefreshListener({ mPresenter!!.loadNotification() }) notification_fresh.setColorSchemeColors(resources.getColor(R.color.colorPrimary)) } override fun initData() { mPresenter!!.loadNotification() } override fun updateNotification(datas: List<Notification>) { notification_fresh.isRefreshing = false mAdapter.updateNotification(datas) } private inner class NotificationAdapter : RecyclerView.Adapter<NotificationItemHolder>(){ private val notifications = mutableListOf<Notification>() fun updateNotification(datas: List<Notification>){ notifications.clear() notifications.addAll(datas) notifyDataSetChanged() } override fun onBindViewHolder(holder: NotificationItemHolder?, position: Int) { val notification = notifications[position] holder!!.bind(notification) } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): NotificationItemHolder { val inflater = LayoutInflater.from(context) val view = inflater.inflate(R.layout.listitem_notification_item,parent,false) return NotificationItemHolder(view) } override fun getItemCount(): Int { return notifications.size } } private inner class NotificationItemHolder(val root: View):RecyclerView.ViewHolder(root){ fun bind(notification:Notification){ val avatar = root.findViewById<CircleImageView>(R.id.avatar) val title = root.findViewById<TextView>(R.id.notification_title) val time = root.findViewById<TextView>(R.id.notification_time) val content = root.findViewById<TextView>(R.id.notification_content) NetworkUtils.getInstace(context)!!.loadImage(avatar,notification.actor.avatarUrl,R.drawable.default_avatar) time.text = CalendarUtils().getTimeDes(notification.createdAt) //clean root.setOnClickListener { } title.text = "" content.text = "" var name = "" if(notification.actor.name == null){ name = notification.actor.login }else{ name = notification.actor.name } if(notification.read){ root.setBackgroundColor(Color.WHITE) }else{ root.setBackgroundColor(resources.getColor(R.color.notification_unread)) } when(notification.type){ "Follow"->{ title.text = spanUserName(name) content.setText(R.string.follow_des) root.setOnClickListener { Route.goUserDetail(activity,notification.actor.login) mPresenter!!.readNotification(notification.id) } } "Mention"->{ title.text = spanMention(name) content.text = Html.fromHtml(notification.mention.bodyHtml).trim() root.setOnClickListener { Route.goTopicDetail(activity,notification.mention.topicId,notification.mention.id) mPresenter!!.readNotification(notification.id) } } "TopicReply"->{ title.text = spanTopicReply(name,notification.reply.topicTitle) content.text = Html.fromHtml(notification.reply.bodyHtml).trim() root.setOnClickListener { Route.goTopicDetail(activity,notification.reply.topicId,notification.reply.id) mPresenter!!.readNotification(notification.id) } } "Topic"->{ title.text = spanTopic(name,notification.topic.title) root.setOnClickListener { Route.goTopicDetail(activity,notification.topic.id) mPresenter!!.readNotification(notification.id) } } } //title.text = Html.fromHtml(notification.) } } companion object Factory{ fun getInstance(args:Bundle?):NotificationFragment{ val fragment = NotificationFragment() if(args != null){ fragment.arguments = args } return fragment } } private fun spanUserName(name:String):Spanned{ val ssb = SpannableStringBuilder(name) val foregroundColor : ForegroundColorSpan = ForegroundColorSpan(context.resources.getColor(R.color.colorPrimary)) ssb.setSpan(foregroundColor,0,name.length,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) return ssb } private fun spanMention(name:String):Spanned{ val text = name + resources.getString(R.string.mention_des) val ssb = SpannableStringBuilder(text) val foregroundColor : ForegroundColorSpan = ForegroundColorSpan(context.resources.getColor(R.color.colorPrimary)) ssb.setSpan(foregroundColor,0,name.length,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) return ssb } private fun spanTopicReply(name:String,title:String):Spanned{ val text = resources.getString(R.string.reply_des,name,title) val ssb = SpannableStringBuilder(text) val foregroundColor1 = ForegroundColorSpan(context.resources.getColor(R.color.colorPrimary)) val foregroundColor2 = ForegroundColorSpan(context.resources.getColor(R.color.colorPrimary)) ssb.setSpan(foregroundColor1,0,name.length,Spannable.SPAN_INCLUSIVE_INCLUSIVE) ssb.setSpan(foregroundColor2,text.indexOf(title),text.indexOf(title) + title.length,Spannable.SPAN_INCLUSIVE_INCLUSIVE) return ssb } private fun spanTopic(name:String,title:String):Spanned{ val text = resources.getString(R.string.new_topic,name,title) val ssb = SpannableStringBuilder(text) val foregroundColor1 = ForegroundColorSpan(context.resources.getColor(R.color.colorPrimary)) val foregroundColor2 = ForegroundColorSpan(context.resources.getColor(R.color.colorPrimary)) ssb.setSpan(foregroundColor1,text.indexOf(name),text.indexOf(name) + name.length,Spannable.SPAN_INCLUSIVE_INCLUSIVE) ssb.setSpan(foregroundColor2,text.indexOf(title),text.indexOf(title) + title.length,Spannable.SPAN_INCLUSIVE_INCLUSIVE) return ssb } }
apache-2.0
7618943beeec01998b9375f0b6a6c59c
39.972851
127
0.663905
4.996689
false
false
false
false
JetBrains/kotlin-native
shared/src/main/kotlin/org/jetbrains/kotlin/konan/target/Xcode.kt
2
2996
/* * Copyright 2010-2018 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.konan.target import org.jetbrains.kotlin.konan.KonanExternalToolFailure import org.jetbrains.kotlin.konan.MissingXcodeException import org.jetbrains.kotlin.konan.exec.Command import org.jetbrains.kotlin.konan.file.File interface Xcode { val toolchain: String val macosxSdk: String val iphoneosSdk: String val iphonesimulatorSdk: String val version: String val appletvosSdk: String val appletvsimulatorSdk: String val watchosSdk: String val watchsimulatorSdk: String // Xcode.app/Contents/Developer/usr val additionalTools: String val simulatorRuntimes: String companion object { val current: Xcode by lazy { CurrentXcode } } } private object CurrentXcode : Xcode { override val toolchain by lazy { val ldPath = xcrun("-f", "ld") // = $toolchain/usr/bin/ld File(ldPath).parentFile.parentFile.parentFile.absolutePath } override val additionalTools: String by lazy { val bitcodeBuildToolPath = xcrun("-f", "bitcode-build-tool") File(bitcodeBuildToolPath).parentFile.parentFile.absolutePath } override val simulatorRuntimes: String by lazy { Command("/usr/bin/xcrun", "simctl", "list", "runtimes", "-j").getOutputLines().joinToString(separator = "\n") } override val macosxSdk by lazy { getSdkPath("macosx") } override val iphoneosSdk by lazy { getSdkPath("iphoneos") } override val iphonesimulatorSdk by lazy { getSdkPath("iphonesimulator") } override val appletvosSdk by lazy { getSdkPath("appletvos") } override val appletvsimulatorSdk by lazy { getSdkPath("appletvsimulator") } override val watchosSdk: String by lazy { getSdkPath("watchos") } override val watchsimulatorSdk: String by lazy { getSdkPath("watchsimulator") } override val version by lazy { xcrun("xcodebuild", "-version") .removePrefix("Xcode ") } private fun xcrun(vararg args: String): String = try { Command("/usr/bin/xcrun", *args).getOutputLines().first() } catch(e: KonanExternalToolFailure) { throw MissingXcodeException("An error occurred during an xcrun execution. Make sure that Xcode and its command line tools are properly installed.", e) } private fun getSdkPath(sdk: String) = xcrun("--sdk", sdk, "--show-sdk-path") }
apache-2.0
dc12166a342f3f2e929f74171e7343f4
35.987654
162
0.703605
4.132414
false
false
false
false
androidx/androidx
window/window/src/main/java/androidx/window/embedding/SplitRule.kt
3
7437
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.window.embedding import android.content.Context import android.graphics.Rect import android.os.Build import android.util.LayoutDirection.LOCALE import android.util.LayoutDirection.LTR import android.util.LayoutDirection.RTL import android.view.WindowMetrics import androidx.annotation.DoNotInline import androidx.annotation.FloatRange import androidx.annotation.IntDef import androidx.annotation.IntRange import androidx.annotation.RequiresApi import androidx.window.embedding.SplitRule.Companion.DEFAULT_SPLIT_MIN_DIMENSION_DP import kotlin.math.min /** * Split configuration rules for activities that are launched to side in a split. * Define the visual properties of the split. Can be set either statically via * [SplitController.Companion.initialize] or at runtime via * [SplitController.registerRule]. The rules can only be applied to activities that * belong to the same application and are running in the same process. The rules are always * applied only to activities that will be started after the rules were set. */ open class SplitRule internal constructor( /** * The smallest value of width of the parent window when the split should be used, in DP. * When the window size is smaller than requested here, activities in the secondary container * will be stacked on top of the activities in the primary one, completely overlapping them. * * The default is [DEFAULT_SPLIT_MIN_DIMENSION_DP] if the app doesn't set. * `0` means to always allow split. */ @IntRange(from = 0) val minWidthDp: Int = DEFAULT_SPLIT_MIN_DIMENSION_DP, /** * The smallest value of the smallest possible width of the parent window in any rotation * when the split should be used, in DP. When the window size is smaller than requested * here, activities in the secondary container will be stacked on top of the activities in * the primary one, completely overlapping them. * * The default is [DEFAULT_SPLIT_MIN_DIMENSION_DP] if the app doesn't set. * `0` means to always allow split. */ @IntRange(from = 0) val minSmallestWidthDp: Int, /** * Defines what part of the width should be given to the primary activity. Defaults to an * equal width split. */ @FloatRange(from = 0.0, to = 1.0) val splitRatio: Float = 0.5f, /** * The layout direction for the split. */ @LayoutDirection val layoutDirection: Int = LOCALE ) : EmbeddingRule() { @IntDef(LTR, RTL, LOCALE) @Retention(AnnotationRetention.SOURCE) internal annotation class LayoutDirection /** * Determines what happens with the associated container when all activities are finished in * one of the containers in a split. * * For example, given that [SplitPairRule.finishPrimaryWithSecondary] is [FINISH_ADJACENT] and * secondary container finishes. The primary associated container is finished if it's * side-by-side with secondary container. The primary associated container is not finished * if it occupies entire task bounds. * * @see SplitPairRule.finishPrimaryWithSecondary * @see SplitPairRule.finishSecondaryWithPrimary * @see SplitPlaceholderRule.finishPrimaryWithPlaceholder */ companion object { /** * Never finish the associated container. * @see SplitRule.Companion */ const val FINISH_NEVER = 0 /** * Always finish the associated container independent of the current presentation mode. * @see SplitRule.Companion */ const val FINISH_ALWAYS = 1 /** * Only finish the associated container when displayed side-by-side/adjacent to the one * being finished. Does not finish the associated one when containers are stacked on top of * each other. * @see SplitRule.Companion */ const val FINISH_ADJACENT = 2 /** * The default min dimension in DP for allowing split if it is not set by apps. The value * reflects [androidx.window.core.layout.WindowWidthSizeClass.MEDIUM]. */ const val DEFAULT_SPLIT_MIN_DIMENSION_DP = 600 } /** * Defines whether an associated container should be finished together with the one that's * already being finished based on their current presentation mode. */ @Retention(AnnotationRetention.SOURCE) @IntDef(FINISH_NEVER, FINISH_ALWAYS, FINISH_ADJACENT) internal annotation class SplitFinishBehavior /** * Verifies if the provided parent bounds are large enough to apply the rule. */ internal fun checkParentMetrics(context: Context, parentMetrics: WindowMetrics): Boolean { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) { return false } val bounds = Api30Impl.getBounds(parentMetrics) // TODO(b/257000820): Application displayMetrics should only be used as a fallback. Replace // with Task density after we include it in WindowMetrics. val density = context.resources.displayMetrics.density return checkParentBounds(density, bounds) } /** * @see checkParentMetrics */ internal fun checkParentBounds(density: Float, bounds: Rect): Boolean { val minWidthPx = convertDpToPx(density, minWidthDp) val minSmallestWidthPx = convertDpToPx(density, minSmallestWidthDp) val validMinWidth = (minWidthDp == 0 || bounds.width() >= minWidthPx) val validSmallestMinWidth = ( minSmallestWidthDp == 0 || min(bounds.width(), bounds.height()) >= minSmallestWidthPx ) return validMinWidth && validSmallestMinWidth } /** * Converts the dimension from Dp to pixels. */ private fun convertDpToPx(density: Float, @IntRange(from = 0) dimensionDp: Int): Int { return (dimensionDp * density + 0.5f).toInt() } @RequiresApi(30) internal object Api30Impl { @DoNotInline fun getBounds(windowMetrics: WindowMetrics): Rect { return windowMetrics.bounds } } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is SplitRule) return false if (minWidthDp != other.minWidthDp) return false if (minSmallestWidthDp != other.minSmallestWidthDp) return false if (splitRatio != other.splitRatio) return false if (layoutDirection != other.layoutDirection) return false return true } override fun hashCode(): Int { var result = minWidthDp result = 31 * result + minSmallestWidthDp result = 31 * result + splitRatio.hashCode() result = 31 * result + layoutDirection return result } }
apache-2.0
0241127837c7d597f751280d3e9660d7
37.739583
99
0.688987
4.761204
false
false
false
false
androidx/androidx
recyclerview/recyclerview-lint/src/test/java/androidx/recyclerview/lint/InvalidSetHasFixedSizeTest.kt
3
11253
/* * 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.recyclerview.lint import androidx.recyclerview.lint.Stubs.RECYCLER_VIEW import androidx.recyclerview.lint.Stubs.VIEW import com.android.tools.lint.checks.infrastructure.LintDetectorTest.kotlin import com.android.tools.lint.checks.infrastructure.LintDetectorTest.xml import com.android.tools.lint.checks.infrastructure.TestLintTask.lint import org.junit.Test class InvalidSetHasFixedSizeTest { @Test fun testCorrectUseOfHasFixedSize() { val resourceIds = kotlin( "com/example/R.kt", """ package com.example object R { object id { const val my_recycler_view = 0 } } """ ).indented().within("src") val source = kotlin( "com/example/Example.kt", """ package com.example import android.view.View import androidx.recyclerview.widget.RecyclerView class Example { fun main() { val view: View = TODO() val recyclerView = view.findViewById<RecyclerView>(R.id.my_recycler_view) recyclerView?.setHasFixedSize(true) } } """ ).indented().within("src") val layoutFile = xml( "layout/recycler_view.xml", """<?xml version="1.0" encoding="utf-8"?> <androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/my_recycler_view" android:layout_width="match_parent" android:layout_height="match_parent"/> """.trimIndent() ).indented().within("res") lint() .files( VIEW, RECYCLER_VIEW, layoutFile, resourceIds, source ) .issues(InvalidSetHasFixedSizeDetector.ISSUE) .run() .expectClean() } @Test fun testCorrectUseOfHasFixedSize2() { val resourceIds = kotlin( "com/example/R.kt", """ package com.example object R { object id { const val my_recycler_view = 0 } } """ ).indented().within("src") val source = kotlin( "com/example/Example.kt", """ package com.example import android.view.View import androidx.recyclerview.widget.RecyclerView class Example { fun main() { val view: View = TODO() val recyclerView = view.findViewById<RecyclerView>(R.id.my_recycler_view) recyclerView?.let { it.setHasFixedSize(true) } } } """ ).indented().within("src") val layoutFile = xml( "layout/recycler_view.xml", """<?xml version="1.0" encoding="utf-8"?> <androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/my_recycler_view" android:layout_width="match_parent" android:layout_height="match_parent"/> """.trimIndent() ).indented().within("res") lint() .files( VIEW, RECYCLER_VIEW, layoutFile, resourceIds, source ) .issues(InvalidSetHasFixedSizeDetector.ISSUE) .run() .expectClean() } @Test fun testInCorrectUsageOfFixedSize() { val resourceIds = kotlin( "com/example/R.kt", """ package com.example object R { object id { const val my_recycler_view = 0 } } """ ).indented().within("src") val source = kotlin( "com/example/Example.kt", """ package com.example import android.view.View import androidx.recyclerview.widget.RecyclerView class Example { fun main() { val view: View = TODO() val recyclerView = view.findViewById<RecyclerView>(R.id.my_recycler_view) recyclerView?.setHasFixedSize(true) } } """ ).indented().within("src") val layoutFile = xml( "layout/recycler_view.xml", """<?xml version="1.0" encoding="utf-8"?> <androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/my_recycler_view" android:layout_width="match_parent" android:layout_height="wrap_content"/> """.trimIndent() ).indented().within("res") lint() .files( VIEW, RECYCLER_VIEW, layoutFile, resourceIds, source ) .issues(InvalidSetHasFixedSizeDetector.ISSUE) .run() /* ktlint-disable max-line-length */ .expect( """ src/com/example/Example.kt:10: Error: When using `setHasFixedSize() in an RecyclerView, wrap_content cannot be used as a value for size in the scrolling direction. [InvalidSetHasFixedSize] recyclerView?.setHasFixedSize(true) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1 errors, 0 warnings """.trimIndent() ) /* ktlint-enable max-line-length */ } @Test fun testInCorrectUsageOfFixedSize2() { val resourceIds = kotlin( "com/example/R.kt", """ package com.example object R { object id { const val my_recycler_view = 0 } } """ ).indented().within("src") val source = kotlin( "com/example/Example.kt", """ package com.example import android.view.View import androidx.recyclerview.widget.RecyclerView class Example { fun main() { val view: View = TODO() val recyclerView = view.findViewById<RecyclerView>(R.id.my_recycler_view) recyclerView?.setHasFixedSize(true) } } """ ).indented().within("src") val layoutFile = xml( "layout/recycler_view.xml", """<?xml version="1.0" encoding="utf-8"?> <androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/my_recycler_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:orientation="horizontal" /> """.trimIndent() ).indented().within("res") lint() .files( VIEW, RECYCLER_VIEW, layoutFile, resourceIds, source ) .issues(InvalidSetHasFixedSizeDetector.ISSUE) .run() /* ktlint-disable max-line-length */ .expect( """ src/com/example/Example.kt:10: Error: When using `setHasFixedSize() in an RecyclerView, wrap_content cannot be used as a value for size in the scrolling direction. [InvalidSetHasFixedSize] recyclerView?.setHasFixedSize(true) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1 errors, 0 warnings """.trimIndent() ) /* ktlint-enable max-line-length */ } @Test fun testInCorrectUseOfHasFixedSize3() { val resourceIds = kotlin( "com/example/R.kt", """ package com.example object R { object id { const val my_recycler_view = 0 } } """ ).indented().within("src") val source = kotlin( "com/example/Example.kt", """ package com.example import android.view.View import androidx.recyclerview.widget.RecyclerView class Example { fun main() { val view: View = TODO() val recyclerView = view.findViewById<RecyclerView>(R.id.my_recycler_view) setFixedSize(recyclerView) } private fun setFixedSize(recyclerView: RecyclerView?) { recyclerView?.setHasFixedSize(true) } } """ ).indented().within("src") val layoutFile = xml( "layout/recycler_view.xml", """<?xml version="1.0" encoding="utf-8"?> <androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/my_recycler_view" android:layout_width="wrap_content" android:layout_height="match_parent"/> """.trimIndent() ).indented().within("res") lint() .files( VIEW, RECYCLER_VIEW, layoutFile, resourceIds, source ) .issues(InvalidSetHasFixedSizeDetector.ISSUE) .run() /* ktlint-disable max-line-length */ .expect( """ src/com/example/Example.kt:14: Error: When using `setHasFixedSize() in an RecyclerView, wrap_content cannot be used as a value for size in the scrolling direction. [InvalidSetHasFixedSize] recyclerView?.setHasFixedSize(true) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1 errors, 0 warnings """.trimIndent() ) /* ktlint-enable max-line-length */ } }
apache-2.0
52c17c06dadabe88d34818af3ea45e82
31.523121
204
0.488225
5.166667
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeParameterTypeFix.kt
1
5724
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsContexts import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinChangeSignatureConfiguration import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinMethodDescriptor import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinTypeInfo import org.jetbrains.kotlin.idea.refactoring.changeSignature.runChangeSignature import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import com.intellij.openapi.application.runWriteAction import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.DefinitelyNotNullType import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.typeUtil.isTypeParameter import org.jetbrains.kotlin.utils.addToStdlib.safeAs class ChangeParameterTypeFix(element: KtParameter, type: KotlinType) : KotlinQuickFixAction<KtParameter>(element) { private val typePresentation = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(type) private val typeInfo = KotlinTypeInfo(isCovariant = false, text = IdeDescriptorRenderers.SOURCE_CODE_NOT_NULL_TYPE_APPROXIMATION.renderType(type)) private val originalTypeText = type.safeAs<DefinitelyNotNullType>()?.original?.toString() ?: type.toString() private val containingDeclarationName: String? private val isPrimaryConstructorParameter: Boolean init { val declaration = PsiTreeUtil.getParentOfType(element, KtNamedDeclaration::class.java) this.containingDeclarationName = declaration?.name this.isPrimaryConstructorParameter = declaration is KtPrimaryConstructor } override fun startInWriteAction(): Boolean = false override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean { return containingDeclarationName != null } override fun getText(): String = element?.let { when { isPrimaryConstructorParameter -> { KotlinBundle.message( "fix.change.return.type.text.primary.constructor", it.name.toString(), containingDeclarationName.toString(), typePresentation ) } else -> { KotlinBundle.message( "fix.change.return.type.text.function", it.name.toString(), containingDeclarationName.toString(), typePresentation ) } } } ?: "" private val commandName: String @NlsContexts.Command get() = element?.let { when { isPrimaryConstructorParameter -> { KotlinBundle.message( "fix.change.return.type.command.primary.constructor", it.name.toString(), containingDeclarationName.toString(), typePresentation ) } else -> { KotlinBundle.message( "fix.change.return.type.command.function", it.name.toString(), containingDeclarationName.toString(), typePresentation ) } } } ?: "" override fun getFamilyName() = KotlinBundle.message("fix.change.return.type.family") override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val function = element.getStrictParentOfType<KtFunction>() ?: return val parameterIndex = function.valueParameters.indexOf(element) val descriptor = function.resolveToDescriptorIfAny(BodyResolveMode.FULL) as? FunctionDescriptor ?: return val parameterType = descriptor.valueParameters[parameterIndex].type val typeParameterText = if (parameterType.isTypeParameter()) element.typeReference?.text else null val configuration = object : KotlinChangeSignatureConfiguration { override fun configure(originalDescriptor: KotlinMethodDescriptor) = originalDescriptor.apply { parameters[if (receiver != null) parameterIndex + 1 else parameterIndex].currentTypeInfo = typeInfo } override fun performSilently(affectedFunctions: Collection<PsiElement>) = true } runChangeSignature(element.project, editor, descriptor, configuration, element, commandName) if (typeParameterText != null && typeParameterText != originalTypeText) { runWriteAction { function.removeTypeParameter(typeParameterText) } } } private fun KtFunction.removeTypeParameter(typeParameterText: String?) { val typeParameterList = typeParameterList ?: return val typeParameters = typeParameterList.parameters val typeParameter = typeParameters.firstOrNull { it.name == typeParameterText } ?: return if (typeParameters.size == 1) typeParameterList.delete() else EditCommaSeparatedListHelper.removeItem(typeParameter) } }
apache-2.0
f3e01b099a3ffacfcbc763a3450a17ce
48.344828
158
0.708246
5.557282
false
false
false
false
phase/lang-kotlin-antlr-compiler
src/main/kotlin/xyz/jadonfowler/compiler/pass/Pass.kt
1
2418
package xyz.jadonfowler.compiler.pass import org.antlr.v4.runtime.ParserRuleContext import xyz.jadonfowler.compiler.ast.* import xyz.jadonfowler.compiler.ast.Function import xyz.jadonfowler.compiler.visitor.Visitor open class Pass(module: Module) : Visitor(module) { fun reportError(problem: String, context: ParserRuleContext) { val line = context.start.line - 1 val lines = module.source.split("\n") val before = if (line > 0) "$line ${lines[line - 1]}\n" else "" val errorLine = "${line + 1} ${lines[line]}\n" val after = if (line + 1 < lines.size) "${line + 2} ${lines[line + 1]}\n" else "" val column = context.start.charPositionInLine val arrow = " ".repeat(line.toString().length + 1) + "~".repeat(column) + "^" module.errors.add("$before$errorLine$arrow\n$after$problem\n") } override fun visit(variable: Variable) { } override fun visit(variableDeclarationStatement: VariableDeclarationStatement) { } override fun visit(variableReassignmentStatement: VariableReassignmentStatement) { } override fun visit(binaryOperator: BinaryOperator) { } override fun visit(block: Block) { } override fun visit(clazz: Clazz) { } override fun visit(falseExpression: FalseExpression) { } override fun visit(formal: Formal) { } override fun visit(function: Function) { } override fun visit(functionCallExpression: FunctionCallExpression) { } override fun visit(functionCallStatement: FunctionCallStatement) { } override fun visit(methodCallStatement: MethodCallStatement) { } override fun visit(methodCallExpression: MethodCallExpression) { } override fun visit(fieldGetterExpression: FieldGetterExpression) { } override fun visit(fieldSetterStatement: FieldSetterStatement) { } override fun visit(ifStatement: IfStatement) { } override fun visit(integerLiteral: IntegerLiteral) { } override fun visit(floatLiteral: FloatLiteral) { } override fun visit(referenceExpression: ReferenceExpression) { } override fun visit(stringLiteral: StringLiteral) { } override fun visit(trueExpression: TrueExpression) { } override fun visit(whileStatement: WhileStatement) { } override fun visit(clazzInitializerExpression: ClazzInitializerExpression) { } }
mpl-2.0
e158865b2cf5ce5ca35e5d8331a3ce3a
25.582418
89
0.686104
4.249561
false
false
false
false
GunoH/intellij-community
plugins/kotlin/ml-completion/src/org/jetbrains/kotlin/idea/mlCompletion/MlCompletionForKotlinFeature.kt
4
1337
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.mlCompletion import com.intellij.completion.ml.settings.CompletionMLRankingSettings import org.jetbrains.kotlin.idea.configuration.ExperimentalFeature object MlCompletionForKotlinFeature : ExperimentalFeature() { override val title: String get() = KotlinMlCompletionBundle.message("experimental.ml.completion") override fun shouldBeShown(): Boolean = MLCompletionForKotlin.isAvailable override var isEnabled: Boolean get() = MLCompletionForKotlin.isEnabled set(value) { MLCompletionForKotlin.isEnabled = value } } internal object MLCompletionForKotlin { const val isAvailable: Boolean = true var isEnabled: Boolean get() { val settings = CompletionMLRankingSettings.getInstance() return settings.isRankingEnabled && settings.isLanguageEnabled("Kotlin") } set(value) { val settings = CompletionMLRankingSettings.getInstance() if (value && !settings.isRankingEnabled) { settings.isRankingEnabled = true } settings.setLanguageEnabled("Kotlin", value) } }
apache-2.0
cb4fa8a6098945db1b07923ac8fc946c
35.135135
158
0.700823
4.97026
false
false
false
false
GunoH/intellij-community
plugins/ant/jps-plugin/testSrc/org/jetbrains/jps/ant/JpsAntSerializationTest.kt
12
5105
// 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.jps.ant import com.intellij.openapi.util.io.FileUtil import com.intellij.testFramework.UsefulTestCase import com.intellij.util.SystemProperties import com.intellij.util.containers.FileCollectionFactory import com.intellij.util.io.directoryContent import org.jetbrains.jps.ant.model.JpsAntExtensionService import org.jetbrains.jps.ant.model.impl.artifacts.JpsAntArtifactExtensionImpl import org.jetbrains.jps.model.artifact.JpsArtifactService import org.jetbrains.jps.model.serialization.JpsSerializationTestCase import java.io.File class JpsAntSerializationTest : JpsSerializationTestCase() { private lateinit var antHome: File override fun setUp() { super.setUp() antHome = createTempDir("antHome") } fun testLoadArtifactProperties() { loadProject(PROJECT_PATH) val artifacts = JpsArtifactService.getInstance().getSortedArtifacts(myProject) assertEquals(2, artifacts.size) val dir = artifacts[0] assertEquals("dir", dir.name) val preprocessing = JpsAntExtensionService.getPreprocessingExtension(dir)!! assertTrue(preprocessing.isEnabled) assertEquals(getUrl("build.xml"), preprocessing.fileUrl) assertEquals("show-message", preprocessing.targetName) assertEquals(JpsAntArtifactExtensionImpl.ARTIFACT_OUTPUT_PATH_PROPERTY, assertOneElement(preprocessing.antProperties).getPropertyName()) val postprocessing = JpsAntExtensionService.getPostprocessingExtension(dir)!! assertEquals(getUrl("build.xml"), postprocessing.fileUrl) assertEquals("create-file", postprocessing.targetName) val properties = postprocessing.antProperties assertEquals(2, properties.size) assertEquals(JpsAntArtifactExtensionImpl.ARTIFACT_OUTPUT_PATH_PROPERTY, properties[0].propertyName) assertEquals(dir.outputPath, properties[0].propertyValue) assertEquals("message.text", properties[1].propertyName) assertEquals("post", properties[1].propertyValue) val jar = artifacts[1] assertEquals("jar", jar.name) assertNull(JpsAntExtensionService.getPostprocessingExtension(jar)) assertNull(JpsAntExtensionService.getPreprocessingExtension(jar)) } fun testLoadAntInstallations() { directoryContent { file("foo.jar") dir("lib") { file("bar.jar") } }.generate(antHome) loadGlobalSettings(OPTIONS_PATH) val installation = JpsAntExtensionService.findAntInstallation(myModel, "Apache Ant version 1.8.2") assertNotNull(installation) assertEquals(FileUtil.toSystemIndependentName(installation!!.antHome.absolutePath), FileUtil.toSystemIndependentName( File(SystemProperties.getUserHome(), "applications/apache-ant-1.8.2").absolutePath)) val installation2 = JpsAntExtensionService.findAntInstallation(myModel, "Patched Ant") assertNotNull(installation2) UsefulTestCase.assertSameElements(toFiles(installation2!!.classpath), File(antHome, "foo.jar"), File(antHome, "lib/bar.jar")) } override fun getPathVariables(): Map<String, String> { val pathVariables = super.getPathVariables() pathVariables.put("MY_ANT_HOME_DIR", antHome.absolutePath) return pathVariables } fun testLoadAntConfiguration() { loadProject(PROJECT_PATH) loadGlobalSettings(OPTIONS_PATH) val buildXmlUrl = getUrl("build.xml") val options = JpsAntExtensionService.getOptions(myProject, buildXmlUrl) assertEquals(128, options.maxHeapSize) assertEquals("-J-Dmy.ant.prop=123", options.antCommandLineParameters) assertContainsElements(toFiles(options.additionalClasspath), File(getAbsolutePath("lib/jdom.jar")), File(getAbsolutePath("ant-lib/a.jar"))) val property = assertOneElement(options.properties) assertEquals("my.property", property.getPropertyName()) assertEquals("its value", property.getPropertyValue()) val emptyFileUrl = getUrl("empty.xml") val options2 = JpsAntExtensionService.getOptions(myProject, emptyFileUrl) assertEquals(256, options2.maxHeapSize) assertEquals(10, options2.maxStackSize) assertEquals("1.6", options2.customJdkName) val bundled = JpsAntExtensionService.getAntInstallationForBuildFile(myModel, buildXmlUrl)!! assertEquals("Bundled Ant", bundled.name) val installation = JpsAntExtensionService.getAntInstallationForBuildFile(myModel, emptyFileUrl)!! assertEquals("Apache Ant version 1.8.2", installation.name) } companion object { const val PROJECT_PATH = "plugins/ant/jps-plugin/testData/ant-project" const val OPTIONS_PATH = "plugins/ant/jps-plugin/testData/config/options" private fun toFiles(classpath: List<String>): Set<File> { val result = FileCollectionFactory.createCanonicalFileSet() for (path in classpath) { result.add(File(path)) } return result } } }
apache-2.0
fc341a0961cc7afd0b20287960ec8608
41.190083
140
0.741626
4.744424
false
true
false
false
JetBrains/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/OptimizationPipeline.kt
1
7752
package org.jetbrains.kotlin.backend.konan import kotlinx.cinterop.alloc import kotlinx.cinterop.memScoped import kotlinx.cinterop.ptr import kotlinx.cinterop.value import llvm.* import org.jetbrains.kotlin.backend.konan.llvm.makeVisibilityHiddenLikeLlvmInternalizePass import org.jetbrains.kotlin.konan.target.* private fun initializeLlvmGlobalPassRegistry() { val passRegistry = LLVMGetGlobalPassRegistry() LLVMInitializeCore(passRegistry) LLVMInitializeTransformUtils(passRegistry) LLVMInitializeScalarOpts(passRegistry) LLVMInitializeVectorization(passRegistry) LLVMInitializeInstCombine(passRegistry) LLVMInitializeIPO(passRegistry) LLVMInitializeInstrumentation(passRegistry) LLVMInitializeAnalysis(passRegistry) LLVMInitializeIPA(passRegistry) LLVMInitializeCodeGen(passRegistry) LLVMInitializeTarget(passRegistry) } internal fun shouldRunLateBitcodePasses(context: Context): Boolean { return context.coverage.enabled } internal fun runLateBitcodePasses(context: Context, llvmModule: LLVMModuleRef) { val passManager = LLVMCreatePassManager()!! LLVMKotlinAddTargetLibraryInfoWrapperPass(passManager, context.llvm.targetTriple) context.coverage.addLateLlvmPasses(passManager) LLVMRunPassManager(passManager, llvmModule) LLVMDisposePassManager(passManager) } private class LlvmPipelineConfiguration(context: Context) { private val target = context.config.target private val configurables: Configurables = context.config.platform.configurables val targetTriple: String = context.llvm.targetTriple val cpuModel: String = configurables.targetCpu ?: run { context.reportCompilationWarning("targetCpu for target $target was not set. Targeting `generic` cpu.") "generic" } val cpuFeatures: String = configurables.targetCpuFeatures ?: "" /** * Null value means that LLVM should use default inliner params * for the provided optimization and size level. */ val customInlineThreshold: Int? = when { context.shouldOptimize() -> configurables.llvmInlineThreshold?.let { it.toIntOrNull() ?: run { context.reportCompilationWarning( "`llvmInlineThreshold` should be an integer. Got `$it` instead. Using default value." ) null } } context.shouldContainDebugInfo() -> null else -> null } val optimizationLevel: LlvmOptimizationLevel = when { context.shouldOptimize() -> LlvmOptimizationLevel.AGGRESSIVE context.shouldContainDebugInfo() -> LlvmOptimizationLevel.NONE else -> LlvmOptimizationLevel.DEFAULT } val sizeLevel: LlvmSizeLevel = when { // We try to optimize code as much as possible on embedded targets. target is KonanTarget.ZEPHYR || target == KonanTarget.WASM32 -> LlvmSizeLevel.AGGRESSIVE context.shouldOptimize() -> LlvmSizeLevel.NONE context.shouldContainDebugInfo() -> LlvmSizeLevel.NONE else -> LlvmSizeLevel.NONE } val codegenOptimizationLevel: LLVMCodeGenOptLevel = when { context.shouldOptimize() -> LLVMCodeGenOptLevel.LLVMCodeGenLevelAggressive context.shouldContainDebugInfo() -> LLVMCodeGenOptLevel.LLVMCodeGenLevelNone else -> LLVMCodeGenOptLevel.LLVMCodeGenLevelDefault } val relocMode: LLVMRelocMode = configurables.currentRelocationMode(context).translateToLlvmRelocMode() private fun RelocationModeFlags.Mode.translateToLlvmRelocMode() = when (this) { RelocationModeFlags.Mode.PIC -> LLVMRelocMode.LLVMRelocPIC RelocationModeFlags.Mode.STATIC -> LLVMRelocMode.LLVMRelocStatic RelocationModeFlags.Mode.DEFAULT -> LLVMRelocMode.LLVMRelocDefault } val codeModel: LLVMCodeModel = LLVMCodeModel.LLVMCodeModelDefault enum class LlvmOptimizationLevel(val value: Int) { NONE(0), DEFAULT(1), AGGRESSIVE(3) } enum class LlvmSizeLevel(val value: Int) { NONE(0), DEFAULT(1), AGGRESSIVE(2) } } internal fun runLlvmOptimizationPipeline(context: Context) { val llvmModule = context.llvmModule!! val config = LlvmPipelineConfiguration(context) context.log { """ Running LLVM optimizations with the following parameters: target_triple: ${config.targetTriple} cpu_model: ${config.cpuModel} cpu_features: ${config.cpuFeatures} optimization_level: ${config.optimizationLevel.value} size_level: ${config.sizeLevel.value} inline_threshold: ${config.customInlineThreshold ?: "default"} """.trimIndent() } memScoped { LLVMKotlinInitializeTargets() initializeLlvmGlobalPassRegistry() val passBuilder = LLVMPassManagerBuilderCreate() val modulePasses = LLVMCreatePassManager() LLVMPassManagerBuilderSetOptLevel(passBuilder, config.optimizationLevel.value) LLVMPassManagerBuilderSetSizeLevel(passBuilder, config.sizeLevel.value) // TODO: use LLVMGetTargetFromName instead. val target = alloc<LLVMTargetRefVar>() val foundLlvmTarget = LLVMGetTargetFromTriple(config.targetTriple, target.ptr, null) == 0 check(foundLlvmTarget) { "Cannot get target from triple ${config.targetTriple}." } val targetMachine = LLVMCreateTargetMachine( target.value, config.targetTriple, config.cpuModel, config.cpuFeatures, config.codegenOptimizationLevel, config.relocMode, config.codeModel) LLVMKotlinAddTargetLibraryInfoWrapperPass(modulePasses, config.targetTriple) // TargetTransformInfo pass. LLVMAddAnalysisPasses(targetMachine, modulePasses) if (context.llvmModuleSpecification.isFinal) { // Since we are in a "closed world" internalization can be safely used // to reduce size of a bitcode with global dce. LLVMAddInternalizePass(modulePasses, 0) } else if (context.config.produce == CompilerOutputKind.STATIC_CACHE) { // Hidden visibility makes symbols internal when linking the binary. // When producing dynamic library, this enables stripping unused symbols from binary with -dead_strip flag, // similar to DCE enabled by internalize but later: makeVisibilityHiddenLikeLlvmInternalizePass(llvmModule) // Important for binary size, workarounds references to undefined symbols from interop libraries. } LLVMAddGlobalDCEPass(modulePasses) config.customInlineThreshold?.let { threshold -> LLVMPassManagerBuilderUseInlinerWithThreshold(passBuilder, threshold) } // Pipeline that is similar to `llvm-lto`. // TODO: Add ObjC optimization passes. LLVMPassManagerBuilderPopulateLTOPassManager(passBuilder, modulePasses, Internalize = 0, RunInliner = 1) LLVMRunPassManager(modulePasses, llvmModule) LLVMPassManagerBuilderDispose(passBuilder) LLVMDisposeTargetMachine(targetMachine) LLVMDisposePassManager(modulePasses) } if (shouldRunLateBitcodePasses(context)) { runLateBitcodePasses(context, llvmModule) } } internal fun RelocationModeFlags.currentRelocationMode(context: Context): RelocationModeFlags.Mode = when (determineLinkerOutput(context)) { LinkerOutputKind.DYNAMIC_LIBRARY -> dynamicLibraryRelocationMode LinkerOutputKind.STATIC_LIBRARY -> staticLibraryRelocationMode LinkerOutputKind.EXECUTABLE -> executableRelocationMode }
apache-2.0
e9d66e393282053887d73d121ed8a964
40.021164
119
0.710139
4.758748
false
true
false
false
GunoH/intellij-community
platform/webSymbols/src/com/intellij/webSymbols/webTypes/json/WebTypesJsonUtils.kt
1
18687
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.webSymbols.webTypes.json import com.intellij.webSymbols.* import com.intellij.webSymbols.WebSymbol.Companion.KIND_CSS_CLASSES import com.intellij.webSymbols.WebSymbol.Companion.KIND_CSS_FUNCTIONS import com.intellij.webSymbols.WebSymbol.Companion.KIND_CSS_PROPERTIES import com.intellij.webSymbols.WebSymbol.Companion.KIND_CSS_PSEUDO_CLASSES import com.intellij.webSymbols.WebSymbol.Companion.KIND_CSS_PSEUDO_ELEMENTS import com.intellij.webSymbols.WebSymbol.Companion.KIND_HTML_ATTRIBUTES import com.intellij.webSymbols.WebSymbol.Companion.KIND_HTML_ELEMENTS import com.intellij.webSymbols.WebSymbol.Companion.KIND_JS_EVENTS import com.intellij.webSymbols.WebSymbol.Companion.KIND_JS_PROPERTIES import com.intellij.webSymbols.WebSymbol.Companion.NAMESPACE_CSS import com.intellij.webSymbols.WebSymbol.Companion.NAMESPACE_HTML import com.intellij.webSymbols.WebSymbol.Companion.NAMESPACE_JS import com.intellij.webSymbols.WebSymbol.Companion.PROP_ARGUMENTS import com.intellij.webSymbols.WebSymbol.Companion.PROP_DOC_HIDE_PATTERN import com.intellij.webSymbols.WebSymbol.Companion.PROP_HIDE_FROM_COMPLETION import com.intellij.webSymbols.completion.WebSymbolCodeCompletionItem import com.intellij.webSymbols.context.WebSymbolsContext import com.intellij.webSymbols.context.WebSymbolsContextKindRules import com.intellij.webSymbols.html.WebSymbolHtmlAttributeValue import com.intellij.webSymbols.query.WebSymbolNameConversionRules import com.intellij.webSymbols.query.WebSymbolNameConverter import com.intellij.webSymbols.query.WebSymbolsQueryExecutor import com.intellij.webSymbols.query.impl.WebSymbolsQueryExecutorImpl.Companion.asSymbolNamespace import com.intellij.webSymbols.query.impl.WebSymbolsQueryExecutorImpl.Companion.parsePath import com.intellij.webSymbols.utils.NameCaseUtils import com.intellij.webSymbols.webTypes.WebTypesSymbolTypeSupport import com.intellij.webSymbols.webTypes.filters.WebSymbolsFilter import com.intellij.webSymbols.webTypes.json.NameConversionRulesSingle.NameConverter import java.util.* import java.util.function.Function private fun namespaceOf(host: GenericContributionsHost): SymbolNamespace = when (host) { is HtmlContributionsHost -> NAMESPACE_HTML is CssContributionsHost -> NAMESPACE_CSS is JsContributionsHost -> NAMESPACE_JS else -> throw IllegalArgumentException(host.toString()) } internal fun Contributions.getAllContributions(framework: FrameworkId?): Sequence<Triple<SymbolNamespace, SymbolKind, List<BaseContribution>>> = sequenceOf(css, js, html) .filter { it != null } .flatMap { host -> host.collectDirectContributions(framework).mapWith(namespaceOf(host)) } internal fun GenericContributionsHost.getAllContributions(framework: FrameworkId?): Sequence<Triple<SymbolNamespace, SymbolKind, List<BaseContribution>>> = if (this is BaseContribution) sequenceOf(this, css, js, html) .filter { it != null } .flatMap { host -> host.collectDirectContributions(framework).mapWith(namespaceOf(host)) } else this.collectDirectContributions(framework).mapWith(namespaceOf(this)) private fun Sequence<Pair<SymbolKind, List<BaseContribution>>>.mapWith(namespace: SymbolNamespace): Sequence<Triple<SymbolNamespace, SymbolKind, List<BaseContribution>>> = map { if (namespace == NAMESPACE_HTML && it.first == KIND_JS_EVENTS) Triple(NAMESPACE_JS, KIND_JS_EVENTS, it.second) else Triple(namespace, it.first, it.second) } internal const val KIND_HTML_VUE_LEGACY_COMPONENTS = "\$vue-legacy-components\$" internal const val VUE_DIRECTIVE_PREFIX = "v-" internal const val VUE_FRAMEWORK = "vue" internal const val KIND_HTML_VUE_COMPONENTS = "vue-components" internal const val KIND_HTML_VUE_COMPONENT_PROPS = "props" internal const val KIND_HTML_VUE_DIRECTIVES = "vue-directives" internal const val KIND_HTML_VUE_DIRECTIVE_ARGUMENT = "argument" internal const val KIND_HTML_VUE_DIRECTIVE_MODIFIERS = "modifiers" private fun GenericContributionsHost.collectDirectContributions(framework: FrameworkId?): Sequence<Pair<SymbolKind, List<BaseContribution>>> = (when (this) { is HtmlContributionsHost -> sequenceOf( Pair(KIND_HTML_ATTRIBUTES, this.attributes), Pair(KIND_HTML_ELEMENTS, this.elements), Pair(KIND_JS_EVENTS, this.events) ).plus( when (this) { is Html -> sequenceOf( Pair(if (framework == VUE_FRAMEWORK) KIND_HTML_VUE_LEGACY_COMPONENTS else KIND_HTML_ELEMENTS, this.tags) ) is HtmlElement -> sequenceOf( Pair(KIND_JS_EVENTS, this.events) ) is HtmlAttribute -> if (this.name.startsWith(VUE_DIRECTIVE_PREFIX) && !this.name.contains( ' ') && framework == VUE_FRAMEWORK) { sequenceOf( Pair(KIND_HTML_VUE_DIRECTIVE_ARGUMENT, this.vueArgument?.toHtmlContribution()?.let { listOf(it) } ?: listOf(matchAllHtmlContribution("Vue directive argument"))), Pair(KIND_HTML_VUE_DIRECTIVE_MODIFIERS, this.vueModifiers.takeIf { it.isNotEmpty() }?.map { it.toHtmlContribution() } ?: listOf(matchAllHtmlContribution("Vue directive modifier"))) ) } else emptySequence() else -> emptySequence() } ) is CssContributionsHost -> sequenceOf( Pair(KIND_CSS_CLASSES, this.classes), Pair(KIND_CSS_FUNCTIONS, this.functions), Pair(KIND_CSS_PROPERTIES, this.properties), Pair(KIND_CSS_PSEUDO_CLASSES, this.pseudoClasses), Pair(KIND_CSS_PSEUDO_ELEMENTS, this.pseudoElements) ) is JsContributionsHost -> sequenceOf( Pair(KIND_JS_EVENTS, this.events), Pair(KIND_JS_PROPERTIES, this.properties) ) else -> emptySequence() }) .plus(this.additionalProperties.asSequence() .map { (name, list) -> Pair(name, list.mapNotNull { it.value as? GenericContribution }) } .filter { it.second.isNotEmpty() }) internal val GenericContributionsHost.genericContributions: Map<String, List<GenericContribution>> get() = this.additionalProperties.asSequence() .map { (name, list) -> Pair(name, list.mapNotNull { it.value as? GenericContribution }) } .filter { it.second.isNotEmpty() } .toMap() internal val GenericContributionsHost.genericProperties: Map<String, Any> get() = this.additionalProperties.asSequence() .map { (name, list) -> Pair(name, list?.mapNotNull { prop -> prop.value.takeIf { it !is GenericContribution } } ?: emptyList()) } .mapNotNull { when (it.second.size) { 0 -> null 1 -> Pair(it.first, it.second[0]) else -> it } } .plus( when (this) { is CssPseudoClass -> sequenceOf(Pair(PROP_ARGUMENTS, this.arguments ?: false)) is CssPseudoElement -> sequenceOf(Pair(PROP_ARGUMENTS, this.arguments ?: false)) else -> emptySequence() } ) .toMap() internal fun Reference.getSymbolKind(context: WebSymbol?): WebSymbolQualifiedKind? = when (val reference = this.value) { is String -> reference is ReferenceWithProps -> reference.path else -> null } .let { parsePath(it, context?.namespace) } .lastOrNull() ?.let { if (it.namespace != null) WebSymbolQualifiedKind(it.namespace, it.kind) else null } internal fun Reference.resolve(name: String?, scope: List<WebSymbolsScope>, queryExecutor: WebSymbolsQueryExecutor, virtualSymbols: Boolean = true, abstractSymbols: Boolean = false): List<WebSymbol> { if (name != null && name.isEmpty()) return emptyList() return when (val reference = this.value) { is String -> queryExecutor.runNameMatchQuery( reference + if (name != null) "/$name" else "", virtualSymbols, abstractSymbols, scope = scope) is ReferenceWithProps -> { val nameConversionRules = reference.createNameConversionRules() val matches = queryExecutor.withNameConversionRules(nameConversionRules).runNameMatchQuery( (reference.path ?: return emptyList()) + if (name != null) "/$name" else "", reference.includeVirtual ?: virtualSymbols, reference.includeAbstract ?: abstractSymbols, scope = scope) if (reference.filter == null) return matches val properties = reference.additionalProperties.toMap() WebSymbolsFilter.get(reference.filter) .filterNameMatches(matches, queryExecutor, scope, properties) } else -> throw IllegalArgumentException(reference::class.java.name) } } internal fun Reference.codeCompletion(name: String, scope: List<WebSymbolsScope>, queryExecutor: WebSymbolsQueryExecutor, position: Int = 0, virtualSymbols: Boolean = true): List<WebSymbolCodeCompletionItem> { return when (val reference = this.value) { is String -> queryExecutor.runCodeCompletionQuery("$reference/$name", position, virtualSymbols, scope) is ReferenceWithProps -> { val nameConversionRules = reference.createNameConversionRules() val codeCompletions = queryExecutor.withNameConversionRules(nameConversionRules).runCodeCompletionQuery( (reference.path ?: return emptyList()) + "/$name", position, reference.includeVirtual ?: virtualSymbols, scope) if (reference.filter == null) return codeCompletions val properties = reference.additionalProperties.toMap() WebSymbolsFilter.get(reference.filter) .filterCodeCompletions(codeCompletions, queryExecutor, scope, properties) } else -> throw IllegalArgumentException(reference::class.java.name) } } internal fun EnablementRules.wrap(): WebSymbolsContextKindRules.EnablementRules = WebSymbolsContextKindRules.EnablementRules( nodePackages, fileExtensions, ideLibraries, fileNamePatterns.mapNotNull { it.toRegex() }, scriptUrlPatterns.mapNotNull { it.toRegex() } ) internal fun DisablementRules.wrap(): WebSymbolsContextKindRules.DisablementRules = WebSymbolsContextKindRules.DisablementRules( fileExtensions, fileNamePatterns.mapNotNull { it.toRegex() }, ) internal fun BaseContribution.Priority.wrap() = WebSymbol.Priority.values()[ordinal] internal val BaseContribution.attributeValue: HtmlAttributeValue? get() = (this as? GenericContribution)?.attributeValue ?: (this as? HtmlAttribute)?.value internal val BaseContribution.type: List<Type>? get() = (this as? TypedContribution)?.type?.takeIf { it.isNotEmpty() } internal fun DeprecatedHtmlAttributeVueArgument.toHtmlContribution(): BaseContribution { val result = GenericHtmlContribution() result.name = "Vue directive argument" result.description = this.description result.docUrl = this.docUrl result.pattern = this.pattern if (pattern.isMatchAllRegex) result.additionalProperties[PROP_DOC_HIDE_PATTERN] = true.toGenericHtmlPropertyValue() return result } internal fun DeprecatedHtmlAttributeVueModifier.toHtmlContribution(): BaseContribution { val result = GenericHtmlContribution() result.name = this.name result.description = this.description result.docUrl = this.docUrl result.pattern = this.pattern if (pattern.isMatchAllRegex) result.additionalProperties[PROP_DOC_HIDE_PATTERN] = true.toGenericHtmlPropertyValue() return result } internal fun Pattern.toRegex(): Regex? = when (val pattern = value) { is String -> Regex(pattern, RegexOption.IGNORE_CASE) is PatternObject -> if (pattern.caseSensitive == true) Regex(pattern.regex) else Regex(pattern.regex, RegexOption.IGNORE_CASE) else -> null } internal val WebTypes.jsTypesSyntaxWithLegacy: WebTypes.JsTypesSyntax? get() = jsTypesSyntax ?: contributions?.html?.typesSyntax ?.let { it as? String } ?.let { try { WebTypes.JsTypesSyntax.fromValue(it) } catch (e: IllegalArgumentException) { null } } internal val WebTypes.descriptionMarkupWithLegacy: WebTypes.DescriptionMarkup? get() = descriptionMarkup?.takeIf { it != WebTypes.DescriptionMarkup.NONE } ?: contributions?.html?.descriptionMarkup ?.let { it as? String } ?.let { try { WebTypes.DescriptionMarkup.fromValue(it) } catch (e: IllegalArgumentException) { null } } internal fun HtmlValueType.wrap(): WebSymbolHtmlAttributeValue.Type? = when (this.value) { "enum" -> WebSymbolHtmlAttributeValue.Type.ENUM "of-match" -> WebSymbolHtmlAttributeValue.Type.OF_MATCH "string" -> WebSymbolHtmlAttributeValue.Type.STRING "boolean" -> WebSymbolHtmlAttributeValue.Type.BOOLEAN "number" -> WebSymbolHtmlAttributeValue.Type.NUMBER null -> null else -> WebSymbolHtmlAttributeValue.Type.COMPLEX } internal fun HtmlValueType.toLangType(): List<Type>? = when (val typeValue = this.value) { null, "enum", "of-match" -> null is List<*> -> typeValue.filterIsInstance<Type>() is TypeReference, is String -> listOf( Type().also { it.value = typeValue }) else -> null } internal fun HtmlAttributeValue.Kind.wrap(): WebSymbolHtmlAttributeValue.Kind = when (this) { HtmlAttributeValue.Kind.NO_VALUE -> WebSymbolHtmlAttributeValue.Kind.NO_VALUE HtmlAttributeValue.Kind.PLAIN -> WebSymbolHtmlAttributeValue.Kind.PLAIN HtmlAttributeValue.Kind.EXPRESSION -> WebSymbolHtmlAttributeValue.Kind.EXPRESSION } internal fun GenericHtmlContribution.copyLegacyFrom(other: BaseContribution) { name = other.name pattern = other.pattern description = other.description docUrl = other.docUrl source = other.source deprecated = other.deprecated if (other is GenericContribution) { default = other.default required = other.required } additionalProperties.putAll(this.additionalProperties) } private fun matchAllHtmlContribution(name: String): GenericContribution = GenericHtmlContribution().also { contribution -> contribution.name = name contribution.pattern = NamePatternRoot().also { it.value = ".*" } contribution.additionalProperties[PROP_DOC_HIDE_PATTERN] = true.toGenericHtmlPropertyValue() contribution.additionalProperties[PROP_HIDE_FROM_COMPLETION] = true.toGenericHtmlPropertyValue() } private val NamePatternRoot?.isMatchAllRegex get() = this != null && value.let { it is String && (it == ".*" || it == ".+") } private fun Any.toGenericHtmlPropertyValue(): GenericHtmlContributions = GenericHtmlContributions().also { list -> list.add(GenericHtmlContributionOrProperty().also { it.value = this }) } private fun ReferenceWithProps.createNameConversionRules(): List<WebSymbolNameConversionRules> { val rules = nameConversion ?: return emptyList() val lastPath = parsePath(path).lastOrNull() if (lastPath?.namespace == null) return emptyList() val builder = WebSymbolNameConversionRules.builder() fun buildConvertersMap(value: Any?, addToBuilder: (WebSymbolQualifiedKind, WebSymbolNameConverter) -> Unit) { when (value) { is NameConverter -> mergeConverters(listOf(value))?.let { addToBuilder(WebSymbolQualifiedKind(lastPath.namespace, lastPath.kind), it) } is List<*> -> mergeConverters(value.filterIsInstance<NameConverter>())?.let { addToBuilder(WebSymbolQualifiedKind(lastPath.namespace, lastPath.kind), it) } is NameConversionRulesSingle -> buildNameConverters(value.additionalProperties, { mergeConverters(listOf(it)) }, addToBuilder) is NameConversionRulesMultiple -> buildNameConverters(value.additionalProperties, { mergeConverters(it) }, addToBuilder) else -> throw IllegalArgumentException(value?.toString()) } } buildConvertersMap(rules.canonicalNames?.value, builder::addCanonicalNamesRule) buildConvertersMap(rules.matchNames?.value, builder::addMatchNamesRule) buildConvertersMap(rules.nameVariants?.value, builder::addNameVariantsRule) if (builder.isEmpty()) return emptyList() else return listOf(builder.build()) } private fun NameConverter.toFunction(): Function<String, String> = when (this) { NameConverter.AS_IS -> Function { it } NameConverter.LOWERCASE -> Function { it.lowercase(Locale.US) } NameConverter.UPPERCASE -> Function { it.uppercase(Locale.US) } NameConverter.PASCAL_CASE -> Function { NameCaseUtils.toPascalCase(it) } NameConverter.CAMEL_CASE -> Function { NameCaseUtils.toCamelCase(it) } NameConverter.KEBAB_CASE -> Function { NameCaseUtils.toKebabCase(it) } NameConverter.SNAKE_CASE -> Function { NameCaseUtils.toSnakeCase(it) } } internal fun mergeConverters(converters: List<NameConverter>): WebSymbolNameConverter? { if (converters.isEmpty()) return null val all = converters.map { it.toFunction() } return WebSymbolNameConverter { name -> all.map { it.apply(name) } } } internal fun <T> buildNameConverters(map: Map<String, T>?, mapper: (T) -> (WebSymbolNameConverter?), addToBuilder: (WebSymbolQualifiedKind, WebSymbolNameConverter) -> Unit) { for ((key, value) in map?.entries ?: return) { val path = key.splitToSequence('/') .filter { it.isNotEmpty() } .toList().takeIf { it.size == 2 } ?: continue val namespace = path[0].asSymbolNamespace() ?: continue val symbolKind = path[1] val converter = mapper(value) ?: continue addToBuilder(WebSymbolQualifiedKind(namespace, symbolKind), converter) } } internal fun List<Type>.mapToTypeReferences(): List<WebTypesSymbolTypeSupport.TypeReference> = mapNotNull { when (val reference = it.value) { is String -> WebTypesSymbolTypeSupport.TypeReference(null, reference) is TypeReference -> if (reference.name != null) WebTypesSymbolTypeSupport.TypeReference(reference.module, reference.name) else null else -> null } } internal fun ContextBase.evaluate(context: WebSymbolsContext): Boolean = when (this) { is ContextKindName -> context[kind] == name is ContextAllOf -> allOf.all { it.evaluate(context) } is ContextAnyOf -> anyOf.any { it.evaluate(context) } is ContextNot -> !not.evaluate(context) else -> throw IllegalStateException(this.javaClass.simpleName) }
apache-2.0
384cfbe52346714246bf6f22ad20c865
41.862385
171
0.713063
4.401083
false
false
false
false
GunoH/intellij-community
platform/code-style-impl/src/com/intellij/formatting/VirtualFormattingImpl.kt
2
3081
// 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.formatting import com.intellij.lang.ASTNode import com.intellij.lang.VirtualFormattingListener import com.intellij.openapi.editor.impl.DocumentImpl import com.intellij.openapi.util.Key import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.codeStyle.CodeStyleSettings import com.intellij.psi.formatter.FormattingDocumentModelImpl private val formattingListenerKey = Key.create<VirtualFormattingListener?>("VIRTUAL_FORMATTING_CHANGE_LISTENER") var PsiElement.virtualFormattingListener: VirtualFormattingListener? get() = getUserData(formattingListenerKey) set(value) = putUserData(formattingListenerKey, value) class VirtualFormattingModelBuilder(private val underlyingBuilder: FormattingModelBuilder, val file: PsiFile, val listener: VirtualFormattingListener) : FormattingModelBuilder { private fun FormattingModel.wrap(): FormattingModel = VirtualFormattingModel(file, rootBlock, listener) override fun createModel(formattingContext: FormattingContext) = underlyingBuilder.createModel(formattingContext).wrap() override fun createModel(element: PsiElement?, settings: CodeStyleSettings?) = underlyingBuilder.createModel(element, settings).wrap() override fun createModel(element: PsiElement, settings: CodeStyleSettings, mode: FormattingMode) = underlyingBuilder.createModel(element, settings, mode).wrap() override fun createModel(element: PsiElement, range: TextRange, settings: CodeStyleSettings, mode: FormattingMode) = underlyingBuilder.createModel(element, range, settings, mode).wrap() } private class VirtualFormattingModel( file: PsiFile, private val rootBlock: Block, private val listener: VirtualFormattingListener) : FormattingModel { private val dummyModel = FormattingDocumentModelImpl(DocumentImpl(file.viewProvider.contents, true), file) override fun commitChanges() = Unit // do nothing override fun getRootBlock() = rootBlock override fun getDocumentModel() = dummyModel override fun shiftIndentInsideRange(node: ASTNode?, range: TextRange, indent: Int): TextRange { listener.shiftIndentInsideRange(node, range, indent) return range } override fun replaceWhiteSpace(textRange: TextRange, whiteSpace: String): TextRange { listener.replaceWhiteSpace(textRange, whiteSpace) return textRange } } fun isEligibleForVirtualFormatting(element: PsiElement): Boolean { return element.virtualFormattingListener != null } fun wrapForVirtualFormatting(element: PsiElement, builder: FormattingModelBuilder?): FormattingModelBuilder? { builder ?: return null val listener = element.virtualFormattingListener ?: return builder val file = element.containingFile ?: return builder return VirtualFormattingModelBuilder(builder, file, listener) }
apache-2.0
88b2df905fbea91e962d545b200e7279
40.08
158
0.788056
4.898251
false
false
false
false
smmribeiro/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesBrowserIgnoredFilesNode.kt
10
3212
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.vcs.changes.ui import com.intellij.ide.DataManager import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.vcs.AbstractVcs import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.changes.ChangeListManagerImpl import com.intellij.openapi.vcs.changes.ChangeListOwner import com.intellij.openapi.vcs.changes.IgnoredViewDialog import com.intellij.openapi.vcs.changes.VcsIgnoreManagerImpl import com.intellij.openapi.vcs.changes.ignore.actions.IgnoreFileActionGroup import com.intellij.ui.awt.RelativePoint import com.intellij.ui.treeStructure.Tree import com.intellij.vcsUtil.VcsUtil import org.jetbrains.annotations.Nls import javax.swing.tree.TreePath class ChangesBrowserIgnoredFilesNode(private val project: Project, files: List<FilePath>) : ChangesBrowserSpecificFilePathsNode<ChangesBrowserNode.Tag>(ChangesBrowserNode.IGNORED_FILES_TAG, files, { if (!project.isDisposed) IgnoredViewDialog(project).show() }) { override fun render(renderer: ChangesBrowserNodeRenderer, selected: Boolean, expanded: Boolean, hasFocus: Boolean) { super.render(renderer, selected, expanded, hasFocus) if (!project.isDisposed && ChangeListManagerImpl.getInstanceImpl(project).isIgnoredInUpdateMode) { appendUpdatingState(renderer) } } override fun canAcceptDrop(dragBean: ChangeListDragBean) = dragBean.unversionedFiles.isNotEmpty() override fun acceptDrop(dragOwner: ChangeListOwner, dragBean: ChangeListDragBean) { val tree = dragBean.sourceComponent as? Tree ?: return val vcs = dragBean.unversionedFiles.getVcs() ?: return val ignoreFileType = VcsIgnoreManagerImpl.getInstanceImpl(project).findIgnoreFileType(vcs) ?: return val ignoreGroup = IgnoreFileActionGroup(ignoreFileType) val popup = JBPopupFactory.getInstance().createActionGroupPopup( null, ignoreGroup, DataManager.getInstance().getDataContext(dragBean.sourceComponent), JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, false) tree.getPathBounds(TreePath(dragBean.targetNode.path))?.let { dropBounds -> popup.show(RelativePoint(dragBean.sourceComponent, dropBounds.location)) } } @Nls override fun getTextPresentation(): String = getUserObject().toString() override fun getSortWeight(): Int = ChangesBrowserNode.IGNORED_SORT_WEIGHT private fun List<FilePath>.getVcs(): AbstractVcs? = mapNotNull { file -> VcsUtil.getVcsFor(project, file) }.firstOrNull() }
apache-2.0
bbf7c5e2945bbab45b447e1f4be6da66
43.625
129
0.766189
4.608321
false
false
false
false
smmribeiro/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsLogContentUtil.kt
1
5644
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.vcs.log.impl import com.intellij.openapi.project.Project import com.intellij.openapi.ui.MessageType import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier import com.intellij.openapi.wm.ToolWindowManager import com.intellij.ui.content.Content import com.intellij.ui.content.ContentManager import com.intellij.ui.content.TabDescriptor import com.intellij.ui.content.TabGroupId import com.intellij.util.Consumer import com.intellij.util.ContentUtilEx import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.vcs.log.VcsLogBundle import com.intellij.vcs.log.VcsLogUi import com.intellij.vcs.log.impl.VcsLogManager.VcsLogUiFactory import com.intellij.vcs.log.ui.MainVcsLogUi import com.intellij.vcs.log.ui.VcsLogPanel import com.intellij.vcs.log.ui.VcsLogUiEx import org.jetbrains.annotations.ApiStatus import java.util.function.Function import java.util.function.Supplier import javax.swing.JComponent /** * Utility methods to operate VCS Log tabs as [Content]s of the [ContentManager] of the VCS toolwindow. */ object VcsLogContentUtil { private fun getLogUi(c: JComponent): VcsLogUiEx? { val uis = VcsLogPanel.getLogUis(c) require(uis.size <= 1) { "Component $c has more than one log ui: $uis" } return uis.singleOrNull() } internal fun selectLogUi(project: Project, logUi: VcsLogUi): Boolean { val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ChangesViewContentManager.TOOLWINDOW_ID) ?: return false val manager = toolWindow.contentManager val component = ContentUtilEx.findContentComponent(manager) { c -> getLogUi(c)?.id == logUi.id } ?: return false if (!toolWindow.isVisible) { toolWindow.activate(null) } return ContentUtilEx.selectContent(manager, component, true) } fun getId(content: Content): String? { return getLogUi(content.component)?.id } @JvmStatic fun <U : VcsLogUiEx> openLogTab(project: Project, logManager: VcsLogManager, tabGroupId: TabGroupId, tabDisplayName: Function<U, @NlsContexts.TabTitle String>, factory: VcsLogUiFactory<out U>, focus: Boolean): U { val logUi = logManager.createLogUi(factory, VcsLogTabLocation.TOOL_WINDOW) val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ChangesViewContentManager.TOOLWINDOW_ID) ?: throw IllegalStateException("Could not find tool window for id ${ChangesViewContentManager.TOOLWINDOW_ID}") ContentUtilEx.addTabbedContent(toolWindow.contentManager, tabGroupId, TabDescriptor(VcsLogPanel(logManager, logUi), Supplier { tabDisplayName.apply(logUi) }, logUi), focus) if (focus) { toolWindow.activate(null) } return logUi } fun closeLogTab(manager: ContentManager, tabId: String): Boolean { return ContentUtilEx.closeContentTab(manager) { c: JComponent -> getLogUi(c)?.id == tabId } } @JvmStatic fun runInMainLog(project: Project, consumer: Consumer<in MainVcsLogUi>) { val window = ToolWindowManager.getInstance(project).getToolWindow(ChangesViewContentManager.TOOLWINDOW_ID) if (window == null || !selectMainLog(window.contentManager)) { showLogIsNotAvailableMessage(project) return } val runConsumer = Runnable { VcsLogContentProvider.getInstance(project)!!.executeOnMainUiCreated(consumer) } if (!window.isVisible) { window.activate(runConsumer) } else { runConsumer.run() } } @RequiresEdt fun showLogIsNotAvailableMessage(project: Project) { VcsBalloonProblemNotifier.showOverChangesView(project, VcsLogBundle.message("vcs.log.is.not.available"), MessageType.WARNING) } internal fun findMainLog(cm: ContentManager): Content? { // here tab name is used instead of log ui id to select the correct tab // it's done this way since main log ui may not be created when this method is called return cm.contents.find { VcsLogContentProvider.TAB_NAME == it.tabName } } internal fun selectMainLog(cm: ContentManager): Boolean { val mainContent = findMainLog(cm) ?: return false cm.setSelectedContent(mainContent) return true } fun selectMainLog(project: Project): Boolean { val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ChangesViewContentManager.TOOLWINDOW_ID) ?: return false return selectMainLog(toolWindow.contentManager) } @JvmStatic fun updateLogUiName(project: Project, ui: VcsLogUi) { val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ChangesViewContentManager.TOOLWINDOW_ID) ?: return val manager = toolWindow.contentManager val component = ContentUtilEx.findContentComponent(manager) { c: JComponent -> ui === getLogUi(c) } ?: return ContentUtilEx.updateTabbedContentDisplayName(manager, component) } @ApiStatus.ScheduledForRemoval(inVersion = "2021.1") @Deprecated("use VcsProjectLog#runWhenLogIsReady(Project, Consumer) instead.") @JvmStatic @RequiresBackgroundThread fun getOrCreateLog(project: Project): VcsLogManager? { VcsProjectLog.ensureLogCreated(project) return VcsProjectLog.getInstance(project).logManager } }
apache-2.0
6cd30fb7948741c535e69bbf5bf8196e
41.126866
137
0.740255
4.637634
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/gradle/testRunConfigurations/expectClassWithTests/src/jvmTest/kotlin/sample/SampleTestsJVM.kt
1
501
package sample import kotlin.test.Test import kotlin.test.assertTrue // JVM actual class <lineMarker descr="Run Test" settings=":cleanJvmTest :jvmTest --tests \"sample.SampleTests\""><lineMarker descr="Has declaration in common module">SampleTests</lineMarker></lineMarker> { @Test actual fun <lineMarker descr="Run Test" settings=":cleanJvmTest :jvmTest --tests \"sample.SampleTests.testMe\""><lineMarker descr="Has declaration in common module">testMe</lineMarker></lineMarker>() { } }
apache-2.0
0b326ed813404c8ceb5f9ecd3ecc125d
44.636364
205
0.752495
4.318966
false
true
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/OpenURLActionType.kt
1
666
package ch.rmy.android.http_shortcuts.scripting.actions.types import ch.rmy.android.http_shortcuts.scripting.ActionAlias import ch.rmy.android.http_shortcuts.scripting.actions.ActionDTO class OpenURLActionType : BaseActionType() { override val type = TYPE override fun fromDTO(actionDTO: ActionDTO) = OpenURLAction( url = actionDTO.getString(0) ?: "", ) override fun getAlias() = ActionAlias( functionName = FUNCTION_NAME, functionNameAliases = setOf("openURL"), parameters = 1, ) companion object { private const val TYPE = "open_url" private const val FUNCTION_NAME = "openUrl" } }
mit
ce82d2bb61fb82f8f04f4b541ef7e124
26.75
64
0.686186
4.08589
false
false
false
false
vector-im/vector-android
vector/src/main/java/im/vector/fragments/keysbackup/settings/KeysBackupSettingsFragment.kt
2
4927
/* * Copyright 2019 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.fragments.keysbackup.settings import android.os.Bundle import android.view.View import androidx.appcompat.app.AlertDialog import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import butterknife.BindView import im.vector.R import im.vector.activity.KeysBackupRestoreActivity import im.vector.activity.KeysBackupSetupActivity import im.vector.activity.util.WaitingViewData import im.vector.fragments.VectorBaseFragment import org.matrix.androidsdk.crypto.keysbackup.KeysBackupStateManager class KeysBackupSettingsFragment : VectorBaseFragment(), KeysBackupSettingsRecyclerViewAdapter.AdapterListener { companion object { fun newInstance() = KeysBackupSettingsFragment() } override fun getLayoutResId() = R.layout.fragment_keys_backup_settings private lateinit var viewModel: KeysBackupSettingsViewModel @BindView(R.id.keys_backup_settings_recycler_view) lateinit var recyclerView: androidx.recyclerview.widget.RecyclerView private var recyclerViewAdapter: KeysBackupSettingsRecyclerViewAdapter? = null override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context) recyclerView.layoutManager = layoutManager recyclerViewAdapter = KeysBackupSettingsRecyclerViewAdapter(activity!!) recyclerView.adapter = recyclerViewAdapter recyclerViewAdapter?.adapterListener = this viewModel = activity?.run { ViewModelProviders.of(this).get(KeysBackupSettingsViewModel::class.java) } ?: throw Exception("Invalid Activity") viewModel.keyBackupState.observe(this, Observer { keysBackupState -> if (keysBackupState == null) { //Cannot happen? viewModel.keyVersionTrust.value = null } else { when (keysBackupState) { KeysBackupStateManager.KeysBackupState.Unknown, KeysBackupStateManager.KeysBackupState.CheckingBackUpOnHomeserver -> { viewModel.loadingEvent.value = WaitingViewData(context!!.getString(R.string.keys_backup_settings_checking_backup_state)) } else -> { viewModel.loadingEvent.value = null //All this cases will be manage by looking at the backup trust object viewModel.session?.crypto?.keysBackup?.mKeysBackupVersion?.let { viewModel.getKeysBackupTrust(it) } ?: run { viewModel.keyVersionTrust.value = null } } } } // Update the adapter for each state change viewModel.session?.let { session -> recyclerViewAdapter?.updateWithTrust(session, viewModel.keyVersionTrust.value) } }) viewModel.keyVersionTrust.observe(this, Observer { viewModel.session?.let { session -> recyclerViewAdapter?.updateWithTrust(session, it) } }) } override fun didSelectSetupMessageRecovery() { context?.let { startActivity(KeysBackupSetupActivity.intent(it, viewModel.session?.myUserId ?: "", false)) } } override fun didSelectRestoreMessageRecovery() { context?.let { startActivity(KeysBackupRestoreActivity.intent(it, viewModel.session?.myUserId ?: "")) } } override fun didSelectDeleteSetupMessageRecovery() { activity?.let { AlertDialog.Builder(it) .setTitle(R.string.keys_backup_settings_delete_confirm_title) .setMessage(R.string.keys_backup_settings_delete_confirm_message) .setCancelable(false) .setPositiveButton(R.string.keys_backup_settings_delete_confirm_title) { _, _ -> viewModel.deleteCurrentBackup(it) } .setNegativeButton(R.string.cancel, null) .setCancelable(true) .show() } } }
apache-2.0
aacd9e70756c6d91178f92826c07eca3
37.80315
144
0.649279
5.241489
false
false
false
false
softappeal/yass
kotlin/yass/main/ch/softappeal/yass/remote/ContractId.kt
1
1837
package ch.softappeal.yass.remote import ch.softappeal.yass.* class ContractId<C : Any> @PublishedApi internal constructor( val contract: Class<C>, val id: Int, val methodMapper: MethodMapper ) inline fun <reified C : Any> contractId(id: Int, methodMapperFactory: MethodMapperFactory): ContractId<C> = ContractId(C::class.java, id, methodMapperFactory(C::class.java)) @OnlyNeededForJava fun <C : Any> contractId(contract: Class<C>, id: Int, methodMapperFactory: MethodMapperFactory): ContractId<C> = ContractId(contract, id, methodMapperFactory(contract)) abstract class Services protected constructor(val methodMapperFactory: MethodMapperFactory) { private val identifiers = mutableSetOf<Int>() @OnlyNeededForJava protected fun <C : Any> contractId(contract: Class<C>, id: Int): ContractId<C> { require(identifiers.add(id)) { "service with id $id already added" } return contractId(contract, id, methodMapperFactory) } protected inline fun <reified C : Any> contractId(id: Int): ContractId<C> = contractId(C::class.java, id) } abstract class AbstractInvocation internal constructor(val methodMapping: MethodMapping, val arguments: List<Any?>) { @Volatile var context: Any? = null } interface AsyncInterceptor { @Throws(Exception::class) fun entry(invocation: AbstractInvocation) @Throws(Exception::class) fun exit(invocation: AbstractInvocation, result: Any?) @Throws(Exception::class) fun exception(invocation: AbstractInvocation, exception: Exception) } val DirectAsyncInterceptor = object : AsyncInterceptor { override fun entry(invocation: AbstractInvocation) {} override fun exit(invocation: AbstractInvocation, result: Any?) {} override fun exception(invocation: AbstractInvocation, exception: Exception) {} }
bsd-3-clause
9d405e3e853278972a82f0ba077ce50a
35.019608
117
0.737616
4.146727
false
false
false
false
intrigus/jtransc
jtransc-utils/src/com/jtransc/serialization/xml/StrReader.kt
2
7361
package com.jtransc.serialization.xml import com.jtransc.error.invalidOp import com.jtransc.text.substr class StrReader(val str: String, val file: String = "file", var pos: Int = 0) { companion object { fun literals(vararg lits: String): Literals = Literals.fromList(lits.toList().toTypedArray()) } val length: Int = this.str.length val eof: Boolean get() = (this.pos >= this.str.length) val hasMore: Boolean get() = (this.pos < this.str.length) fun reset() = run { this.pos = 0 } fun createRange(range: IntRange): TRange = createRange(range.start, range.endInclusive + 1) fun createRange(start: Int = this.pos, end: Int = this.pos): TRange = TRange(start, end, this) fun readRange(length: Int): TRange { val range = TRange(this.pos, this.pos + length, this) this.pos += length return range } inline fun slice(action: () -> Unit): String? { val start = this.pos action() val end = this.pos return if (end > start) this.slice(start, end) else null } fun slice(start: Int, end: Int): String = this.str.substring(start, end) fun peek(count: Int): String = substr(this.pos, count) fun peek(): Char = if (hasMore) this.str[this.pos] else '\u0000' fun peekChar(): Char = if (hasMore) this.str[this.pos] else '\u0000' fun read(count: Int): String = this.peek(count).apply { skip(count) } fun skipUntil(char: Char) = run { while (hasMore && this.peekChar() != char) this.readChar() } fun skipUntilIncluded(char: Char) = run { while (hasMore && this.readChar() != char) Unit } //inline fun skipWhile(check: (Char) -> Boolean) = run { while (check(this.peekChar())) this.skip(1) } inline fun skipWhile(filter: (Char) -> Boolean) = run { while (hasMore && filter(this.peekChar())) this.readChar() } inline fun skipUntil(filter: (Char) -> Boolean) = run { while (hasMore && !filter(this.peekChar())) this.readChar() } inline fun matchWhile(check: (Char) -> Boolean): String? = slice { skipWhile(check) } fun readUntil(char: Char) = this.slice { skipUntil(char) } fun readUntilIncluded(char: Char) = this.slice { skipUntilIncluded(char) } inline fun readWhile(filter: (Char) -> Boolean) = this.slice { skipWhile(filter) } ?: "" inline fun readUntil(filter: (Char) -> Boolean) = this.slice { skipUntil(filter) } ?: "" fun unread(count: Int = 1) = this.apply { this.pos -= count; } fun readChar(): Char = if (hasMore) this.str[this.pos++] else '\u0000' fun read(): Char = if (hasMore) this.str[this.pos++] else '\u0000' fun readExpect(expected: String): String { val readed = this.read(expected.length) if (readed != expected) throw IllegalArgumentException("Expected '$expected' but found '$readed' at $pos") return readed } fun expect(expected: Char) = readExpect("$expected") fun skip(count: Int = 1) = this.apply { this.pos += count; } private fun substr(pos: Int, length: Int): String { return this.str.substring(Math.min(pos, this.length), Math.min(pos + length, this.length)) } fun matchLit(lit: String): String? { if (substr(this.pos, lit.length) != lit) return null this.pos += lit.length return lit } fun matchLitRange(lit: String): TRange? = if (substr(this.pos, lit.length) == lit) this.readRange(lit.length) else null fun matchLitListRange(lits: Literals): TRange? { for (len in lits.lengths) { if (lits.contains(substr(this.pos, len))) return this.readRange(len) } return null } fun skipSpaces() = this.apply { this.skipWhile { Character.isWhitespace(it) } } fun matchIdentifier() = matchWhile { Character.isLetterOrDigit(it) || it == '-' || it == '~' || it == ':' } fun matchSingleOrDoubleQuoteString(): String? { when (this.peekChar()) { '\'', '"' -> { return this.slice { val quoteType = this.readChar() this.readUntil(quoteType) this.readChar() } } else -> return null } } //fun matchEReg(v: Regex): String? { // val result = v.find(this.str.substring(this.pos)) ?: return null // val m = result.groups[0]!!.value // this.pos += m.length // return m //} // //fun matchERegRange(v: Regex): TRange? { // val result = v.find(this.str.substring(this.pos)) ?: return null // return this.readRange(result.groups[0]!!.value.length) //} fun matchStartEnd(start: String, end: String): String? { if (substr(this.pos, start.length) != start) return null val startIndex = this.pos val index = this.str.indexOf(end, this.pos) if (index < 0) return null //trace(index); this.pos = index + end.length return this.slice(startIndex, this.pos) } fun clone(): StrReader = StrReader(str, file, pos) fun tryRead(str: String): Boolean { if (peek(str.length) == str) { skip(str.length) return true } return false } class Literals(private val lits: Array<String>, private val map: MutableMap<String, Boolean>, val lengths: Array<Int>) { companion object { fun invoke(vararg lits: String): Literals = fromList(lits.toCollection(arrayListOf<String>()).toTypedArray()) //fun invoke(lits:Array<String>): Literals = fromList(lits) fun fromList(lits: Array<String>): Literals { val lengths = lits.map { it.length }.sorted().reversed().distinct().toTypedArray() val map = hashMapOf<String, Boolean>() for (lit in lits) map[lit] = true return Literals(lits, map, lengths) } } fun contains(lit: String) = map.containsKey(lit) fun matchAt(str: String, offset: Int): String? { for (len in lengths) { val id = str.substr(offset, len) if (contains(id)) return id } return null } override fun toString() = "Literals(${lits.joinToString(" ")})" } class TRange(val min: Int, val max: Int, val reader: StrReader) { companion object { fun combine(a: TRange, b: TRange): TRange { return TRange(Math.min(a.min, b.min), Math.max(a.max, b.max), a.reader) } fun combineList(list: List<TRange>): TRange? { if (list.isEmpty()) return null val first = list[0] var min = first.min var max = first.max for (i in list) { min = Math.min(min, i.min) max = Math.max(max, i.max) } return TRange(min, max, first.reader) } fun createDummy() = TRange(0, 0, StrReader("")) } fun contains(index: Int): Boolean = index >= this.min && index <= this.max override fun toString() = "$min:$max" val file: String get() = this.reader.file val text: String get () = this.reader.slice(this.min, this.max) fun startEmptyRange(): TRange = TRange(this.min, this.min, this.reader) fun endEmptyRange(): TRange = TRange(this.max, this.max, this.reader) fun displace(offset: Int): TRange = TRange(this.min + offset, this.max + offset, this.reader) } } fun StrReader.readStringLit(reportErrors: Boolean = true): String { val out = StringBuilder() val quotec = read() when (quotec) { '"', '\'' -> Unit else -> invalidOp("Invalid string literal") } var closed = false while (hasMore) { val c = read() if (c == '\\') { val cc = read() out.append(when (cc) { '\\' -> '\\'; '/' -> '/'; '\'' -> '\''; '"' -> '"' 'b' -> '\b'; 'f' -> '\u000c'; 'n' -> '\n'; 'r' -> '\r'; 't' -> '\t' 'u' -> read(4).toInt(0x10).toChar() else -> invalidOp("Invalid char '$cc'") }) } else if (c == quotec) { closed = true break } else { out.append(c) } } if (!closed && reportErrors) { throw RuntimeException("String literal not closed! '${this.str}'") } return out.toString() }
apache-2.0
d0fd6378b807ca35ed40fb83b961baf2
33.237209
121
0.647738
3.019278
false
false
false
false
blademainer/intellij-community
platform/built-in-server/src/org/jetbrains/io/fastCgi/FastCgiService.kt
4
6702
/* * Copyright 2000-2014 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.io.fastCgi import com.intellij.execution.process.OSProcessHandler import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.util.Consumer import com.intellij.util.containers.ConcurrentIntObjectMap import com.intellij.util.containers.ContainerUtil import io.netty.bootstrap.Bootstrap import io.netty.buffer.ByteBuf import io.netty.channel.Channel import io.netty.handler.codec.http.* import org.jetbrains.builtInWebServer.SingleConnectionNetService import org.jetbrains.concurrency.Promise import org.jetbrains.io.* import java.util.concurrent.atomic.AtomicInteger val LOG: Logger = Logger.getInstance(FastCgiService::class.java) // todo send FCGI_ABORT_REQUEST if client channel disconnected public abstract class FastCgiService(project: Project) : SingleConnectionNetService(project) { private val requestIdCounter = AtomicInteger() protected val requests: ConcurrentIntObjectMap<Channel> = ContainerUtil.createConcurrentIntObjectMap<Channel>() companion object { private fun sendBadGateway(channel: Channel) { try { if (channel.isActive()) { Responses.sendStatus(HttpResponseStatus.BAD_GATEWAY, channel) } } catch (e: Throwable) { NettyUtil.log(e, LOG) } } private fun parseHeaders(response: HttpResponse, buffer: ByteBuf) { val builder = StringBuilder() while (buffer.isReadable) { builder.setLength(0) var key: String? = null var valueExpected = true while (true) { val b = buffer.readByte().toInt() if (b < 0 || b.toChar() == '\n') { break } if (b.toChar() != '\r') { if (valueExpected && b.toChar() == ':') { valueExpected = false key = builder.toString() builder.setLength(0) MessageDecoder.skipWhitespace(buffer) } else { builder.append(b.toChar()) } } } if (builder.length() == 0) { // end of headers return } // skip standard headers if (key.isNullOrEmpty() || key!!.startsWith("http", ignoreCase = true) || key!!.startsWith("X-Accel-", ignoreCase = true)) { continue } val value = builder.toString() if (key!!.equals("status", ignoreCase = true)) { val index = value.indexOf(' ') if (index == -1) { LOG.warn("Cannot parse status: " + value) response.setStatus(HttpResponseStatus.OK) } else { response.setStatus(HttpResponseStatus.valueOf(Integer.parseInt(value.substring(0, index)))) } } else if (!(key.startsWith("http") || key.startsWith("HTTP"))) { response.headers().add(key, value) } } } } override fun closeProcessConnections() { try { super.closeProcessConnections() } finally { requestIdCounter.set(0) if (!requests.isEmpty()) { val waitingClients = ContainerUtil.toList(requests.elements()) requests.clear() for (channel in waitingClients) { sendBadGateway(channel) } } } } override fun configureBootstrap(bootstrap: Bootstrap, errorOutputConsumer: Consumer<String>) { bootstrap.handler { it.pipeline().addLast("fastCgiDecoder", FastCgiDecoder(errorOutputConsumer, this@FastCgiService)) it.pipeline().addLast("exceptionHandler", ChannelExceptionHandler.getInstance()) } } public fun send(fastCgiRequest: FastCgiRequest, content: ByteBuf) { val notEmptyContent: ByteBuf? if (content.isReadable()) { content.retain() notEmptyContent = content notEmptyContent.touch() } else { notEmptyContent = null } try { if (processHandler.has()) { fastCgiRequest.writeToServerChannel(notEmptyContent, processChannel!!) } else { processHandler.get() .done(object : Consumer<OSProcessHandler> { override fun consume(osProcessHandler: OSProcessHandler) { fastCgiRequest.writeToServerChannel(notEmptyContent, processChannel!!) } }) .rejected { Promise.logError(LOG, it) handleError(fastCgiRequest, notEmptyContent) } } } catch (e: Throwable) { LOG.error(e) handleError(fastCgiRequest, notEmptyContent) } } private fun handleError(fastCgiRequest: FastCgiRequest, content: ByteBuf?) { try { if (content != null && content.refCnt() != 0) { content.release() } } finally { val channel = requests.remove(fastCgiRequest.requestId) if (channel != null) { sendBadGateway(channel) } } } public fun allocateRequestId(channel: Channel): Int { var requestId = requestIdCounter.getAndIncrement() if (requestId >= java.lang.Short.MAX_VALUE) { requestIdCounter.set(0) requestId = requestIdCounter.getAndDecrement() } requests.put(requestId, channel) return requestId } fun responseReceived(id: Int, buffer: ByteBuf?) { val channel = requests.remove(id) if (channel == null || !channel.isActive) { buffer?.release() return } if (buffer == null) { Responses.sendStatus(HttpResponseStatus.BAD_GATEWAY, channel) return } val httpResponse = DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buffer) try { parseHeaders(httpResponse, buffer) Responses.addServer(httpResponse) if (!HttpUtil.isContentLengthSet(httpResponse)) { HttpUtil.setContentLength(httpResponse, buffer.readableBytes().toLong()) } } catch (e: Throwable) { buffer.release() try { LOG.error(e) } finally { Responses.sendStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR, channel) } return } channel.writeAndFlush(httpResponse) } }
apache-2.0
808f43cd461f83e8fd89f59bcdf4b614
29.330317
132
0.637869
4.584131
false
false
false
false
koma-im/koma
src/main/kotlin/koma/gui/view/window/chatroom/roominfo/about/RoomAliasView.kt
1
7464
package koma.gui.view.window.chatroom.roominfo.about import de.jensd.fx.glyphs.materialicons.MaterialIcon import de.jensd.fx.glyphs.materialicons.utils.MaterialIconFactory import javafx.beans.binding.Bindings import javafx.beans.property.SimpleBooleanProperty import javafx.beans.property.SimpleObjectProperty import javafx.beans.property.SimpleStringProperty import javafx.geometry.Pos import javafx.scene.control.* import javafx.scene.layout.Priority import javafx.stage.Stage import javafx.util.Callback import koma.gui.element.emoji.keyboard.NoSelectionModel import koma.gui.view.window.chatroom.roominfo.about.requests.requestAddRoomAlias import koma.gui.view.window.chatroom.roominfo.about.requests.requestSetRoomCanonicalAlias import koma.koma_app.appState import koma.matrix.UserId import koma.matrix.event.room_message.RoomEventType import koma.matrix.room.naming.RoomAlias import koma.matrix.room.naming.RoomId import koma.util.onFailure import kotlinx.coroutines.* import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.javafx.JavaFx import link.continuum.database.models.getChangeStateAllowed import link.continuum.desktop.database.RoomDataStorage import link.continuum.desktop.gui.* import link.continuum.desktop.util.getOrNull import mu.KotlinLogging import org.controlsfx.control.Notifications import java.util.concurrent.Callable private val logger = KotlinLogging.logger {} private typealias RoomAliasStr = String class RoomAliasForm(room: RoomId, user: UserId, dataStorage: RoomDataStorage ) { private val scope = MainScope() val root: VBox val stage = Stage().apply { setOnHiding { scope.cancel() } } init { val data = dataStorage.data val canEditCanonAlias = SimpleBooleanProperty(false) val canEdit = SimpleBooleanProperty(false) scope.launch { data.runOp { val d = this canEditCanonAlias.set(getChangeStateAllowed(d, room, user, RoomEventType.CanonAlias.toString())) canEdit.set(getChangeStateAllowed(d, room, user)) } } val canonAlias = SimpleStringProperty() dataStorage.latestCanonAlias.receiveUpdates(room).onEach { val n = it?.getOrNull() canonAlias.set(n) stage.title = "Update Aliases of $n" }.launchIn(scope) root = VBox(5.0).apply { text("Room Aliases") vbox() { spacing = 5.0 add(ListView<RoomAliasStr>().apply { val listView = this prefHeight = 200.0 selectionModel = NoSelectionModel() cellFactory = Callback<ListView<RoomAliasStr>, ListCell<RoomAliasStr>> { RoomAliasCell(room, canEditCanonAlias, canonAlias, canEdit) } VBox.setVgrow(this, Priority.ALWAYS) scope.launch { dataStorage.latestAliasList.receiveUpdates(room).collect { listView.items.setAll(it) } } }) hbox(5.0) { removeWhen(canEdit.not()) val field = TextField() field.promptText = "additional-alias" val servername = room.servername hbox { alignment = Pos.CENTER label("#") add(field) label(":") label(servername) } val getAlias = { "#${field.text}:$servername" } button("Add") { action { requestAddRoomAlias(room, getAlias()) } } } } } } } private fun deleteRoomAlias(room: RoomId, alias: RoomAliasStr?) { alias?:return val api = appState.apiClient api ?: return GlobalScope.launch { val result = api.deleteRoomAlias(alias) result.onFailure { val message = it.message launch(Dispatchers.JavaFx) { Notifications.create() .title("Failed to delete room alias $alias") .text("In room ${room}\n$message") .owner(JFX.primaryStage) .showWarning() } } } } class RoomAliasCell( private val room: RoomId, private val canonEditAllowed: SimpleBooleanProperty, private val canonicalAlias: SimpleStringProperty, private val editAllowedDef: SimpleBooleanProperty ): ListCell<RoomAliasStr>() { private val roomAlias = SimpleObjectProperty<RoomAliasStr>() private val cell = HBox(5.0) init { val text = roomAlias val isCanon = Bindings.createBooleanBinding(Callable { roomAlias.value == canonicalAlias.value }, roomAlias, canonicalAlias) val star = MaterialIconFactory.get().createIcon(MaterialIcon.STAR) val notstar = MaterialIconFactory.get().createIcon(MaterialIcon.STAR_BORDER) val deleteIcon = MaterialIconFactory.get().createIcon(MaterialIcon.DELETE) with(cell) { prefWidth = 1.0 minWidth = 1.0 alignment = Pos.CENTER_LEFT stackpane { add(Hyperlink().apply { graphic = notstar tooltip("Set as Canonical Alias") visibleWhen(cell.hoverProperty().and(canonEditAllowed)) setOnAction { roomAlias.get()?.also { requestSetRoomCanonicalAlias(room, RoomAlias( it)) } } }) add(Hyperlink().apply { graphic = star tooltip("Current Canonical Alias") removeWhen { isCanon.not() } }) } label { textProperty().bind(text) style = "-fx-font-weight: bold;" } contextMenu = ContextMenu().apply { item("Delete") { removeWhen(editAllowedDef.not()) action { deleteRoomAlias(room, roomAlias.value) } } item("Set Canonical") { removeWhen(canonEditAllowed.not()) action { roomAlias.get()?.let { requestSetRoomCanonicalAlias(room, RoomAlias(it)) } } } Unit } add(Hyperlink().apply { graphic = deleteIcon visibleWhen(cell.hoverProperty().and(editAllowedDef)) setOnAction { deleteRoomAlias(room, roomAlias.value) } }) } } override fun updateItem(item: RoomAliasStr?, empty: Boolean) { super.updateItem(item, empty) if (empty || item == null) { graphic = null return } roomAlias.set(item) graphic = cell } }
gpl-3.0
b186d01b0aa0d65ffc673950a1b377b7
35.768473
112
0.555868
5.10883
false
false
false
false
fossasia/rp15
app/src/main/java/org/fossasia/openevent/general/about/AboutEventViewModel.kt
1
1969
package org.fossasia.openevent.general.about import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.plusAssign import org.fossasia.openevent.general.utils.extensions.withDefaultSchedulers import org.fossasia.openevent.general.R import org.fossasia.openevent.general.common.SingleLiveEvent import org.fossasia.openevent.general.data.Resource import org.fossasia.openevent.general.event.Event import org.fossasia.openevent.general.event.EventService import timber.log.Timber class AboutEventViewModel(private val eventService: EventService, private val resource: Resource) : ViewModel() { private val compositeDisposable = CompositeDisposable() private val mutableProgressAboutEvent = MutableLiveData<Boolean>() val progressAboutEvent: LiveData<Boolean> = mutableProgressAboutEvent private val mutableEvent = MutableLiveData<Event>() val event: LiveData<Event> = mutableEvent private val mutableError = SingleLiveEvent<String>() val error: LiveData<String> = mutableError fun loadEvent(id: Long) { if (id == -1L) { mutableError.value = Resource().getString(R.string.error_fetching_event_message) return } compositeDisposable += eventService.getEvent(id) .withDefaultSchedulers() .doOnSubscribe { mutableProgressAboutEvent.value = true }.doFinally { mutableProgressAboutEvent.value = false }.subscribe({ eventList -> mutableEvent.value = eventList }, { mutableError.value = resource.getString(R.string.error_fetching_event_message) Timber.e(it, "Error fetching event %d", id) } ) } override fun onCleared() { super.onCleared() compositeDisposable.clear() } }
apache-2.0
6966e940d7fcd56c5f9bfcc53313c5ab
37.607843
113
0.708989
4.997462
false
false
false
false
fossasia/rp15
app/src/main/java/org/fossasia/openevent/general/ticket/TicketDetailsRecyclerAdapter.kt
1
1621
package org.fossasia.openevent.general.ticket import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import org.fossasia.openevent.general.R class TicketDetailsRecyclerAdapter : RecyclerView.Adapter<TicketDetailsViewHolder>() { private val tickets = ArrayList<Ticket>() private var eventCurrency: String? = null private var qty = ArrayList<Int>() private var donationsList = ArrayList<Float>() fun addAll(ticketList: List<Ticket>) { if (tickets.isNotEmpty()) this.tickets.clear() this.tickets.addAll(ticketList) notifyDataSetChanged() } fun setCurrency(currencyCode: String?) { eventCurrency = currencyCode } fun setDonations(donations: List<Float>) { if (donationsList.isNotEmpty()) donationsList.clear() donationsList.addAll(donations) notifyDataSetChanged() } fun setQuantity(ticketQuantities: List<Int>) { if (qty.isNotEmpty())qty.clear() qty.addAll(ticketQuantities) notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TicketDetailsViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_ticket_details, parent, false) return TicketDetailsViewHolder(view) } override fun onBindViewHolder(holder: TicketDetailsViewHolder, position: Int) { holder.bind(tickets[position], qty[position], donationsList[position], eventCurrency) } override fun getItemCount(): Int { return tickets.size } }
apache-2.0
d1839e97391edc8d150d20ae02d69af3
31.42
107
0.706354
4.698551
false
false
false
false
syrop/Wiktor-Navigator
navigator/src/main/kotlin/pl/org/seva/navigator/main/extension/Fragment.kt
1
2027
/* * Copyright (C) 2019 Wiktor Nizio * * 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/>. * * If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp */ package pl.org.seva.navigator.main.extension import android.content.SharedPreferences import androidx.annotation.IdRes import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import com.google.android.gms.maps.SupportMapFragment import org.kodein.di.LazyDelegate import pl.org.seva.navigator.R import pl.org.seva.navigator.navigation.MapHolder import kotlin.reflect.KProperty fun Fragment.nav(@IdRes resId: Int): Boolean { findNavController().navigate(resId) return true } fun Fragment.back() = findNavController().popBackStack() inline fun <reified R : ViewModel> Fragment.viewModel() = object : LazyDelegate<R> { override fun provideDelegate(receiver: Any?, prop: KProperty<Any?>) = lazy { ViewModelProvider([email protected]()).get(R::class.java) } } fun Fragment.createMapHolder(f: MapHolder.() -> Unit): MapHolder = MapHolder().apply(f).also { val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync { map -> it withMap map } } val Fragment.prefs: SharedPreferences get() = requireContext().prefs
gpl-3.0
5b9c48dcfe573f5156e5ad401636f3bc
37.245283
98
0.76813
4.136735
false
false
false
false