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
square/okio
okio/src/jvmTest/kotlin/okio/JvmSystemFileSystemTest.kt
1
1873
/* * Copyright (C) 2020 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okio import kotlinx.datetime.Clock import org.junit.Test import java.io.InterruptedIOException import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.fail /** * This test will run using [NioSystemFileSystem] by default. If [java.nio.file.Files] is not found * on the classpath, [JvmSystemFileSystem] will be use instead. */ class NioSystemFileSystemTest : AbstractFileSystemTest( clock = Clock.System, fileSystem = FileSystem.SYSTEM, windowsLimitations = Path.DIRECTORY_SEPARATOR == "\\", allowClobberingEmptyDirectories = Path.DIRECTORY_SEPARATOR == "\\", temporaryDirectory = FileSystem.SYSTEM_TEMPORARY_DIRECTORY ) class JvmSystemFileSystemTest : AbstractFileSystemTest( clock = Clock.System, fileSystem = JvmSystemFileSystem(), windowsLimitations = Path.DIRECTORY_SEPARATOR == "\\", allowClobberingEmptyDirectories = Path.DIRECTORY_SEPARATOR == "\\", temporaryDirectory = FileSystem.SYSTEM_TEMPORARY_DIRECTORY ) { @Test fun checkInterruptedBeforeDeleting() { Thread.currentThread().interrupt() try { fileSystem.delete(base) fail() } catch (expected: InterruptedIOException) { assertEquals("interrupted", expected.message) assertFalse(Thread.interrupted()) } } }
apache-2.0
03c3af098b7872bfc6b4f2b47c07e9ae
33.054545
99
0.746396
4.295872
false
true
false
false
androidx/androidx
compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/input/key/KeyInputModifier.kt
3
5784
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.input.key import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusModifier import androidx.compose.ui.focus.ModifierLocalParentFocusModifier import androidx.compose.ui.focus.findActiveFocusNode import androidx.compose.ui.focus.findLastKeyInputModifier import androidx.compose.ui.layout.LayoutCoordinates import androidx.compose.ui.layout.OnPlacedModifier import androidx.compose.ui.modifier.ModifierLocalConsumer import androidx.compose.ui.modifier.ModifierLocalProvider import androidx.compose.ui.modifier.ModifierLocalReadScope import androidx.compose.ui.modifier.ProvidableModifierLocal import androidx.compose.ui.modifier.modifierLocalOf import androidx.compose.ui.node.LayoutNode import androidx.compose.ui.node.NodeCoordinator import androidx.compose.ui.platform.debugInspectorInfo import androidx.compose.ui.platform.inspectable /** * Adding this [modifier][Modifier] to the [modifier][Modifier] parameter of a component will * allow it to intercept hardware key events when it (or one of its children) is focused. * * @param onKeyEvent This callback is invoked when the user interacts with the hardware keyboard. * While implementing this callback, return true to stop propagation of this event. If you return * false, the key event will be sent to this [onKeyEvent]'s parent. * * @sample androidx.compose.ui.samples.KeyEventSample */ fun Modifier.onKeyEvent(onKeyEvent: (KeyEvent) -> Boolean): Modifier = inspectable( inspectorInfo = debugInspectorInfo { name = "onKeyEvent" properties["onKeyEvent"] = onKeyEvent } ) { KeyInputModifier(onKeyEvent = onKeyEvent, onPreviewKeyEvent = null) } /** * Adding this [modifier][Modifier] to the [modifier][Modifier] parameter of a component will * allow it to intercept hardware key events when it (or one of its children) is focused. * * @param onPreviewKeyEvent This callback is invoked when the user interacts with the hardware * keyboard. It gives ancestors of a focused component the chance to intercept a [KeyEvent]. * Return true to stop propagation of this event. If you return false, the key event will be sent * to this [onPreviewKeyEvent]'s child. If none of the children consume the event, it will be * sent back up to the root [KeyInputModifier] using the onKeyEvent callback. * * @sample androidx.compose.ui.samples.KeyEventSample */ fun Modifier.onPreviewKeyEvent(onPreviewKeyEvent: (KeyEvent) -> Boolean): Modifier = inspectable( inspectorInfo = debugInspectorInfo { name = "onPreviewKeyEvent" properties["onPreviewKeyEvent"] = onPreviewKeyEvent } ) { KeyInputModifier(onKeyEvent = null, onPreviewKeyEvent = onPreviewKeyEvent) } /** * Used to build a tree of [KeyInputModifier]s. This contains the [KeyInputModifier] that is * higher in the layout tree. */ internal val ModifierLocalKeyInput = modifierLocalOf<KeyInputModifier?> { null } internal class KeyInputModifier( val onKeyEvent: ((KeyEvent) -> Boolean)?, val onPreviewKeyEvent: ((KeyEvent) -> Boolean)? ) : ModifierLocalConsumer, ModifierLocalProvider<KeyInputModifier?>, OnPlacedModifier { private var focusModifier: FocusModifier? = null var parent: KeyInputModifier? = null private set var layoutNode: LayoutNode? = null private set override val key: ProvidableModifierLocal<KeyInputModifier?> get() = ModifierLocalKeyInput override val value: KeyInputModifier get() = this fun processKeyInput(keyEvent: KeyEvent): Boolean { val activeKeyInputModifier = focusModifier ?.findActiveFocusNode() ?.findLastKeyInputModifier() ?: error("KeyEvent can't be processed because this key input node is not active.") val consumed = activeKeyInputModifier.propagatePreviewKeyEvent(keyEvent) return if (consumed) true else activeKeyInputModifier.propagateKeyEvent(keyEvent) } override fun onModifierLocalsUpdated(scope: ModifierLocalReadScope) = with(scope) { focusModifier?.keyInputChildren?.remove(this@KeyInputModifier) focusModifier = ModifierLocalParentFocusModifier.current focusModifier?.keyInputChildren?.add(this@KeyInputModifier) parent = ModifierLocalKeyInput.current } fun propagatePreviewKeyEvent(keyEvent: KeyEvent): Boolean { // We first propagate the preview key event to the parent. val consumed = parent?.propagatePreviewKeyEvent(keyEvent) if (consumed == true) return consumed // If none of the parents consumed the event, we attempt to consume it. return onPreviewKeyEvent?.invoke(keyEvent) ?: false } fun propagateKeyEvent(keyEvent: KeyEvent): Boolean { // We attempt to consume the key event first. val consumed = onKeyEvent?.invoke(keyEvent) if (consumed == true) return consumed // If the event is not consumed, we propagate it to the parent. return parent?.propagateKeyEvent(keyEvent) ?: false } override fun onPlaced(coordinates: LayoutCoordinates) { layoutNode = (coordinates as NodeCoordinator).layoutNode } }
apache-2.0
0fdd5b98f44932e7485894f33f64d3f3
42.164179
97
0.749827
4.638332
false
false
false
false
pokk/SSFM
app/src/main/kotlin/taiwan/no1/app/ssfm/misc/widgets/SideMenu.kt
1
13289
package taiwan.no1.app.ssfm.misc.widgets import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.app.Activity import android.content.Context import android.content.res.Configuration import android.graphics.Rect import android.support.annotation.DrawableRes import android.support.annotation.LayoutRes import android.util.DisplayMetrics import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.view.animation.AnimationUtils import android.widget.FrameLayout import com.devrapid.kotlinknifer.WeakRef import com.devrapid.kotlinknifer.animatorListener import kotlinx.android.synthetic.main.custom_menu_scroll_view.view.ll_menu import kotlinx.android.synthetic.main.custom_menu_view_container.view.iv_background import kotlinx.android.synthetic.main.custom_menu_view_container.view.iv_shadow import kotlinx.android.synthetic.main.custom_menu_view_container.view.rl_menu_holder import org.jetbrains.anko.sdk25.coroutines.onClick import taiwan.no1.app.ssfm.R import java.lang.ref.WeakReference /** * * @author jieyi * @since 6/7/17 */ class SideMenu(context: Context, @LayoutRes resMenu: Int = -1) : FrameLayout(context) { companion object { private const val PRESSED_MOVE_HORIZONTAL = 2 private const val PRESSED_MOVE_VERTICAL = 3 private const val PRESSED_DOWN = 4 private const val PRESSED_DONE = 5 private const val ROTATE_Y_ANGLE = 10f private const val ANIMATION_DURATION = 250L } //region Variables // ** Public variables lateinit var vScrollMenu: View var isOpened = false private set var menuListener = MenuListener() private set var menuItems = mutableListOf<WeakReference<MenuItem>>() set(value) { field = value rebuildMenu() } var mScaleValue = 0.75f var mUse3D = false lateinit private var activity: Activity lateinit private var viewActivity: TouchDisableView lateinit private var viewDecor: ViewGroup // ** Private variables private val llMenu by lazy { vScrollMenu.ll_menu } private val displayMetrics by lazy { DisplayMetrics() } private val screenHeight by lazy { displayMetrics.let { activity.windowManager.defaultDisplay.getMetrics(it); it.heightPixels } } private val screenWidth by lazy { displayMetrics.let { activity.windowManager.defaultDisplay.getMetrics(it); it.widthPixels } } private val animationListener = animatorListener { onAnimationStart { if ([email protected]) { [email protected]([email protected]) [email protected]._openMenu?.invoke() } } onAnimationEnd { if ([email protected]) { [email protected] = true [email protected] { if ([email protected]) [email protected]() } } else { [email protected] = false [email protected](null) [email protected]([email protected]) [email protected]._closeMenu?.invoke() } } } private var ignoredViews = mutableListOf<View>() private var shadowAdjustScaleX = 0f private var shadowAdjustScaleY = 0f private var lastRawX = 0f private var lastActionDownX = 0f private var lastActionDownY = 0f private var pressedState = PRESSED_DOWN private var isInIgnoredView = false //endregion init { (context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater).let { it.inflate(R.layout.custom_menu_view_container, this) vScrollMenu = it.inflate(if (0 <= resMenu) resMenu else R.layout.custom_menu_scroll_view, this, false) rl_menu_holder.addView(vScrollMenu) } } override fun dispatchTouchEvent(ev: android.view.MotionEvent): Boolean { val currentActivityScaleX = viewActivity.scaleX if (1.0f == currentActivityScaleX) { setScaleDirection() } when (ev.action) { MotionEvent.ACTION_DOWN -> { lastActionDownX = ev.x lastActionDownY = ev.y isInIgnoredView = isInIgnoredView(ev) && !isOpened pressedState = PRESSED_DOWN } MotionEvent.ACTION_MOVE -> run action_move@ { if ((PRESSED_DOWN != pressedState && PRESSED_MOVE_HORIZONTAL != pressedState) || isInIgnoredView) { return@action_move } val (xOffset, yOffset) = Pair((ev.x - lastActionDownX).toInt(), (ev.y - lastActionDownY).toInt()) if (PRESSED_DOWN == pressedState) { if (25 < yOffset || -25 > yOffset) { pressedState = PRESSED_MOVE_VERTICAL return@action_move } if (30 < xOffset || -30 > xOffset) { pressedState = PRESSED_MOVE_HORIZONTAL ev.action = MotionEvent.ACTION_CANCEL } } else if (PRESSED_MOVE_HORIZONTAL == pressedState) { if (0.95f > currentActivityScaleX) { showScrollViewMenu(vScrollMenu) } val targetScale = getTargetScale(ev.rawX) if (mUse3D) { val angle = (-1 * ROTATE_Y_ANGLE) * ((1 - targetScale) * 2).toInt() viewActivity.rotationY = angle iv_shadow.scaleX = targetScale - shadowAdjustScaleX iv_shadow.scaleY = targetScale - shadowAdjustScaleY } else { iv_shadow.scaleX = targetScale + shadowAdjustScaleX iv_shadow.scaleY = targetScale + shadowAdjustScaleY } viewActivity.scaleX = targetScale viewActivity.scaleY = targetScale vScrollMenu.alpha = (1 - targetScale) * 4f lastRawX = ev.rawX return true } } MotionEvent.ACTION_UP -> run action_up@ { if (isInIgnoredView || PRESSED_MOVE_HORIZONTAL != pressedState) { return@action_up } pressedState = PRESSED_DONE if (isOpened) { if (0.79f < currentActivityScaleX) closeMenu() else openMenu() } else { if (0.93f > currentActivityScaleX) openMenu() else closeMenu() } } } lastRawX = ev.rawX return super.dispatchTouchEvent(ev) } override fun onDetachedFromWindow() { super.onDetachedFromWindow() menuItems.clear() } fun attachActivity(activity: Activity) { initValue(activity) setShadowAdjustScaleXByOrientation() viewDecor.addView(this, 0) } fun openMenu() { setScaleDirection() isOpened = true // Scale down for the activity. buildScaleDownAnimation(viewActivity, mScaleValue, mScaleValue).also { val scaleDown_shadow = buildScaleDownAnimation(iv_shadow, mScaleValue + shadowAdjustScaleX, mScaleValue + shadowAdjustScaleY) val alpha_menu = buildMenuAnimation(vScrollMenu, 1.0f) it.addListener(animationListener) it.playTogether(scaleDown_shadow, alpha_menu) }.start() } fun closeMenu() { isOpened = false // Scale up for the activity. buildScaleUpAnimation(viewActivity, 1.0f, 1.0f).also { val scaleUp_shadow = buildScaleUpAnimation(iv_shadow, 1.0f, 1.0f) val alpha_menu = buildMenuAnimation(vScrollMenu, 0.0f) it.addListener(animationListener) it.playTogether(scaleUp_shadow, alpha_menu) }.start() } fun setMenuBackground(@DrawableRes resBackground: Int) = iv_background.setImageResource( resBackground) fun setShadowVisible(isVisible: Boolean) = iv_shadow.setBackgroundResource(if (isVisible) R.drawable.shadow else 0) fun addMenuItem(menuItem: MenuItem) { menuItems.add(WeakReference(menuItem)) llMenu.addView(menuItem) } fun addIgnoredView(v: View) = ignoredViews.add(v) fun removeIgnoredView(v: View) = ignoredViews.remove(v) fun clearIgnoredViewList() = ignoredViews.clear() private fun initValue(activity: Activity) { this.activity = activity viewDecor = activity.window.decorView as ViewGroup viewActivity = TouchDisableView(this.activity) val mContent = viewDecor.getChildAt(0) viewDecor.removeViewAt(0) viewActivity.content = mContent // TODO: 6/9/17 I cant bring the viewActivity to the front. addView(viewActivity) (vScrollMenu.parent as ViewGroup).removeView(vScrollMenu) } private fun setShadowAdjustScaleXByOrientation() = when (resources.configuration.orientation) { Configuration.ORIENTATION_LANDSCAPE -> { shadowAdjustScaleX = 0.034f shadowAdjustScaleY = 0.12f } Configuration.ORIENTATION_PORTRAIT -> { shadowAdjustScaleX = 0.05f shadowAdjustScaleY = 0.06f } else -> TODO("noop") } private fun rebuildMenu() { llMenu.removeAllViews() menuItems.forEach { llMenu.addView(it.get()) } } private fun setScaleDirection() { val (pivotX, pivotY) = Pair(screenWidth * 2.85f, screenHeight * 0.5f) viewActivity.pivotX = pivotX viewActivity.pivotY = pivotY iv_shadow.pivotX = pivotX * 1.1f iv_shadow.pivotY = pivotY * 1.1f } private fun buildScaleDownAnimation(target: View, targetScaleX: Float, targetScaleY: Float): AnimatorSet = // scale down animation AnimatorSet().also { it.playTogether(ObjectAnimator.ofFloat(target, "scaleX", targetScaleX), ObjectAnimator.ofFloat(target, "scaleY", targetScaleY)) if (mUse3D) { it.playTogether(ObjectAnimator.ofFloat(target, "rotationY", -1 * ROTATE_Y_ANGLE)) } it.interpolator = AnimationUtils.loadInterpolator(activity, android.R.anim.decelerate_interpolator) it.duration = ANIMATION_DURATION } private fun buildScaleUpAnimation(target: View, targetScaleX: Float, targetScaleY: Float): AnimatorSet = // scale animation AnimatorSet().also { it.playTogether(ObjectAnimator.ofFloat(target, "scaleX", targetScaleX), ObjectAnimator.ofFloat(target, "scaleY", targetScaleY)) if (mUse3D) { it.playTogether(ObjectAnimator.ofFloat(target, "rotationY", 0f)) } it.duration = ANIMATION_DURATION } private fun buildMenuAnimation(target: View, alpha: Float): AnimatorSet = // alpha animation AnimatorSet().also { it.playTogether(ObjectAnimator.ofFloat(target, "alpha", alpha)) it.duration = ANIMATION_DURATION } private fun isInIgnoredView(ev: MotionEvent): Boolean { val rect = Rect() ignoredViews.forEach { it.getGlobalVisibleRect(rect) if (rect.contains(ev.x.toInt(), ev.y.toInt())) { return true } } return false } private fun getTargetScale(currentRawX: Float): Float { val scaleFloatX = (currentRawX - lastRawX) / screenWidth * 0.5f var targetScale = viewActivity.scaleX - scaleFloatX targetScale = if (1.0f < targetScale) 1.0f else targetScale targetScale = if (0.5f > targetScale) 0.5f else targetScale return targetScale } private fun showScrollViewMenu(scrollViewMenu: View) = scrollViewMenu.parent ?: let { addView(scrollViewMenu) } private fun hideScrollViewMenu(scrollViewMenu: View) = scrollViewMenu.parent ?: let { removeView(scrollViewMenu) } /** * Menu Listener. */ class MenuListener { var _openMenu by WeakRef({}) var _closeMenu by WeakRef({}) internal fun openMenu(open: () -> Unit): MenuListener = also { it._openMenu = open } internal fun closeMenu(close: () -> Unit): MenuListener = also { it._closeMenu = close } } }
apache-2.0
9ad71ccbe7df2063b5c5490b91c03188
35.311475
119
0.594702
4.735923
false
false
false
false
GunoH/intellij-community
plugins/repository-search/src/test/kotlin/org/jetbrains/idea/reposearch/DependencySearchServiceTest.kt
2
2442
package org.jetbrains.idea.reposearch import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.testFramework.ExtensionTestUtil import com.intellij.testFramework.LightPlatformTestCase import com.intellij.util.WaitFor import junit.framework.TestCase import org.jetbrains.concurrency.isPending import java.util.concurrent.CompletableFuture import java.util.function.Consumer class DependencySearchServiceTest : LightPlatformTestCase() { private lateinit var dependencySearchService: DependencySearchService override fun setUp() { super.setUp() dependencySearchService = DependencySearchService(project) Disposer.register(testRootDisposable, dependencySearchService) } fun testShouldReturnDataFromCache() { var requests = 0 val testProvider = object : TestSearchProvider() { override fun isLocal() = false override fun fulltextSearch(searchString: String): CompletableFuture<List<RepositoryArtifactData>> = CompletableFuture.supplyAsync { requests++ listOf(RepositoryArtifactData { searchString }) } } ExtensionTestUtil.maskExtensions(DependencySearchService.EP_NAME, listOf(DependencySearchProvidersFactory { listOf(testProvider) }), testRootDisposable, false) val searchParameters = SearchParameters(true, false) val promise = dependencySearchService.fulltextSearch("something", searchParameters) {} object : WaitFor(500) { override fun condition() = !promise.isPending } assertTrue(promise.isSucceeded) TestCase.assertEquals(1, requests) dependencySearchService.fulltextSearch("something", searchParameters) {} TestCase.assertEquals(1, requests) val promise1 = dependencySearchService.fulltextSearch("something", SearchParameters(false, false)) {} object : WaitFor(500) { override fun condition() = !promise1.isPending } assertTrue(promise1.isSucceeded) TestCase.assertEquals(2, requests) } open class TestSearchProvider : DependencySearchProvider { override fun fulltextSearch(searchString: String): CompletableFuture<List<RepositoryArtifactData>> { TODO("Not yet implemented") } override fun suggestPrefix(groupId: String?, artifactId: String?): CompletableFuture<List<RepositoryArtifactData>> { TODO("Not yet implemented") } override fun isLocal(): Boolean { TODO("Not yet implemented") } } }
apache-2.0
e038b5982ff092bed3c2448bf7798828
32.930556
163
0.76208
5.262931
false
true
false
false
GunoH/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/target/MavenRuntimeTargetConfiguration.kt
10
2103
// 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.jetbrains.idea.maven.execution.target import com.intellij.execution.target.LanguageRuntimeConfiguration import com.intellij.execution.target.LanguageRuntimeType import com.intellij.execution.target.TargetEnvironment import com.intellij.execution.target.TargetEnvironmentRequest import com.intellij.openapi.components.BaseState import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.extensions.ExtensionPointName import java.nio.file.Path class MavenRuntimeTargetConfiguration : LanguageRuntimeConfiguration(MavenRuntimeType.TYPE_ID), PersistentStateComponent<MavenRuntimeTargetConfiguration.MyState> { var homePath: String = "" var versionString: String = "" override fun getState() = MyState().also { it.homePath = this.homePath it.versionString = this.versionString } override fun loadState(state: MyState) { this.homePath = state.homePath ?: "" this.versionString = state.versionString ?: "" } class MyState : BaseState() { var homePath by string() var versionString by string() } companion object { fun createUploadRoot(mavenRuntimeConfiguration: MavenRuntimeTargetConfiguration?, targetEnvironmentRequest: TargetEnvironmentRequest, volumeDescriptor: LanguageRuntimeType.VolumeDescriptor, localRootPath: Path): TargetEnvironment.UploadRoot { return EP_NAME.computeSafeIfAny { it.createUploadRoot(mavenRuntimeConfiguration, targetEnvironmentRequest, volumeDescriptor, localRootPath) } ?: mavenRuntimeConfiguration?.createUploadRoot(volumeDescriptor, localRootPath) ?: TargetEnvironment.UploadRoot(localRootPath, TargetEnvironment.TargetPath.Temporary()) } private val EP_NAME = ExtensionPointName.create<TargetConfigurationMavenExtension>("org.jetbrains.idea.maven.targetConfigurationExtension") } }
apache-2.0
7c2cd94841712200a666c42842ae2151
44.73913
143
0.757489
5.392308
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/KotlinCompletionContributor.kt
1
21959
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.completion import com.intellij.codeInsight.completion.* import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementDecorator import com.intellij.openapi.editor.Document import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.patterns.PlatformPatterns import com.intellij.patterns.PsiJavaPatterns.elementType import com.intellij.patterns.PsiJavaPatterns.psiElement import com.intellij.psi.* import com.intellij.psi.search.PsiElementProcessor import com.intellij.psi.tree.TokenSet import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.elementType import com.intellij.util.ProcessingContext import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.completion.smart.SmartCompletion import org.jetbrains.kotlin.idea.completion.smart.SmartCompletionSession import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.bindingContextUtil.getReferenceTargets import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import kotlin.math.max class KotlinCompletionContributor : CompletionContributor() { private val AFTER_NUMBER_LITERAL = psiElement().afterLeafSkipping( psiElement().withText(""), psiElement().withElementType(elementType().oneOf(KtTokens.FLOAT_LITERAL, KtTokens.INTEGER_LITERAL)) ) private val AFTER_INTEGER_LITERAL_AND_DOT = psiElement().afterLeafSkipping( psiElement().withText("."), psiElement().withElementType(elementType().oneOf(KtTokens.INTEGER_LITERAL)) ) companion object { // add '$' to ignore context after the caret const val DEFAULT_DUMMY_IDENTIFIER: String = CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED + "$" } init { val provider = object : CompletionProvider<CompletionParameters>() { override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) { performCompletion(parameters, result) } } extend(CompletionType.BASIC, PlatformPatterns.psiElement(), provider) extend(CompletionType.SMART, PlatformPatterns.psiElement(), provider) } override fun beforeCompletion(context: CompletionInitializationContext) { val psiFile = context.file if (psiFile !is KtFile) return // this code will make replacement offset "modified" and prevents altering it by the code in CompletionProgressIndicator context.replacementOffset = context.replacementOffset val offset = context.startOffset val tokenBefore = psiFile.findElementAt(max(0, offset - 1)) if (offset > 0 && tokenBefore!!.node.elementType == KtTokens.REGULAR_STRING_PART && tokenBefore.text.startsWith(".")) { val prev = tokenBefore.parent.prevSibling if (prev != null && prev is KtSimpleNameStringTemplateEntry) { val expression = prev.expression if (expression != null) { val prefix = tokenBefore.text.substring(0, offset - tokenBefore.startOffset) context.dummyIdentifier = "{" + expression.text + prefix + CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED + "}" context.offsetMap.addOffset(CompletionInitializationContext.START_OFFSET, expression.startOffset) return } } } context.dummyIdentifier = when { context.completionType == CompletionType.SMART -> DEFAULT_DUMMY_IDENTIFIER PackageDirectiveCompletion.ACTIVATION_PATTERN.accepts(tokenBefore) -> PackageDirectiveCompletion.DUMMY_IDENTIFIER isInClassHeader(tokenBefore) -> CompletionUtilCore.DUMMY_IDENTIFIER // do not add '$' to not interrupt class declaration parsing isInUnclosedSuperQualifier(tokenBefore) -> CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED + ">" isInSimpleStringTemplate(tokenBefore) -> CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED else -> specialLambdaSignatureDummyIdentifier(tokenBefore) ?: specialExtensionReceiverDummyIdentifier(tokenBefore) ?: specialInTypeArgsDummyIdentifier(tokenBefore) ?: specialInArgumentListDummyIdentifier(tokenBefore) ?: specialInBinaryExpressionDummyIdentifier(tokenBefore) ?: DEFAULT_DUMMY_IDENTIFIER } val tokenAt = psiFile.findElementAt(max(0, offset)) if (tokenAt != null) { /* do not use parent expression if we are at the end of line - it's probably parsed incorrectly */ if (context.completionType == CompletionType.SMART && !isAtEndOfLine(offset, context.editor.document)) { var parent = tokenAt.parent if (parent is KtExpression && parent !is KtBlockExpression) { // search expression to be replaced - go up while we are the first child of parent expression var expression: KtExpression = parent parent = expression.parent while (parent is KtExpression && parent.getFirstChild() == expression) { expression = parent parent = expression.parent } val suggestedReplacementOffset = replacementOffsetByExpression(expression) if (suggestedReplacementOffset > context.replacementOffset) { context.replacementOffset = suggestedReplacementOffset } context.offsetMap.addOffset(SmartCompletion.OLD_ARGUMENTS_REPLACEMENT_OFFSET, expression.endOffset) val argumentList = (expression.parent as? KtValueArgument)?.parent as? KtValueArgumentList if (argumentList != null) { context.offsetMap.addOffset( SmartCompletion.MULTIPLE_ARGUMENTS_REPLACEMENT_OFFSET, argumentList.rightParenthesis?.textRange?.startOffset ?: argumentList.endOffset ) } } } // IDENTIFIER when 'f<caret>oo: Foo' // COLON when 'foo<caret>: Foo' if (tokenAt.node.elementType == KtTokens.IDENTIFIER || tokenAt.node.elementType == KtTokens.COLON) { val parameter = tokenAt.parent as? KtParameter if (parameter != null) { context.offsetMap.addOffset(VariableOrParameterNameWithTypeCompletion.REPLACEMENT_OFFSET, parameter.endOffset) } } } } private fun replacementOffsetByExpression(expression: KtExpression): Int { when (expression) { is KtCallExpression -> { val calleeExpression = expression.calleeExpression if (calleeExpression != null) { return calleeExpression.textRange!!.endOffset } } is KtQualifiedExpression -> { val selector = expression.selectorExpression if (selector != null) { return replacementOffsetByExpression(selector) } } } return expression.textRange!!.endOffset } private fun isInClassHeader(tokenBefore: PsiElement?): Boolean { val classOrObject = tokenBefore?.parents?.firstIsInstanceOrNull<KtClassOrObject>() ?: return false val name = classOrObject.nameIdentifier ?: return false val headerEnd = classOrObject.body?.startOffset ?: classOrObject.endOffset val offset = tokenBefore.startOffset return name.endOffset <= offset && offset <= headerEnd } private fun specialLambdaSignatureDummyIdentifier(tokenBefore: PsiElement?): String? { var leaf = tokenBefore while (leaf is PsiWhiteSpace || leaf is PsiComment) { leaf = leaf.prevLeaf(true) } val lambda = leaf?.parents?.firstOrNull { it is KtFunctionLiteral } ?: return null val lambdaChild = leaf.parents.takeWhile { it != lambda }.lastOrNull() return if (lambdaChild is KtParameterList) CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED else null } private val declarationKeywords = TokenSet.create(KtTokens.FUN_KEYWORD, KtTokens.VAL_KEYWORD, KtTokens.VAR_KEYWORD) private val declarationTokens = TokenSet.orSet( TokenSet.create( KtTokens.IDENTIFIER, KtTokens.LT, KtTokens.GT, KtTokens.COMMA, KtTokens.DOT, KtTokens.QUEST, KtTokens.COLON, KtTokens.IN_KEYWORD, KtTokens.OUT_KEYWORD, KtTokens.LPAR, KtTokens.RPAR, KtTokens.ARROW, TokenType.ERROR_ELEMENT ), KtTokens.WHITE_SPACE_OR_COMMENT_BIT_SET ) private fun specialExtensionReceiverDummyIdentifier(tokenBefore: PsiElement?): String? { var token = tokenBefore ?: return null var ltCount = 0 var gtCount = 0 val builder = StringBuilder() while (true) { val tokenType = token.node!!.elementType if (tokenType in declarationKeywords) { val balance = ltCount - gtCount if (balance < 0) return null builder.append(token.text!!.reversed()) builder.reverse() var tail = "X" + ">".repeat(balance) + ".f" if (tokenType == KtTokens.FUN_KEYWORD) { tail += "()" } builder.append(tail) val text = builder.toString() val file = KtPsiFactory(tokenBefore.project).createFile(text) val declaration = file.declarations.singleOrNull() ?: return null if (declaration.textLength != text.length) return null val containsErrorElement = !PsiTreeUtil.processElements(file, PsiElementProcessor { it !is PsiErrorElement }) return if (containsErrorElement) null else "$tail$" } if (tokenType !in declarationTokens) return null if (tokenType == KtTokens.LT) ltCount++ if (tokenType == KtTokens.GT) gtCount++ builder.append(token.text!!.reversed()) token = PsiTreeUtil.prevLeaf(token) ?: return null } } private fun performCompletion(parameters: CompletionParameters, result: CompletionResultSet) { val position = parameters.position val parametersOriginFile = parameters.originalFile if (position.containingFile !is KtFile || parametersOriginFile !is KtFile) return if (position.node.elementType == KtTokens.LONG_TEMPLATE_ENTRY_START) { val expression = (position.parent as? KtBlockStringTemplateEntry)?.expression if (expression is KtDotQualifiedExpression) { val correctedPosition = (expression.selectorExpression as? KtNameReferenceExpression)?.firstChild if (correctedPosition != null) { // Workaround for KT-16848 // ex: // expression: some.IntellijIdeaRulezzz // correctedOffset: ^ // expression: some.funcIntellijIdeaRulezzz // correctedOffset ^ val correctedOffset = correctedPosition.endOffset - CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED.length val correctedParameters = parameters.withPosition(correctedPosition, correctedOffset) doComplete(correctedParameters, result) { wrapLookupElementForStringTemplateAfterDotCompletion(it) } return } } } doComplete(parameters, result) } private fun doComplete( parameters: CompletionParameters, result: CompletionResultSet, lookupElementPostProcessor: ((LookupElement) -> LookupElement)? = null ) { val position = parameters.position if (position.getNonStrictParentOfType<PsiComment>() != null) { // don't stop here, allow other contributors to run return } if (shouldSuppressCompletion(parameters, result.prefixMatcher)) { result.stopHere() return } if (PackageDirectiveCompletion.perform(parameters, result)) { result.stopHere() return } for (extension in KotlinCompletionExtension.EP_NAME.extensionList) { if (extension.perform(parameters, result)) return } fun addPostProcessor(session: CompletionSession) { if (lookupElementPostProcessor != null) { session.addLookupElementPostProcessor(lookupElementPostProcessor) } } result.restartCompletionWhenNothingMatches() val configuration = CompletionSessionConfiguration(parameters) if (parameters.completionType == CompletionType.BASIC) { val session = BasicCompletionSession(configuration, parameters, result) addPostProcessor(session) if (parameters.isAutoPopup && session.shouldDisableAutoPopup()) { result.stopHere() return } val somethingAdded = session.complete() if (!somethingAdded && parameters.invocationCount < 2) { // Rerun completion if nothing was found val newConfiguration = CompletionSessionConfiguration( useBetterPrefixMatcherForNonImportedClasses = false, nonAccessibleDeclarations = false, javaGettersAndSetters = true, javaClassesNotToBeUsed = false, staticMembers = parameters.invocationCount > 0, dataClassComponentFunctions = true ) val newSession = BasicCompletionSession(newConfiguration, parameters, result) addPostProcessor(newSession) newSession.complete() } } else { val session = SmartCompletionSession(configuration, parameters, result) addPostProcessor(session) session.complete() } } private fun wrapLookupElementForStringTemplateAfterDotCompletion(lookupElement: LookupElement): LookupElement = LookupElementDecorator.withDelegateInsertHandler(lookupElement) { context, element -> val document = context.document val startOffset = context.startOffset val psiDocumentManager = PsiDocumentManager.getInstance(context.project) psiDocumentManager.commitDocument(document) val token = getToken(context.file, document.charsSequence, startOffset) val nameRef = token.parent as KtNameReferenceExpression document.insertString(nameRef.startOffset, "{") val tailOffset = context.tailOffset document.insertString(tailOffset, "}") context.tailOffset = tailOffset element.handleInsert(context) } private fun shouldSuppressCompletion(parameters: CompletionParameters, prefixMatcher: PrefixMatcher): Boolean { val position = parameters.position val invocationCount = parameters.invocationCount // no completion inside number literals if (AFTER_NUMBER_LITERAL.accepts(position)) return true // no completion auto-popup after integer and dot if (invocationCount == 0 && prefixMatcher.prefix.isEmpty() && AFTER_INTEGER_LITERAL_AND_DOT.accepts(position)) return true return false } private fun isAtEndOfLine(offset: Int, document: Document): Boolean { var i = offset val chars = document.charsSequence while (i < chars.length) { val c = chars[i] if (c == '\n') return true if (!Character.isWhitespace(c)) return false i++ } return true } private fun specialInTypeArgsDummyIdentifier(tokenBefore: PsiElement?): String? { if (tokenBefore == null) return null if (tokenBefore.getParentOfType<KtTypeArgumentList>(true) != null) { // already parsed inside type argument list return CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED // do not insert '$' to not break type argument list parsing } val pair = unclosedTypeArgListNameAndBalance(tokenBefore) ?: return null val (nameToken, balance) = pair assert(balance > 0) val nameRef = nameToken.parent as? KtNameReferenceExpression ?: return null val bindingContext = nameRef.getResolutionFacade().analyze(nameRef, BodyResolveMode.PARTIAL) val targets = nameRef.getReferenceTargets(bindingContext) return if (targets.isNotEmpty() && targets.all { it is FunctionDescriptor || it is ClassDescriptor && it.kind == ClassKind.CLASS }) { CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED + ">".repeat(balance) + "$" } else { null } } private fun unclosedTypeArgListNameAndBalance(tokenBefore: PsiElement): Pair<PsiElement, Int>? { val nameToken = findCallNameTokenIfInTypeArgs(tokenBefore) ?: return null val pair = unclosedTypeArgListNameAndBalance(nameToken) return if (pair == null) { Pair(nameToken, 1) } else { Pair(pair.first, pair.second + 1) } } private val callTypeArgsTokens = TokenSet.orSet( TokenSet.create( KtTokens.IDENTIFIER, KtTokens.LT, KtTokens.GT, KtTokens.COMMA, KtTokens.DOT, KtTokens.QUEST, KtTokens.COLON, KtTokens.LPAR, KtTokens.RPAR, KtTokens.ARROW ), KtTokens.WHITE_SPACE_OR_COMMENT_BIT_SET ) // if the leaf could be located inside type argument list of a call (if parsed properly) // then it returns the call name reference this type argument list would belong to private fun findCallNameTokenIfInTypeArgs(leaf: PsiElement): PsiElement? { var current = leaf while (true) { val tokenType = current.node!!.elementType if (tokenType !in callTypeArgsTokens) return null if (tokenType == KtTokens.LT) { val nameToken = current.prevLeaf(skipEmptyElements = true) ?: return null if (nameToken.node!!.elementType != KtTokens.IDENTIFIER) return null return nameToken } if (tokenType == KtTokens.GT) { // pass nested type argument list val prev = current.prevLeaf(skipEmptyElements = true) ?: return null val typeRef = findCallNameTokenIfInTypeArgs(prev) ?: return null current = typeRef continue } current = current.prevLeaf(skipEmptyElements = true) ?: return null } } private fun specialInArgumentListDummyIdentifier(tokenBefore: PsiElement?): String? { // If we insert $ in the argument list of a delegation specifier, this will break parsing // and the following block will not be attached as a body to the constructor. Therefore // we need to use a regular identifier. val argumentList = tokenBefore?.getNonStrictParentOfType<KtValueArgumentList>() ?: return null if (argumentList.parent is KtConstructorDelegationCall) return CompletionUtil.DUMMY_IDENTIFIER_TRIMMED return null } private fun specialInBinaryExpressionDummyIdentifier(tokenBefore: PsiElement?): String? { if (tokenBefore.elementType == KtTokens.IDENTIFIER && tokenBefore?.context?.context is KtBinaryExpression) return CompletionUtilCore.DUMMY_IDENTIFIER return null } private fun isInUnclosedSuperQualifier(tokenBefore: PsiElement?): Boolean { if (tokenBefore == null) return false val tokensToSkip = TokenSet.orSet(TokenSet.create(KtTokens.IDENTIFIER, KtTokens.DOT), KtTokens.WHITE_SPACE_OR_COMMENT_BIT_SET) val tokens = generateSequence(tokenBefore) { it.prevLeaf() } val ltToken = tokens.firstOrNull { it.node.elementType !in tokensToSkip } ?: return false if (ltToken.node.elementType != KtTokens.LT) return false val superToken = ltToken.prevLeaf { it !is PsiWhiteSpace && it !is PsiComment } return superToken?.node?.elementType == KtTokens.SUPER_KEYWORD } private fun isInSimpleStringTemplate(tokenBefore: PsiElement?): Boolean { return tokenBefore?.parents?.firstIsInstanceOrNull<KtStringTemplateExpression>()?.isPlain() ?: false } } abstract class KotlinCompletionExtension { abstract fun perform(parameters: CompletionParameters, result: CompletionResultSet): Boolean companion object { val EP_NAME: ExtensionPointName<KotlinCompletionExtension> = ExtensionPointName.create("org.jetbrains.kotlin.completionExtension") } } private fun getToken(file: PsiFile, charsSequence: CharSequence, startOffset: Int): PsiElement { assert(startOffset > 1 && charsSequence[startOffset - 1] == '.') val token = file.findElementAt(startOffset - 2)!! return if (token.node.elementType == KtTokens.IDENTIFIER || token.node.elementType == KtTokens.THIS_KEYWORD) token else getToken(file, charsSequence, token.startOffset + 1) }
apache-2.0
f52a5ecfcb1b13ea3f81ceaa6ad52ad3
44.465839
158
0.653035
5.450236
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/ast/TypeParameters.kt
6
2355
// 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.PsiTypeParameter import com.intellij.psi.PsiTypeParameterList import org.jetbrains.kotlin.j2k.CodeBuilder import org.jetbrains.kotlin.j2k.Converter import org.jetbrains.kotlin.j2k.append import org.jetbrains.kotlin.j2k.buildList class TypeParameter(val name: Identifier, val extendsTypes: List<Type>) : Element() { fun hasWhere(): Boolean = extendsTypes.size > 1 fun whereToKotlin(builder: CodeBuilder) { if (hasWhere()) { builder append name append " : " append extendsTypes[1] } } override fun generateCode(builder: CodeBuilder) { builder append name if (extendsTypes.isNotEmpty()) { builder append " : " append extendsTypes[0] } } } class TypeParameterList(val parameters: List<TypeParameter>) : Element() { override fun generateCode(builder: CodeBuilder) { if (parameters.isNotEmpty()) builder.append(parameters, ", ", "<", ">") } fun appendWhere(builder: CodeBuilder): CodeBuilder { if (hasWhere()) { builder.buildList(generators = parameters.map { { it.whereToKotlin(builder) } }, separator = ", ", prefix = " where ", suffix = "") } return builder } override val isEmpty: Boolean get() = parameters.isEmpty() private fun hasWhere(): Boolean = parameters.any { it.hasWhere() } companion object { val Empty = TypeParameterList(listOf()) } } private fun Converter.convertTypeParameter(typeParameter: PsiTypeParameter): TypeParameter { return TypeParameter(typeParameter.declarationIdentifier(), typeParameter.extendsListTypes.map { typeConverter.convertType(it) }).assignPrototype(typeParameter) } fun Converter.convertTypeParameterList(typeParameterList: PsiTypeParameterList?): TypeParameterList { return if (typeParameterList != null) TypeParameterList(typeParameterList.typeParameters.toList().map { convertTypeParameter(it) }).assignPrototype(typeParameterList) else TypeParameterList.Empty }
apache-2.0
8c8bd5be2261c259b7fc84724fc3b017
35.796875
158
0.673461
4.916493
false
false
false
false
Helabs/generator-he-kotlin-mvp
app/templates/app_arch_comp/src/main/kotlin/data/local/db/RepoDao.kt
1
2504
package <%= appPackage %>.data.local.db import android.arch.persistence.room.Dao /** * Interface for database access on Repo related operations. */ @Dao abstract class RepoDao// @Insert(onConflict = OnConflictStrategy.REPLACE) // public abstract void insert(Repo... repos); // // @Insert(onConflict = OnConflictStrategy.REPLACE) // public abstract void insertContributors(List<Contributor> contributors); // // @Insert(onConflict = OnConflictStrategy.REPLACE) // public abstract void insertRepos(List<Repo> repositories); // // @Insert(onConflict = OnConflictStrategy.IGNORE) // public abstract long createRepoIfNotExists(Repo repo); // // @Query("SELECT * FROM repo WHERE owner_login = :login AND name = :name") // public abstract LiveData<Repo> load(String login, String name); // // @SuppressWarnings(RoomWarnings.CURSOR_MISMATCH) // @Query("SELECT login, avatarUrl, repoName, repoOwner, contributions FROM contributor " // + "WHERE repoName = :name AND repoOwner = :owner " // + "ORDER BY contributions DESC") // public abstract LiveData<List<Contributor>> loadContributors(String owner, String name); // // @Query("SELECT * FROM Repo " // + "WHERE owner_login = :owner " // + "ORDER BY stars DESC") // public abstract LiveData<List<Repo>> loadRepositories(String owner); // // @Insert(onConflict = OnConflictStrategy.REPLACE) // public abstract void insert(RepoSearchResult result); // // @Query("SELECT * FROM RepoSearchResult WHERE query = :query") // public abstract LiveData<RepoSearchResult> search(String query); // // public LiveData<List<Repo>> loadOrdered(List<Integer> repoIds) { // SparseIntArray order = new SparseIntArray(); // int index = 0; // for (Integer repoId : repoIds) { // order.put(repoId, index++); // } // return Transformations.map(loadById(repoIds), repositories -> { // Collections.sort(repositories, (r1, r2) -> { // int pos1 = order.get(r1.id); // int pos2 = order.get(r2.id); // return pos1 - pos2; // }); // return repositories; // }); // } // // @Query("SELECT * FROM Repo WHERE id in (:repoIds)") // protected abstract LiveData<List<Repo>> loadById(List<Integer> repoIds); // // @Query("SELECT * FROM RepoSearchResult WHERE query = :query") // public abstract RepoSearchResult findSearchResult(String query);
mit
18f029f38f2a963062451780c4022ac2
38.746032
94
0.647764
4
false
false
false
false
Jamefrus/LibBinder
src/main/kotlin/su/jfdev/libbinder/items/Library.kt
1
1611
package su.jfdev.libbinder.items import su.jfdev.libbinder.IllegalFormatBindException import su.jfdev.libbinder.util.mapOfNotNull import su.jfdev.libbinder.util.nullIfEmpty import su.jfdev.libbinder.util.nullable data class Library(val properties: Map<String, String>) { constructor(group: String, name: String, version: String, classifier: String?, extension: String?) : this(mapOfNotNull("group" to group, "name" to name, "version" to version, "classifier" to classifier, "extension" to extension)) val group: String by properties val name: String by properties val version: String by properties val classifier: String? by properties.nullable() val extension: String? by properties.nullable() val id: String get() = buildString { append("$group:$name:$version") if (classifier != null) append(":$classifier") if (extension != null) append("@$extension") } companion object { fun from(id: String): Library { val withoutExtension = id.substringBefore("@") val extension = id.substringAfter("@", "").nullIfEmpty() val otherParts = withoutExtension.split(':') if (otherParts.size < 3) throw IllegalFormatBindException("Format of bind declaration is unreadable") val (group, name, version) = otherParts val classifier = otherParts.getOrNull(3) return Library(group, name, version, classifier, extension) } @Suppress("NOTHING_TO_INLINE", "unused") inline fun from(map: Map<String, String>) = Library(map) } }
mit
eb992a018a1e4acd834a96d5228b5f00
40.333333
113
0.667287
4.438017
false
false
false
false
smmribeiro/intellij-community
platform/external-system-impl/src/com/intellij/openapi/externalSystem/autoimport/changes/VirtualFilesChangesProvider.kt
4
1563
// 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.externalSystem.autoimport.AsyncFileChangeListenerBase import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ModificationType.EXTERNAL import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ModificationType.INTERNAL import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.util.EventDispatcher class VirtualFilesChangesProvider(private val isIgnoreInternalChanges: Boolean) : FilesChangesProvider, AsyncFileChangeListenerBase() { private val eventDispatcher = EventDispatcher.create(FilesChangesListener::class.java) override fun subscribe(listener: FilesChangesListener, parentDisposable: Disposable) { eventDispatcher.addListener(listener, parentDisposable) } override val processRecursively = false override fun init() = eventDispatcher.multicaster.init() override fun apply() = eventDispatcher.multicaster.apply() override fun isRelevant(file: VirtualFile, event: VFileEvent) = !isIgnoreInternalChanges || !event.isFromSave override fun updateFile(file: VirtualFile, event: VFileEvent) { val modificationType = if (event.isFromRefresh) EXTERNAL else INTERNAL eventDispatcher.multicaster.onFileChange(file.path, file.modificationStamp, modificationType) } }
apache-2.0
c5d6d7b95bcb723b31a36151eac10379
47.875
140
0.826615
4.977707
false
false
false
false
insogroup/utils
src/main/kotlin/com/github/insanusmokrassar/utils/IOC/strategies/FixedExecutorServiceStrategy.kt
1
1699
package com.github.insanusmokrassar.utils.IOC.strategies import com.github.insanusmokrassar.iobjectk.interfaces.IObject import com.github.insanusmokrassar.utils.IOC.exceptions.ResolveStrategyException import com.github.insanusmokrassar.utils.IOC.interfaces.IOCStrategy import java.util.HashMap import java.util.concurrent.ExecutorService import java.util.concurrent.Executors class FixedExecutorServiceStrategy : IOCStrategy { protected var executorServices: MutableMap<String, ExecutorService> = HashMap() protected var defaultThreadsCount: Int? = 1 /** * @param settings * <pre> * { * "default" : number,//this number will used for keys which will not set in settings * "taskName" : number, * "taskName2" : number, * "taskName3" : number, * ... * } * </pre> */ constructor(settings: IObject<Any>) { val keys = settings.keys() for (key in keys) { if (key == "default") { defaultThreadsCount = settings.get<Int>(key) continue } executorServices.put(key, Executors.newFixedThreadPool(settings.get<Int>(key))) } } @Throws(ResolveStrategyException::class) override fun <T> getInstance(vararg args: Any): T { val targetTaskName = args[0] as String if (executorServices.containsKey(targetTaskName)) { return executorServices[targetTaskName]!! as T } val executorService = Executors.newFixedThreadPool(defaultThreadsCount!!) executorServices.put(targetTaskName, executorService) return executorService as T } }
mit
f81eed85931b42e609c6934b81e3920b
32.98
97
0.650383
4.530667
false
false
false
false
TachiWeb/TachiWeb-Server
Tachiyomi-App/src/main/java/eu/kanade/tachiyomi/source/online/russian/Mangachan.kt
1
11333
package eu.kanade.tachiyomi.source.online.russian import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.model.* import eu.kanade.tachiyomi.source.online.ParsedHttpSource import eu.kanade.tachiyomi.util.asJsoup import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element import java.text.SimpleDateFormat import java.util.* class Mangachan : ParsedHttpSource() { override val id: Long = 7 override val name = "Mangachan" override val baseUrl = "http://mangachan.me" override val lang = "ru" override val supportsLatest = true override fun popularMangaRequest(page: Int): Request = GET("$baseUrl/mostfavorites?offset=${20 * (page - 1)}", headers) override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { var pageNum = 1 when { page < 1 -> pageNum = 1 page >= 1 -> pageNum = page } val url = if (query.isNotEmpty()) { "$baseUrl/?do=search&subaction=search&story=$query&search_start=$pageNum" } else { var genres = "" var order = "" var statusParam = true var status = "" for (filter in if (filters.isEmpty()) getFilterList() else filters) { when (filter) { is GenreList -> { filter.state.forEach { f -> if (!f.isIgnored()) { genres += (if (f.isExcluded()) "-" else "") + f.id + '+' } } } is OrderBy -> { if (filter.state!!.ascending && filter.state!!.index == 0) { statusParam = false } } is Status -> status = arrayOf("", "all_done", "end", "ongoing", "new_ch")[filter.state] } } if (genres.isNotEmpty()) { for (filter in filters) { when (filter) { is OrderBy -> { order = if (filter.state!!.ascending) { arrayOf("", "&n=favasc", "&n=abcdesc", "&n=chasc")[filter.state!!.index] } else { arrayOf("&n=dateasc", "&n=favdesc", "&n=abcasc", "&n=chdesc")[filter.state!!.index] } } } } if (statusParam) { "$baseUrl/tags/${genres.dropLast(1)}$order?offset=${20 * (pageNum - 1)}&status=$status" } else { "$baseUrl/tags/$status/${genres.dropLast(1)}/$order?offset=${20 * (pageNum - 1)}" } } else { for (filter in filters) { when (filter) { is OrderBy -> { order = if (filter.state!!.ascending) { arrayOf("manga/new", "manga/new&n=favasc", "manga/new&n=abcdesc", "manga/new&n=chasc")[filter.state!!.index] } else { arrayOf("manga/new&n=dateasc", "mostfavorites", "catalog", "sortch")[filter.state!!.index] } } } } if (statusParam) { "$baseUrl/$order?offset=${20 * (pageNum - 1)}&status=$status" } else { "$baseUrl/$order/$status?offset=${20 * (pageNum - 1)}" } } } return GET(url, headers) } override fun latestUpdatesRequest(page: Int): Request = GET("$baseUrl/newestch?page=$page") override fun popularMangaSelector() = "div.content_row" override fun latestUpdatesSelector() = "ul.area_rightNews li" override fun searchMangaSelector() = popularMangaSelector() override fun popularMangaFromElement(element: Element): SManga { val manga = SManga.create() manga.thumbnail_url = element.select("div.manga_images img").first().attr("src") element.select("h2 > a").first().let { manga.setUrlWithoutDomain(it.attr("href")) manga.title = it.text() } return manga } override fun latestUpdatesFromElement(element: Element): SManga { val manga = SManga.create() element.select("a:nth-child(1)").first().let { manga.setUrlWithoutDomain(it.attr("href")) manga.title = it.text() } return manga } override fun searchMangaFromElement(element: Element): SManga = popularMangaFromElement(element) override fun popularMangaNextPageSelector() = "a:contains(Вперед)" override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector() override fun searchMangaNextPageSelector() = "a:contains(Далее)" private fun searchGenresNextPageSelector() = popularMangaNextPageSelector() override fun searchMangaParse(response: Response): MangasPage { val document = response.asJsoup() var hasNextPage = false val mangas = document.select(searchMangaSelector()).map { element -> searchMangaFromElement(element) } val nextSearchPage = document.select(searchMangaNextPageSelector()) if (nextSearchPage.isNotEmpty()) { val query = document.select("input#searchinput").first().attr("value") val pageNum = nextSearchPage.let { selector -> val onClick = selector.attr("onclick") onClick?.split("""\\d+""") } nextSearchPage.attr("href", "$baseUrl/?do=search&subaction=search&story=$query&search_start=$pageNum") hasNextPage = true } val nextGenresPage = document.select(searchGenresNextPageSelector()) if (nextGenresPage.isNotEmpty()) { hasNextPage = true } return MangasPage(mangas, hasNextPage) } override fun mangaDetailsParse(document: Document): SManga { val infoElement = document.select("table.mangatitle").first() val descElement = document.select("div#description").first() val imgElement = document.select("img#cover").first() val manga = SManga.create() manga.author = infoElement.select("tr:eq(2) > td:eq(1)").text() manga.genre = infoElement.select("tr:eq(5) > td:eq(1)").text() manga.status = parseStatus(infoElement.select("tr:eq(4) > td:eq(1)").text()) manga.description = descElement.textNodes().first().text() manga.thumbnail_url = imgElement.attr("src") return manga } private fun parseStatus(element: String): Int = when { element.contains("перевод завершен") -> SManga.COMPLETED element.contains("перевод продолжается") -> SManga.ONGOING else -> SManga.UNKNOWN } override fun chapterListSelector() = "table.table_cha tr:gt(1)" override fun chapterFromElement(element: Element): SChapter { val urlElement = element.select("a").first() val chapter = SChapter.create() chapter.setUrlWithoutDomain(urlElement.attr("href")) chapter.name = urlElement.text() chapter.date_upload = element.select("div.date").first()?.text()?.let { SimpleDateFormat("yyyy-MM-dd", Locale.US).parse(it).time } ?: 0 return chapter } override fun pageListParse(response: Response): List<Page> { val html = response.body()!!.string() val beginIndex = html.indexOf("fullimg\":[") + 10 val endIndex = html.indexOf(",]", beginIndex) val trimmedHtml = html.substring(beginIndex, endIndex).replace("\"", "") val pageUrls = trimmedHtml.split(',') return pageUrls.mapIndexed { i, url -> Page(i, "", url) } } override fun pageListParse(document: Document): List<Page> { throw Exception("Not used") } override fun imageUrlParse(document: Document) = "" private class GenreList(genres: List<Genre>) : Filter.Group<Genre>("Тэги", genres) private class Genre(name: String, val id: String = name.replace(' ', '_')) : Filter.TriState(name) private class Status : Filter.Select<String>("Статус", arrayOf("Все", "Перевод завершен", "Выпуск завершен", "Онгоинг", "Новые главы")) private class OrderBy : Filter.Sort("Сортировка", arrayOf("Дата", "Популярность", "Имя", "Главы"), Filter.Sort.Selection(1, false)) override fun getFilterList() = FilterList( Status(), OrderBy(), GenreList(getGenreList()) ) /* [...document.querySelectorAll("li.sidetag > a:nth-child(1)")] * .map(el => `Genre("${el.getAttribute('href').substr(6)}")`).join(',\n') * on http://mangachan.me/ */ private fun getGenreList() = listOf( Genre("18_плюс"), Genre("bdsm"), Genre("арт"), Genre("боевик"), Genre("боевые_искусства"), Genre("вампиры"), Genre("веб"), Genre("гарем"), Genre("гендерная_интрига"), Genre("героическое_фэнтези"), Genre("детектив"), Genre("дзёсэй"), Genre("додзинси"), Genre("драма"), Genre("игра"), Genre("инцест"), Genre("искусство"), Genre("история"), Genre("киберпанк"), Genre("кодомо"), Genre("комедия"), Genre("литРПГ"), Genre("махо-сёдзё"), Genre("меха"), Genre("мистика"), Genre("музыка"), Genre("научная_фантастика"), Genre("повседневность"), Genre("постапокалиптика"), Genre("приключения"), Genre("психология"), Genre("романтика"), Genre("самурайский_боевик"), Genre("сборник"), Genre("сверхъестественное"), Genre("сказка"), Genre("спорт"), Genre("супергерои"), Genre("сэйнэн"), Genre("сёдзё"), Genre("сёдзё-ай"), Genre("сёнэн"), Genre("сёнэн-ай"), Genre("тентакли"), Genre("трагедия"), Genre("триллер"), Genre("ужасы"), Genre("фантастика"), Genre("фурри"), Genre("фэнтези"), Genre("школа"), Genre("эротика"), Genre("юри"), Genre("яой"), Genre("ёнкома") ) }
apache-2.0
f1072aca491b1ea43f90a12c2cfb3d05
36.127586
140
0.533018
4.429042
false
false
false
false
egf2-guide/guide-android
app/src/main/kotlin/com/eigengraph/egf2/guide/ui/anko/ForgotUI.kt
1
676
package com.eigengraph.egf2.guide.ui.anko import android.view.View import com.eigengraph.egf2.guide.R import com.eigengraph.egf2.guide.ui.fragment.LoginFragment import org.jetbrains.anko.* import org.jetbrains.anko.appcompat.v7.tintedEditText import org.jetbrains.anko.design.textInputLayout class ForgotUI { fun bind(parent: LoginFragment): View = parent.context.UI { scrollView { verticalLayout { padding = dip(16) textInputLayout { parent.email = tintedEditText { hint = resources.getString(R.string.hint_email) singleLine = true } }.lparams(width = matchParent, height = wrapContent) } } }.view }
mit
7764aaddbd7da17e9aeb512fc1663256
25.038462
58
0.707101
3.595745
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/utils/ThemeHelper.kt
1
2566
package ch.rmy.android.http_shortcuts.utils import android.content.Context import android.graphics.Color import androidx.core.content.res.use import ch.rmy.android.framework.extensions.color import ch.rmy.android.framework.extensions.isDarkThemeEnabled import ch.rmy.android.http_shortcuts.R class ThemeHelper(context: Context) { val theme: Int val transparentTheme: Int val statusBarColor: Int private val isDarkThemeEnabled: Boolean = context.isDarkThemeEnabled() init { val themeId = Settings(context).theme theme = when (themeId) { Settings.THEME_GREEN -> R.style.LightThemeAlt1 Settings.THEME_RED -> R.style.LightThemeAlt2 Settings.THEME_PURPLE -> R.style.LightThemeAlt3 Settings.THEME_GREY -> R.style.LightThemeAlt4 Settings.THEME_ORANGE -> R.style.LightThemeAlt5 Settings.THEME_INDIGO -> R.style.LightThemeAlt6 else -> R.style.LightThemeAlt0 } transparentTheme = when (themeId) { Settings.THEME_GREEN -> R.style.LightThemeTransparentAlt1 Settings.THEME_RED -> R.style.LightThemeTransparentAlt2 Settings.THEME_PURPLE -> R.style.LightThemeTransparentAlt3 Settings.THEME_GREY -> R.style.LightThemeTransparentAlt4 Settings.THEME_ORANGE -> R.style.LightThemeTransparentAlt5 Settings.THEME_INDIGO -> R.style.LightThemeTransparentAlt6 else -> R.style.LightThemeTransparentAlt0 } statusBarColor = if (isDarkThemeEnabled) { Color.BLACK } else { when (themeId) { Settings.THEME_GREEN -> color(context, R.color.primary_dark_alt1) Settings.THEME_RED -> color(context, R.color.primary_dark_alt2) Settings.THEME_PURPLE -> color(context, R.color.primary_dark_alt3) Settings.THEME_GREY -> color(context, R.color.primary_dark_alt4) Settings.THEME_ORANGE -> color(context, R.color.primary_dark_alt5) Settings.THEME_INDIGO -> color(context, R.color.primary_dark_alt6) else -> color(context, R.color.primary_dark_alt0) } } } fun getPrimaryColor(context: Context) = if (isDarkThemeEnabled) { color(context, R.color.primary_color) } else { context.obtainStyledAttributes(intArrayOf(R.attr.colorPrimary)).use { attributes -> attributes.getColor(0, color(context, R.color.primary_alt0)) } } }
mit
93bcf1b429ea2bc448bae75914a12ffe
41.065574
95
0.645362
4.158833
false
false
false
false
intrigus/jtransc
jtransc-core/src/com/jtransc/ast/dependency/genStaticInitOrder.kt
2
4987
package com.jtransc.ast.dependency import com.jtransc.ast.* import com.jtransc.ast.treeshaking.GetTemplateReferencesRefs import com.jtransc.ast.treeshaking.TRefConfig import com.jtransc.ast.treeshaking.TRefReason import com.jtransc.gen.TargetName import com.jtransc.plugin.JTranscPluginGroup import com.jtransc.text.INDENTS //const val SI_TRACE = true const val SI_TRACE = false // @TODO: We should evaluate actual AST in order to do this properly (to handle branches properly) // @TODO: Before modifying this file, please provide tests to avoid future regressions and better // @TODO: work on this implementation fun genStaticInitOrder(program: AstProgram, plugins: JTranscPluginGroup) { //val classes = LinkedHashSet<AstType.REF>() //val processed = LinkedHashSet<AstRef>() val targetName = program.injector.get<TargetName>() val mainClass = program[program.entrypoint] val CLASS = program["java.lang.Class".fqname] val inits = program.staticInitsSorted val obj = object { val visited = hashSetOf<Any>() val capturedClass = LinkedHashMap<AstClass, Int>() fun getClassLockCount(clazz: AstClass): Int { return capturedClass.getOrPut(clazz) { 0 }; } fun lockClass(clazz: AstClass) { capturedClass[clazz] = getClassLockCount(clazz) + 1 } fun unlockClass(clazz: AstClass, depth: Int) { capturedClass[clazz] = getClassLockCount(clazz) - 1 if (capturedClass[clazz]!! <= 0) { if (SI_TRACE) println("${INDENTS[depth]}Added: ${clazz.ref}") inits += clazz.ref } } fun visitMethod(method: AstMethod?, depth: Int) { if (method == null) return if (!visited.add(method)) return val clazz = method.containingClass // Totally ignore this class since it references all classes! // @TODO: Think about this some more if (clazz.fqname == "j.ProgramReflection") return if (clazz.fqname == "java.util.ServiceLoader") return lockClass(clazz) if (SI_TRACE) println("${INDENTS[depth]}Appeared method $method [") val refs = if (method.hasDependenciesInBody(targetName)) { //method.bodyDependencies.allSortedRefsStaticInit AstDependencyAnalyzer.analyze(program, method.body, method.name, config = AstDependencyAnalyzer.Config( AstDependencyAnalyzer.Reason.STATIC, methodHandler = { expr, da -> plugins.onStaticInitHandleMethodCall(program, expr, method.body, da) } )).allSortedRefsStaticInit } else { GetTemplateReferencesRefs(program, method.annotationsList.getBodiesForTarget(targetName).map { it.value }.joinToString { "\n" }, clazz.name, config = TRefConfig(reason = TRefReason.STATIC)) } for (ref in refs) { if (ref is AstMemberRef) { lockClass(program[ref.containingClass]) } if (ref is AstType.REF) { lockClass(program[ref]!!) } // First visit static constructor if (ref is AstMethodRef) { visitMethod(program[ref.containingClass].staticConstructor, depth + 1) } // Then visit methods when (ref) { is AstType.REF -> { val scons = program[ref]?.staticConstructor //println(">>>>>>>>>>>>>>> : $ref ($scons)") visitMethod(CLASS.staticConstructor, depth + 1) //println("Added: ${method.containingClass.ref}") //inits += clazz.ref if (scons != null) visitMethod(scons, depth + 1) //println("<<<<<<<<<<<<<<<") } is AstMethodRef -> { visitMethod(program[ref], depth + 1) } } if (ref is AstType.REF) { unlockClass(program[ref]!!, depth) } if (ref is AstMemberRef) { unlockClass(program[ref.containingClass], depth) } } //if ("Easings" in clazz.fqname) println(INDENTS[depth] + "/${clazz.fqname}") unlockClass(clazz, depth) if (SI_TRACE) println("${INDENTS[depth]}] Disappeared method $method") } fun visitClass(clazz: AstClass) { if (!visited.add(clazz)) return if (SI_TRACE) println("Appeared class $clazz") lockClass(clazz) // Parent classes are loaded before loading this class if (clazz.extending != null) visitClass(program[clazz.extending]) // Later, the static constructor is executed (let's find references without taking branches into account) visitMethod(clazz.staticConstructor, 0) unlockClass(clazz, 0) } } // ~~~~~~~~~~~~~~~~~~~~~~~~~~ Should be added ProgramReflection first because getClass created static constructor and request Class // @NOTE: We can't visit ProgramReflection since we don't know the order of execution //obj.visitClass(program[ProgramReflection::class.java.fqname]) // Also should be added different charsets. We don't see them directly because they added as services //for (clazz in program.classes) // for (ancestor in clazz.ancestors) // if(ancestor.name == JTranscCharset::class.java.fqname) // obj.visitClass(program[clazz.name]) obj.visitClass(mainClass) for (clazz in program.classes) obj.visitClass(clazz) // Classes without extra static requirements for (clazz in program.classes) inits += clazz.ref }
apache-2.0
a365924508145b47f1d5e0e8394d442d
30.974359
193
0.698616
3.694074
false
false
false
false
android/uamp
automotive/src/main/java/com/example/android/uamp/automotive/QrCodeSignInFragment.kt
2
2357
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.uamp.automotive import android.os.Bundle import android.text.method.LinkMovementMethod import android.view.View import androidx.core.content.ContextCompat.getDrawable import androidx.core.text.HtmlCompat import androidx.fragment.app.Fragment import com.bumptech.glide.Glide import com.example.android.uamp.automotive.databinding.QrSignInBinding /** * Fragment that is used to facilitate QR code sign-in. Users scan a QR code rendered by this * fragment with their phones, which performs the authentication required for sign-in * * <p>This screen serves as a demo for UI best practices for QR code sign in. Sign in implementation * will be app specific and is not included. */ class QrCodeSignInFragment : Fragment(R.layout.qr_sign_in) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val binding = QrSignInBinding.bind(view) binding.toolbar.setNavigationOnClickListener { requireActivity().supportFragmentManager.popBackStack() } binding.appIcon.setImageDrawable(getDrawable(requireContext(), R.drawable.aural_logo)) binding.primaryMessage.text = getString(R.string.qr_sign_in_primary_text) binding.secondaryMessage.text = getString(R.string.qr_sign_in_secondary_text) // Links in footer text should be clickable. binding.footer.text = HtmlCompat.fromHtml( requireContext().getString(R.string.sign_in_footer), HtmlCompat.FROM_HTML_MODE_LEGACY ) binding.footer.movementMethod = LinkMovementMethod.getInstance() Glide.with(this).load(getString(R.string.qr_code_url)).into(binding.qrCode) } }
apache-2.0
ead99b4ea8c6fa6c4209ffdbccca4bc9
39.637931
100
0.743318
4.277677
false
false
false
false
gam2046/UtilsClass
kotlin/ReflectionHelper.kt
1
1903
/** * get the `Class` of string exp * @param classLoader load the class which `ClassLoader` will be used. null for defaults */ fun <T> String.toClassObject(classLoader: ClassLoader? = null): Class<T> { return if (classLoader == null) { Class.forName(this) } else { classLoader.loadClass(this) } as Class<T> } /** * create an instance of the `Class` * @param argsTypes the type lists for constructor, put empty array if there is no params * @param argsValues the value lists for constructor, put empty array if there is no params * @return return the instance of `Class` */ fun <T> Class<T>.newInstance(argsTypes: Array<Class<out Any>>, argsValues: Array<out Any>): T { val constructor = this.getConstructor(*argsTypes) return constructor.newInstance(*argsValues) } /** * invoke method * * T is the ClassType * R is the method returns type * @param invoker the method of instance, null for static method * @param methodName the name of method which you want to invoke * @param argsTypes the type lists for method, put empty array if there is no params * @param argsValues the value lists for method, put empty array if there is no params * @return return value for the method */ fun <T, R> Class<T>.invokeMethod(invoker: T? = null, methodName: String, argsTypes: Array<Class<out Any>>, argsValues: Array<out Any>): R { val method = this.getMethod(methodName, *argsTypes) method.isAccessible = true return method.invoke(invoker, argsValues) as R } /** * get field value * T is the ClassType * R is the method returns type * @param invoker the field of instance, null for static field * @param fieldName the name of field * @return field value */ fun <T, R> Class<T>.queryField(invoker: T? = null, fieldName: String): R { val field = this.getField(fieldName) field.isAccessible = true return field.get(invoker) as R }
gpl-3.0
df4de2d914a43fc23174f3175edcb04a
34.90566
139
0.705202
3.806
false
false
false
false
nsnikhil/Notes
app/src/main/java/com/nrs/nsnik/notes/view/adapters/CheckListAdapter.kt
1
5929
/* * Notes Copyright (C) 2018 Nikhil Soni * This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. * This is free software, and you are welcome to redistribute it * under certain conditions; type `show c' for details. * * The hypothetical commands `show w' and `show c' should show the appropriate * parts of the General Public License. Of course, your program's commands * might be different; for a GUI interface, you would use an "about box". * * You should also get your employer (if you work as a programmer) or school, * if any, to sign a "copyright disclaimer" for the program, if necessary. * For more information on this, and how to apply and follow the GNU GPL, see * <http://www.gnu.org/licenses/>. * * The GNU General Public License does not permit incorporating your program * into proprietary programs. If your program is a subroutine library, you * may consider it more useful to permit linking proprietary applications with * the library. If this is what you want to do, use the GNU Lesser General * Public License instead of this License. But first, please read * <http://www.gnu.org/philosophy/why-not-lgpl.html>. */ package com.nrs.nsnik.notes.view.adapters import android.content.Context import android.graphics.Paint import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.EditorInfo import android.view.inputmethod.InputMethodManager import android.widget.CheckBox import android.widget.EditText import android.widget.ImageView import android.widget.TextView import androidx.core.content.ContextCompat import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.jakewharton.rxbinding2.view.RxView import com.jakewharton.rxbinding2.widget.RxCompoundButton import com.jakewharton.rxbinding2.widget.RxTextView import com.nrs.nsnik.notes.R import com.nrs.nsnik.notes.model.CheckListObject import com.nrs.nsnik.notes.view.adapters.diffUtil.CheckListDiffUtil import com.nrs.nsnik.notes.view.listeners.AdapterType import com.nrs.nsnik.notes.view.listeners.OnAddClickListener import com.nrs.nsnik.notes.view.listeners.OnItemRemoveListener import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.single_check_list_item.view.* import java.util.concurrent.TimeUnit class CheckListAdapter(private val mOnAddClickListener: OnAddClickListener, private val onItemRemoveListener: OnItemRemoveListener) : ListAdapter<CheckListObject, CheckListAdapter.MyViewHolder>(CheckListDiffUtil()) { private val compositeDisposable: CompositeDisposable = CompositeDisposable() private lateinit var context: Context override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { context = parent.context return MyViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.single_check_list_item, parent, false)) } override fun onBindViewHolder(holder: MyViewHolder, position: Int) { val checkList = getItem(position) holder.text.setText(checkList.text) holder.checkBox.isChecked = checkList.done if (holder.text.text.toString().isNotEmpty()) modifyText(holder.text, checkList.done) if (position == itemCount - 1) setFocus(holder.text) } private fun setFocus(editText: EditText) { editText.isFocusable = true editText.isFocusableInTouchMode = true editText.requestFocus() val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager? imm!!.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT) } private fun modifyText(textView: TextView, done: Boolean) { textView.apply { paintFlags = if (done) textView.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG else textView.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv() if (done) textView.setTextColor(ContextCompat.getColor(context, R.color.grey)) else textView.setTextColor(ContextCompat.getColor(context, R.color.colorAccent)) } } private fun cleanUp() { compositeDisposable.clear() compositeDisposable.dispose() } override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) { super.onDetachedFromRecyclerView(recyclerView) cleanUp() } inner class MyViewHolder internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView) { val checkBox: CheckBox = itemView.checkListTicker val text: EditText = itemView.checkListItem private val remove: ImageView = itemView.checkListRemove init { compositeDisposable.addAll( RxTextView.textChanges(text).debounce(500, TimeUnit.MILLISECONDS).subscribe { if (adapterPosition != RecyclerView.NO_POSITION) { val newContent: String = it.toString() getItem(adapterPosition).text = newContent } }, RxTextView.editorActions(text).subscribe { if (it == EditorInfo.IME_ACTION_NEXT) mOnAddClickListener.addClickListener() }, RxCompoundButton.checkedChanges(checkBox).subscribe { if (adapterPosition != RecyclerView.NO_POSITION) { val value: Boolean = it getItem(adapterPosition).done = value modifyText(text, value) } }, RxView.clicks(remove).subscribe { if (adapterPosition != RecyclerView.NO_POSITION) onItemRemoveListener.onItemRemoved(adapterPosition, AdapterType.CHECKLIST_ADAPTER) } ) } } }
gpl-3.0
5212fd73cdbede2cf8d3511b9649d2da
43.916667
216
0.699612
4.808597
false
false
false
false
jonnyzzz/TeamCity.Node
server/src/main/java/com/jonnyzzz/teamcity/plugins/node/server/JsRunTypeBase.kt
1
2611
/* * Copyright 2013-2015 Eugene Petrenko * * 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.jonnyzzz.teamcity.plugins.node.server import com.jonnyzzz.teamcity.plugins.node.common.isEmptyOrSpaces import jetbrains.buildServer.serverSide.InvalidProperty import jetbrains.buildServer.serverSide.PropertiesProcessor import com.jonnyzzz.teamcity.plugins.node.common.NodeBean /** * Created by Eugene Petrenko ([email protected]) * Date: 15.01.13 22:06 */ abstract class JsRunTypeBase : RunTypeBase() { protected val bean : NodeBean = NodeBean() abstract override fun getType(): String abstract override fun getDisplayName(): String abstract override fun getDescription(): String override fun getRunnerPropertiesProcessor(): PropertiesProcessor { val that = this; return object : PropertiesProcessor { override fun process(p0: Map<String, String>?): MutableCollection<InvalidProperty>? { if (p0 == null) return arrayListOf() return that.validateParameters(p0) } } } protected open fun validateParameters(parameters: Map<String, String>): MutableCollection<InvalidProperty> { val result = arrayListOf<InvalidProperty>() val mode = bean.findExecutionMode(parameters) if (mode == null) { result.add(InvalidProperty(bean.executionModeKey, "Execution Mode must be selected")) } else { val content = parameters[mode.parameter] if (content.isEmptyOrSpaces()) { result.add(InvalidProperty(mode.parameter, "${mode.description} should not be empty")) } } return result; } override fun describeParameters(parameters: Map<String, String>): String { val builder = StringBuilder() val mode = bean.findExecutionMode(parameters) if (mode != null) { builder.append("Execute: ${mode.description}\n") if (mode == bean.executionModeFile) { builder.append("File: ${parameters[bean.executionModeFile.parameter]}") } } return builder.toString() } override fun getDefaultRunnerProperties(): MutableMap<String, String>? = hashMapOf() }
apache-2.0
83172391b51eed4dde47ceb0ea0b3896
32.909091
110
0.723478
4.448041
false
false
false
false
joseph-roque/BowlingCompanion
app/src/main/java/ca/josephroque/bowlingcompanion/settings/SettingsActivity.kt
1
1419
package ca.josephroque.bowlingcompanion.settings import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.MenuItem import ca.josephroque.bowlingcompanion.R import kotlinx.android.synthetic.main.activity_navigation.toolbar as toolbar /** * Base activity to change user settings. */ class SettingsActivity : AppCompatActivity() { // MARK: Lifecycle functions override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setTheme(R.style.SettingTheme) setContentView(R.layout.activity_settings) setupToolbar() if (savedInstanceState == null) { val preferenceFragment = SettingsFragment.newInstance() val ft = supportFragmentManager.beginTransaction() ft.add(R.id.pref_container, preferenceFragment) ft.commit() } } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { onBackPressed() return true } return super.onOptionsItemSelected(item) } // MARK: Private functions private fun setupToolbar() { setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowHomeEnabled(true) supportActionBar?.setTitle(R.string.title_activity_settings) } }
mit
bd9cc9bd318637c2af5c1b1f1936b2d1
29.191489
76
0.693446
5.16
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-food-bukkit/src/main/kotlin/com/rpkit/food/bukkit/listener/PlayerFishListener.kt
1
1389
/* * Copyright 2022 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.food.bukkit.listener import com.rpkit.core.service.Services import com.rpkit.food.bukkit.expiry.RPKExpiryServiceImpl import org.bukkit.entity.Item import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.player.PlayerFishEvent /** * Player fish listener for adding expiry dates. */ class PlayerFishListener : Listener { @EventHandler fun onPlayerFish(event: PlayerFishEvent) { val caught = event.caught if (caught != null) { if (caught is Item) { val item = caught.itemStack val expiryService = Services[RPKExpiryServiceImpl::class.java] ?: return expiryService.setExpiry(item) caught.itemStack = item } } } }
apache-2.0
0b128554d6f650486e4321138c5121a1
31.302326
88
0.696904
4.234756
false
false
false
false
shchurov/gitter-kotlin-client
app/src/main/kotlin/com/github/shchurov/gitterclient/domain/interactors/MarkMessageAsReadInteractor.kt
1
1547
package com.github.shchurov.gitterclient.domain.interactors import com.github.shchurov.gitterclient.data.database.Database import com.github.shchurov.gitterclient.data.network.api.GitterApi import com.github.shchurov.gitterclient.data.subscribers.EmptySubscriber import com.github.shchurov.gitterclient.domain.interactors.threading.SchedulersProvider import com.github.shchurov.gitterclient.domain.models.Message import java.util.* import javax.inject.Inject import javax.inject.Named class MarkMessageAsReadInteractor @Inject constructor( private val gitterApi: GitterApi, private val database: Database, private val schedulersProvider: SchedulersProvider, @Named("roomId") private val roomId: String ) { companion object { private const val MAX_PENDING_MESSAGES = 20 } private val ids = mutableListOf<String>() fun markAsReadLazy(message: Message) { message.unread = false database.decrementRoomUnreadItems(roomId) ids.add(message.id) if (ids.size == MAX_PENDING_MESSAGES) { sendRequest(roomId) } } fun flush() { if (ids.size > 0) { sendRequest(roomId) } } private fun sendRequest(roomId: String) { val copyIds = ArrayList(ids) ids.clear() gitterApi.markMessagesAsRead(roomId, copyIds) .subscribeOn(schedulersProvider.background) .unsubscribeOn(schedulersProvider.background) .subscribe(EmptySubscriber()) } }
apache-2.0
9c8272179beaad573651b6abb2f9d188
30.591837
87
0.694893
4.563422
false
false
false
false
nhaarman/expect.kt
expect.kt/src/test/kotlin/com/nhaarman/expect/TestObserverMatcherTest.kt
1
3932
/* * Copyright 2017 Niek Haarman * * 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.nhaarman.expect import io.reactivex.Observable import org.junit.Test import java.io.IOException class TestObserverMatcherTest { @Test fun `expect no values - success`() { /* When */ val observer = Observable.never<Unit>().test() /* Then */ expect(observer).toHaveNoValues() } @Test fun `expect no values - failure`() { /* Given */ val observer = Observable.just(Unit).test() /* Expect */ expectErrorWithMessage("Expected no values") on { /* When */ expect(observer).toHaveNoValues() } } @Test fun `expect value count - success`() { /* When */ val observer = Observable.just(Unit).test() /* Then */ expect(observer).toHaveValueCount(1) } @Test fun `expect value count - failure`() { /* When */ val observer = Observable.just(Unit).test() /* Expect */ expectErrorWithMessage("1 values were observed") on { /* Then */ expect(observer).toHaveValueCount(3) } } @Test fun `expect values - success`() { /* When */ val observer = Observable.just(Unit).test() /* Then */ expect(observer).toHaveValues(Unit) } @Test fun `expect values - failure - invalid count`() { /* Given */ val observer = Observable.just(Unit).test() /* Expect */ expectErrorWithMessage("1 values were observed") on { /* When */ expect(observer).toHaveValues(Unit, Unit) } } @Test fun `expect values - failure - invalid items`() { /* Given */ val observer = Observable.just(1, 2).test() /* Expect */ expectErrorWithMessage("but was") on { /* When */ expect(observer).toHaveValues(1, 1) } } @Test fun `expect completion - success`() { /* Given */ val observer = Observable.just(Unit).test() /* Then */ expect(observer).toBeCompleted() } @Test fun `expect completion - failure`() { /* Given */ val observer = Observable.never<Unit>().test() /* Expect */ expectErrorWithMessage("Not completed") on { /* When */ expect(observer).toBeCompleted() } } @Test fun `expect error - success`() { /* Given */ val exception = IOException("") /* When */ val observer = Observable.error<Unit>(exception).test() /* Then */ expect(observer).toHaveError(exception) } @Test fun `expect error - failure - no error`() { /* Given */ val exception = IOException("") val observer = Observable.never<Unit>().test() /* Expect */ expectErrorWithMessage("No errors") on { /* When */ expect(observer).toHaveError(exception) } } @Test fun `expect error - failure - different error`() { /* Given */ val observer = Observable.error<Unit>(IOException("1")).test() /* Expect */ expectErrorWithMessage("Error not present") on { /* When */ expect(observer).toHaveError(IOException("2")) } } }
apache-2.0
6aafd556e89d1fbf39e4669f14174c4a
23.277778
75
0.554934
4.524741
false
true
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/gateway/modules/InviteBlockerModule.kt
1
18264
package net.perfectdreams.loritta.cinnamon.discord.gateway.modules import com.github.benmanes.caffeine.cache.Caffeine import dev.kord.common.entity.* import dev.kord.common.entity.optional.Optional import dev.kord.core.cache.data.MemberData import dev.kord.core.cache.data.UserData import dev.kord.gateway.* import dev.kord.rest.builder.message.create.actionRow import dev.kord.rest.builder.message.create.allowedMentions import dev.kord.rest.request.KtorRequestException import io.ktor.http.* import mu.KotlinLogging import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.cinnamon.emotes.Emotes import net.perfectdreams.loritta.common.utils.LorittaPermission import net.perfectdreams.loritta.common.utils.text.TextUtils.stripCodeBackticks import net.perfectdreams.loritta.i18n.I18nKeysData import net.perfectdreams.loritta.cinnamon.discord.gateway.GatewayEventContext import net.perfectdreams.loritta.cinnamon.discord.utils.metrics.DiscordGatewayEventsProcessorMetrics import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.styled import net.perfectdreams.loritta.cinnamon.discord.interactions.components.interactiveButton import net.perfectdreams.loritta.cinnamon.discord.interactions.components.loriEmoji import net.perfectdreams.loritta.cinnamon.discord.interactions.inviteblocker.ActivateInviteBlockerBypassButtonClickExecutor import net.perfectdreams.loritta.cinnamon.discord.interactions.inviteblocker.ActivateInviteBlockerData import net.perfectdreams.loritta.cinnamon.discord.utils.DiscordInviteUtils import net.perfectdreams.loritta.cinnamon.discord.utils.MessageUtils import net.perfectdreams.loritta.cinnamon.discord.utils.hasLorittaPermission import net.perfectdreams.loritta.cinnamon.discord.utils.sources.UserTokenSource import net.perfectdreams.loritta.cinnamon.discord.utils.toLong import java.util.concurrent.TimeUnit import java.util.regex.Matcher import java.util.regex.Pattern class InviteBlockerModule(val m: LorittaBot) : ProcessDiscordEventsModule() { companion object { private val URL_PATTERN = Pattern.compile("[-a-zA-Z0-9@:%._+~#=]{2,256}\\.[A-z]{2,7}\\b([-a-zA-Z0-9@:%_+.~#?&/=]*)") private val logger = KotlinLogging.logger {} } private val cachedInviteLinks = Caffeine.newBuilder().expireAfterAccess(30L, TimeUnit.MINUTES) .build<Snowflake, Set<String>>() .asMap() override suspend fun processEvent(context: GatewayEventContext): ModuleResult { when (val event = context.event) { is MessageCreate -> { val author = event.message.author val guildId = event.message.guildId.value ?: return ModuleResult.Continue // Not in a guild val member = event.message.member.value ?: return ModuleResult.Continue // The member isn't in the guild val channelId = event.message.channelId return handleMessage( guildId, channelId, event.message.id, author, member, event.message.content, event.message.embeds ) } is MessageUpdate -> { val author = event.message.author.value ?: return ModuleResult.Continue // Where's the user? val guildId = event.message.guildId.value ?: return ModuleResult.Continue // Not in a guild val member = event.message.member.value ?: return ModuleResult.Continue // The member isn't in the guild val channelId = event.message.channelId val content = event.message.content.value ?: return ModuleResult.Continue // Where's the message content? val embeds = event.message.embeds.value ?: return ModuleResult.Continue // Where's the embeds? (This is an empty list even if the message doesn't have any embeds) return handleMessage( guildId, channelId, event.message.id, author, member, content, embeds ) } // Delete invite list from cache when a server invite is created or deleted is InviteCreate -> event.invite.guildId.value?.let { cachedInviteLinks.remove(it) } is InviteDelete -> event.invite.guildId.value?.let { cachedInviteLinks.remove(it) } else -> {} } return ModuleResult.Continue } private suspend fun handleMessage( guildId: Snowflake, channelId: Snowflake, messageId: Snowflake, author: DiscordUser, member: DiscordGuildMember, content: String, embeds: List<DiscordEmbed> ): ModuleResult { // Ignore messages sent by bots if (author.bot.discordBoolean) return ModuleResult.Continue val strippedContent = content // We need to strip the code marks to avoid this: // https://cdn.discordapp.com/attachments/513405772911345664/760887806191992893/invite-bug.png .stripCodeBackticks() .replace("\u200B", "") // https://discord.gg\loritta is actually detected as https://discord.gg/loritta on Discord // So we are going to flip all \ to / .replace("\\", "/") // https://discord.gg//loritta is actually detected as https://discord.gg/loritta on Discord // (yes, two issues, wow) // So we are going to replace all /+ to /, so https://discord.gg//loritta becomes https://discord.gg/loritta .replace(Regex("/+"), "/") val validMatchers = mutableListOf<Matcher>() val contentMatcher = getMatcherIfHasInviteLink(strippedContent) if (contentMatcher != null) validMatchers.add(contentMatcher) if (!isYouTubeLink(strippedContent)) { for (embed in embeds) { val descriptionMatcher = getMatcherIfHasInviteLink(embed.description) if (descriptionMatcher != null) validMatchers.add(descriptionMatcher) val titleMatcher = getMatcherIfHasInviteLink(embed.title) if (titleMatcher != null) validMatchers.add(titleMatcher) val urlMatcher = getMatcherIfHasInviteLink(embed.url) if (urlMatcher != null) validMatchers.add(urlMatcher) val footerMatcher = getMatcherIfHasInviteLink(embed.footer.value?.text) if (footerMatcher != null) validMatchers.add(footerMatcher) val authorNameMatcher = getMatcherIfHasInviteLink(embed.author.value?.name) if (authorNameMatcher != null) validMatchers.add(authorNameMatcher) val authorUrlMatcher = getMatcherIfHasInviteLink(embed.author.value?.url) if (authorUrlMatcher != null) validMatchers.add(authorUrlMatcher) val fields = embed.fields.value if (fields != null) { for (field in fields) { val fieldMatcher = getMatcherIfHasInviteLink(field.value) if (fieldMatcher != null) validMatchers.add(fieldMatcher) } } } } // There isn't any matched links in the message! if (validMatchers.isEmpty()) return ModuleResult.Continue // We will only get the configuration and stuff after checking if we should act on the message val serverConfig = m.pudding.serverConfigs.getServerConfigRoot(guildId.value) val inviteBlockerConfig = serverConfig ?.getInviteBlockerConfig() ?: return ModuleResult.Continue if (inviteBlockerConfig.whitelistedChannels.contains(channelId.toLong())) return ModuleResult.Continue val i18nContext = m.languageManager.getI18nContextByLegacyLocaleId(serverConfig.localeId) // Can the user bypass the invite blocker check? val canBypass = m.pudding.serverConfigs.hasLorittaPermission(guildId, member, LorittaPermission.ALLOW_INVITES) if (canBypass) return ModuleResult.Continue // Para evitar que use a API do Discord para pegar os invites do servidor toda hora, nós iremos *apenas* pegar caso seja realmente // necessário, e, ao pegar, vamos guardar no cache de invites val lorittaPermissions = m.cache.getLazyCachedLorittaPermissions(guildId, channelId) val allowedInviteCodes = mutableSetOf<String>() if (inviteBlockerConfig.whitelistServerInvites) { val cachedGuildInviteLinks = cachedInviteLinks[guildId] if (cachedGuildInviteLinks == null) { val guildInviteLinks = mutableSetOf<String>() if (lorittaPermissions.hasPermission(Permission.ManageGuild)) { try { logger.info { "Querying guild $guildId's vanity invite..." } val vanityInvite = m.rest.guild.getVanityInvite(guildId) val vanityInviteCode = vanityInvite.code if (vanityInviteCode != null) guildInviteLinks.add(vanityInviteCode) else logger.info { "Guild $guildId has the vanity invite feature, but they haven't set the invite code!" } } catch (e: KtorRequestException) { // Forbidden = The server does not have the feature enabled if (e.httpResponse.status != HttpStatusCode.Forbidden) throw e else logger.info { "Guild $guildId does not have the vanity invite feature..." } } logger.info { "Querying guild $guildId normal invites..." } val invites = m.rest.guild.getGuildInvites(guildId) // This endpoint does not return the vanity invite val codes = invites.map { it.code } guildInviteLinks.addAll(codes) } else { logger.warn { "Not querying guild $guildId invites because I don't have permission to manage the guild there!" } } allowedInviteCodes.addAll(guildInviteLinks) } else { allowedInviteCodes.addAll(cachedGuildInviteLinks) } cachedInviteLinks[guildId] = allowedInviteCodes } logger.info { "Allowed invite codes in guild $guildId: $allowedInviteCodes" } for (matcher in validMatchers) { val urls = mutableSetOf<String>() while (matcher.find()) { var url = matcher.group() if (url.startsWith("discord.gg", true)) { url = "discord.gg" + matcher.group(1).replace(".", "") } urls.add(url) } val inviteCodes = urls.mapNotNull { DiscordInviteUtils.getInviteCodeFromUrl(it) } val disallowedInviteCodes = inviteCodes.filter { it !in allowedInviteCodes } if (disallowedInviteCodes.isNotEmpty()) { logger.info { "Invite Blocker triggered in guild $guildId! Invite Codes: $disallowedInviteCodes" } DiscordGatewayEventsProcessorMetrics.invitesBlocked .labels(guildId.toString()) .inc() if (inviteBlockerConfig.deleteMessage && lorittaPermissions.hasPermission(Permission.ManageMessages)) { try { // Discord does not log messages deleted by bots, so providing an audit log reason is pointless m.rest.channel.deleteMessage( channelId, messageId ) } catch (e: KtorRequestException) { // Maybe the message was deleted by another bot? if (e.httpResponse.status != HttpStatusCode.NotFound) throw e else logger.warn { "I tried deleting the message ${messageId} on $guildId, but looks like another bot deleted it... Let's just ignore it and pretend it was successfully deleted" } } } val warnMessage = inviteBlockerConfig.warnMessage if (inviteBlockerConfig.tellUser && !warnMessage.isNullOrEmpty()) { if (lorittaPermissions.canTalk()) { logger.info { "Sending blocked invite message in $channelId on $guildId..." } val userData = UserData.from(author) val memberData = MemberData.from(userData.id, guildId, member) val toBeSent = MessageUtils.createMessage( m, guildId, warnMessage, listOf( UserTokenSource(m.kord, userData, memberData) ), emptyMap() ) val sentMessage = m.rest.channel.createMessage(channelId) { toBeSent.apply(this) } if (m.cache.hasPermission(guildId, channelId, author.id, Permission.ManageGuild)) { // If the user has permission to enable the invite bypass permission, make Loritta recommend to enable the permission val topRole = m.cache.getRoles(guildId, member) .asSequence() .sortedByDescending { it.position } .filter { !it.isManaged } .filter { it.idLong != guildId.value.toLong() } // If it is the role ID == guild ID, then it is the @everyone role! .firstOrNull() if (topRole != null) { // A role has been found! Tell the user about enabling the invite blocker bypass m.rest.channel.createMessage(channelId) { this.failIfNotExists = false this.messageReference = sentMessage.id styled( i18nContext.get(I18nKeysData.Modules.InviteBlocker.ActivateInviteBlockerBypass("<@&${topRole.id}>")), Emotes.LoriSmile ) styled( i18nContext.get(I18nKeysData.Modules.InviteBlocker.HowToReEnableLater("<${m.config.loritta.website.url}guild/${author.id}/configure/permissions>")), Emotes.LoriHi ) actionRow { interactiveButton( ButtonStyle.Primary, i18nContext.get(I18nKeysData.Modules.InviteBlocker.AllowSendingInvites), ActivateInviteBlockerBypassButtonClickExecutor, m.encodeDataForComponentOrStoreInDatabase( ActivateInviteBlockerData( author.id, Snowflake(topRole.id) ) ) ) { loriEmoji = Emotes.LoriPat } } // Empty allowed mentions because we don't want to mention the role allowedMentions {} } } } } else { logger.warn { "I wanted to tell about the blocked invite in $channelId on $guildId, but I can't talk there!" } } } // Invite has been found, exit! return ModuleResult.Cancel } else { logger.info { "Invite Blocker triggered in guild $guildId, but we will ignore it because it is on the invite code allowed list... Invite Codes: $inviteCodes" } continue } } return ModuleResult.Continue } /** * Checks if [content] contains a YouTube Link * * @param content the content * @return if the link contains a YouTube URL */ private fun isYouTubeLink(content: String?): Boolean { if (content.isNullOrBlank()) return false val matcher = URL_PATTERN.matcher(content) return if (matcher.find()) { val everything = matcher.group(0) val afterSlash = matcher.group(1) val uri = everything.replace(afterSlash, "") uri.endsWith("youtube.com") || uri.endsWith("youtu.be") } else { false } } private fun getMatcherIfHasInviteLink(optionalString: Optional<String>?) = optionalString?.let { getMatcherIfHasInviteLink(it.value) } private fun getMatcherIfHasInviteLink(content: String?): Matcher? { if (content.isNullOrBlank()) return null val matcher = URL_PATTERN.matcher(content) return if (matcher.find()) { matcher.reset() matcher } else { null } } }
agpl-3.0
fe2c1b33e35afb7285efa76801c06f6c
47.187335
202
0.561658
5.369597
false
false
false
false
mutualmobile/CardStackUI
cardstack/src/main/java/com/mutualmobile/cardstack/CardStackAdapter.kt
1
10946
package com.mutualmobile.cardstack import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.content.Context import android.content.res.Resources import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.view.animation.DecelerateInterpolator import android.widget.FrameLayout import java.util.ArrayList /** * This class acts as an adapter for the [CardStackLayout] view. This adapter is intentionally * made an abstract class with following abstract methods - * * * * * [.getCount] - Decides the number of views present in the view * * * [.createView] - Creates the view for all positions in range [0, [.getCount]) * * * Contains the logic for touch events in [.onTouch] */ abstract class CardStackAdapter(context: Context) : View.OnTouchListener, View.OnClickListener { companion object { // Animation constants const val ANIM_DURATION = 600 const val DECELERATION_FACTOR = 2 const val INVALID_CARD_POSITION = -1 } private val mScreenHeight: Int private val dp30: Int private val maxDistanceToConsiderAsClick: Float // Settings for the adapter from layout protected var cardGapBottom: Float = 0F private var mCardGap: Float = 0F private var mParallaxScale: Int = 0 private var mParallaxEnabled: Boolean = false private var mShowInitAnimation: Boolean = false private var mScrollParent: CardStackLayout? = null private var mFrame: FrameLayout? = null private var mCardViews: ArrayList<View> = arrayListOf() var fullCardHeight: Int = 0 private set /** * Returns true if no animation is in progress currently. Can be used to disable any events * if they are not allowed during an animation. Returns false if an animation is in progress. * * @return - true if animation in progress, false otherwise */ var isScreenTouchable = false private set private var mTouchFirstY = -1f private var mTouchPrevY = -1f private var mTouchDistance = 0f /** * Returns the position of selected card. If no card * is selected, returns [.INVALID_CARD_POSITION] */ var selectedCardPosition = INVALID_CARD_POSITION private set private val scaleFactorForElasticEffect: Float private var mParentPaddingTop = 0 private var mCardPaddingInternal = 0 /** * Defines the number of cards that are present in the [CardStackLayout] * * @return cardCount - Number of views in the related [CardStackLayout] */ abstract val count: Int protected val scrollOffset: Int get() = mScrollParent?.scrollY ?: 0 /** * Returns false if all the cards are in their initial position i.e. no card is selected * * * Returns true if the [CardStackLayout] has a card selected and all other cards are * at the bottom of the screen. * * @return true if any card is selected, false otherwise */ val isCardSelected: Boolean get() = selectedCardPosition != INVALID_CARD_POSITION init { val resources = context.resources val dm = Resources.getSystem() .displayMetrics mScreenHeight = dm.heightPixels dp30 = resources.getDimension(R.dimen.dp30) .toInt() scaleFactorForElasticEffect = resources.getDimension(R.dimen.dp8) .toInt() .toFloat() maxDistanceToConsiderAsClick = resources.getDimension(R.dimen.dp8) .toInt() .toFloat() } /** * Defines and initializes the view to be shown in the [CardStackLayout] * Provides two parameters to the sub-class namely - * * @param position * @param container * @return View corresponding to the position and parent container */ abstract fun createView( position: Int, container: ViewGroup? ): View internal fun addView(position: Int) { val root = createView(position, mFrame) root.setOnTouchListener(this) root.setTag(R.id.cardstack_internal_position_tag, position) root.setLayerType(View.LAYER_TYPE_HARDWARE, null) root.isFocusable = true root.isFocusableInTouchMode = true mCardPaddingInternal = root.paddingTop val lp = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, fullCardHeight) root.layoutParams = lp if (mShowInitAnimation) { root.y = getCardFinalY(position) isScreenTouchable = false } else { root.y = getCardOriginalY(position) - mParentPaddingTop isScreenTouchable = true } mCardViews[position] = root mFrame?.addView(root) } protected fun getCardFinalY(position: Int): Float { return mScreenHeight.toFloat() - dp30.toFloat() - (count - position) * cardGapBottom - mCardPaddingInternal.toFloat() } protected fun getCardOriginalY(position: Int): Float { return mParentPaddingTop + mCardGap * position } /** * Resets all cards in [CardStackLayout] to their initial positions * * @param r Execute r.run() once the reset animation is done */ @JvmOverloads fun resetCards(r: Runnable? = null) { val animations = ArrayList<Animator>(count) for (i in 0 until count) { val child = mCardViews[i] animations.add(ObjectAnimator.ofFloat<View>(child, View.Y, child.y, getCardOriginalY(i))) } startAnimations(animations, r, true) } /** * Plays together all animations passed in as parameter. Once animation is completed, r.run() is * executed. If parameter isReset is set to true, [.mSelectedCardPosition] is set to [.INVALID_CARD_POSITION] * * @param animations * @param r * @param isReset */ private fun startAnimations( animations: List<Animator>, r: Runnable?, isReset: Boolean ) { val animatorSet = AnimatorSet() animatorSet.playTogether(animations) animatorSet.duration = ANIM_DURATION.toLong() animatorSet.interpolator = DecelerateInterpolator(DECELERATION_FACTOR.toFloat()) animatorSet.addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { r?.run() isScreenTouchable = true if (isReset) { selectedCardPosition = INVALID_CARD_POSITION mScrollParent?.setScrollingEnabled(true) } } }) animatorSet.start() } override fun onTouch( v: View, event: MotionEvent ): Boolean { if (!isScreenTouchable) { return false } val y = event.rawY val positionOfCardToMove = v.getTag(R.id.cardstack_internal_position_tag) as Int when (event.action) { MotionEvent.ACTION_DOWN -> { if (mTouchFirstY != -1f) { return false } mTouchFirstY = y mTouchPrevY = mTouchFirstY mTouchDistance = 0f } MotionEvent.ACTION_MOVE -> { if (selectedCardPosition == INVALID_CARD_POSITION) moveCards(positionOfCardToMove, y - mTouchFirstY) mTouchDistance += Math.abs(y - mTouchPrevY) } MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { if (mTouchDistance < maxDistanceToConsiderAsClick && Math.abs(y - mTouchFirstY) < maxDistanceToConsiderAsClick) { if (selectedCardPosition == INVALID_CARD_POSITION) { onClick(v) } else { resetCards() } } mTouchFirstY = -1f mTouchPrevY = mTouchFirstY mTouchDistance = 0f return false } } return true } override fun onClick(v: View) { if (!isScreenTouchable) { return } isScreenTouchable = false mScrollParent?.setScrollingEnabled(false) if (selectedCardPosition == INVALID_CARD_POSITION) { selectedCardPosition = v.getTag(R.id.cardstack_internal_position_tag) as Int val animations = ArrayList<Animator>(count) for (i in 0 until count) { val child = mCardViews[i] animations.add(getAnimatorForView(child, i, selectedCardPosition)) } startAnimations(animations, Runnable { isScreenTouchable = true if (mScrollParent?.onCardSelectedListener != null) { mScrollParent?.onCardSelectedListener?.onCardSelected(v, selectedCardPosition) } }, false) } } /** * This method can be overridden to have different animations for each card when a click event * happens on any card view. This method will be called for every * * @param view The view for which this method needs to return an animator * @param selectedCardPosition Position of the card that was clicked * @param currentCardPosition Position of the current card * @return animator which has to be applied on the current card */ protected fun getAnimatorForView( view: View, currentCardPosition: Int, selectedCardPosition: Int ): Animator { val offsetTop = scrollOffset return if (currentCardPosition != selectedCardPosition) { ObjectAnimator.ofFloat(view, View.Y, view.y, offsetTop + getCardFinalY(currentCardPosition)) } else { ObjectAnimator.ofFloat(view, View.Y, view.y, offsetTop + getCardOriginalY(0)) } } private fun moveCards( positionOfCardToMove: Int, diff: Float ) { if (diff < 0 || positionOfCardToMove < 0 || positionOfCardToMove >= count) return for (i in positionOfCardToMove until count) { val child = mCardViews[i] var diffCard = diff / scaleFactorForElasticEffect diffCard = if (mParallaxEnabled) { if (mParallaxScale > 0) { diffCard * (mParallaxScale / 3).toFloat() * (count + 1 - i).toFloat() } else { val scale = mParallaxScale * -1 diffCard * (i * (scale / 3) + 1) } } else diffCard * (count * 2 + 1) child.y = getCardOriginalY(i) + diffCard } } /** * Provides an API to [CardStackLayout] to set the parameters provided to it in its XML * * @param cardStackLayout Parent of all cards */ internal fun setAdapterParams(cardStackLayout: CardStackLayout) { mScrollParent = cardStackLayout mFrame = cardStackLayout.frame cardGapBottom = cardStackLayout.cardGapBottom mCardGap = cardStackLayout.cardGap mParallaxScale = cardStackLayout.parallaxScale mParallaxEnabled = cardStackLayout.isParallaxEnabled if (mParallaxEnabled && mParallaxScale == 0) mParallaxEnabled = false mShowInitAnimation = cardStackLayout.isShowInitAnimation mParentPaddingTop = cardStackLayout.paddingTop fullCardHeight = (mScreenHeight.toFloat() - dp30.toFloat() - count * cardGapBottom).toInt() } /** * Since there is no view recycling in [CardStackLayout], we maintain an instance of every * view that is set for every position. This method returns a view at the requested position. * * @param position Position of card in [CardStackLayout] * @return View at requested position */ fun getCardView(position: Int) = mCardViews[position] }
apache-2.0
4b0fb2cb4577b38a579aff5f8edcc083
30.366762
121
0.688379
4.227887
false
false
false
false
oukingtim/king-admin
king-admin-kotlin/src/main/kotlin/com/oukingtim/config/ShiroRealm.kt
1
2090
package com.oukingtim.config import com.oukingtim.domain.SysUser import com.oukingtim.service.SysMenuService import com.oukingtim.service.SysUserService import org.apache.shiro.authc.* import org.apache.shiro.authz.AuthorizationInfo import org.apache.shiro.authz.SimpleAuthorizationInfo import org.apache.shiro.realm.AuthorizingRealm import org.apache.shiro.subject.PrincipalCollection import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Component /** * Created by oukingtim */ @Component class ShiroRealm :AuthorizingRealm() { @Autowired private val sysUserService: SysUserService? = null @Autowired private val sysMenuService: SysMenuService? = null /** * 授权(验证权限时调用) */ override fun doGetAuthorizationInfo(principalCollection: PrincipalCollection): AuthorizationInfo { val user = principalCollection.primaryPrincipal as SysUser val userId = user.id //用户权限列表 val permsSet = sysMenuService!!.getPermissions(userId!!) val info = SimpleAuthorizationInfo() info.stringPermissions = permsSet return info } /** * 认证(登录时调用) */ @Throws(AuthenticationException::class) override fun doGetAuthenticationInfo(authenticationToken: AuthenticationToken): AuthenticationInfo { val username = authenticationToken.principal as String val password = String(authenticationToken.credentials as CharArray) //查询用户信息 val user = sysUserService!!.findByUserName(username) ?: throw UnknownAccountException("用户名不正确") //账号不存在 //密码错误 if (password != user.password) { throw IncorrectCredentialsException("用户名或密码不正确") } //账号禁用 if ("0" == user.status) { throw LockedAccountException("用户已被禁用,请联系管理员") } val info = SimpleAuthenticationInfo(user, password, name) return info } }
mit
043e7a11c19c5dfadc58cf9e93209342
28.621212
104
0.707779
4.471396
false
false
false
false
jitsi/jitsi-videobridge
jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/rtp/codec/vp8/Vp8Parser.kt
1
2718
/* * Copyright @ 2018 - present 8x8, 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 org.jitsi.nlj.rtp.codec.vp8 import org.jitsi.nlj.MediaSourceDesc import org.jitsi.nlj.PacketInfo import org.jitsi.nlj.rtp.codec.VideoCodecParser import org.jitsi.nlj.util.StateChangeLogger import org.jitsi.rtp.extensions.toHex import org.jitsi.utils.logging2.Logger import org.jitsi.utils.logging2.createChildLogger /** * Some [Vp8Packet] fields are not able to be determined by looking at a single VP8 packet (for example the frame * height can only be acquired from keyframes). This class updates the layer descriptions with information * from frames, and also diagnoses packet format variants that the Jitsi videobridge won't be able to route. */ class Vp8Parser( sources: Array<MediaSourceDesc>, parentLogger: Logger ) : VideoCodecParser(sources) { private val logger = createChildLogger(parentLogger) // Consistency private val pictureIdState = StateChangeLogger("missing picture id", logger) private val extendedPictureIdState = StateChangeLogger("missing extended picture ID", logger) private val tidWithoutTl0PicIdxState = StateChangeLogger("TID with missing TL0PICIDX", logger) override fun parse(packetInfo: PacketInfo) { val vp8Packet = packetInfo.packetAs<Vp8Packet>() if (vp8Packet.height > -1) { // TODO: handle case where new height is from a packet older than the // latest height we've seen. findRtpEncodingDesc(vp8Packet)?.let { enc -> val newLayers = enc.layers.map { layer -> layer.copy(height = vp8Packet.height) } enc.layers = newLayers.toTypedArray() } } pictureIdState.setState(vp8Packet.hasPictureId, vp8Packet) { "Packet Data: ${vp8Packet.toHex(80)}" } extendedPictureIdState.setState(vp8Packet.hasExtendedPictureId, vp8Packet) { "Packet Data: ${vp8Packet.toHex(80)}" } tidWithoutTl0PicIdxState.setState( vp8Packet.hasTL0PICIDX || !vp8Packet.hasTemporalLayerIndex, vp8Packet ) { "Packet Data: ${vp8Packet.toHex(80)}" } } }
apache-2.0
9e4b9a31507e9240bb961a93097755dc
40.181818
113
0.705666
4.06278
false
false
false
false
jitsi/jitsi-videobridge
rtp/src/main/kotlin/org/jitsi/rtp/rtcp/rtcpfb/payload_specific_fb/RtcpFbFirPacket.kt
1
5155
/* * Copyright @ 2018 - present 8x8, 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 org.jitsi.rtp.rtcp.rtcpfb.payload_specific_fb import org.jitsi.rtp.extensions.bytearray.getInt import org.jitsi.rtp.extensions.bytearray.putInt import org.jitsi.rtp.extensions.unsigned.toPositiveInt import org.jitsi.rtp.extensions.unsigned.toPositiveLong import org.jitsi.rtp.rtcp.RtcpHeaderBuilder import org.jitsi.rtp.rtcp.rtcpfb.RtcpFbPacket import org.jitsi.rtp.util.BufferPool import org.jitsi.rtp.util.RtpUtils /** * * https://tools.ietf.org/html/rfc4585#section-6.1 * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * |V=2|P| FMT | PT | length | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | SSRC of packet sender | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | SSRC of media source | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | SSRC | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Seq nr. | Reserved | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | .... | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * https://tools.ietf.org/html/rfc5104#section-4.3.1.1 * * The SSRC field in the FIR FCI block is used to set the media sender * SSRC, the media source SSRC field in the RTCPFB header is unused for FIR packets. * Within the common packet header for feedback messages (as defined in * section 6.1 of [RFC4585]), the "SSRC of packet sender" field * indicates the source of the request, and the "SSRC of media source" * is not used and SHALL be set to 0. The SSRCs of the media senders to * which the FIR command applies are in the corresponding FCI entries. * A FIR message MAY contain requests to multiple media senders, using * one FCI entry per target media sender. */ // TODO: support multiple FIR blocks class RtcpFbFirPacket( buffer: ByteArray, offset: Int, length: Int ) : PayloadSpecificRtcpFbPacket(buffer, offset, length) { override fun clone(): RtcpFbFirPacket = RtcpFbFirPacket(cloneBuffer(0), 0, length) var mediaSenderSsrc: Long get() = getMediaSenderSsrc(buffer, offset) set(value) = setMediaSenderSsrc(buffer, offset, value) var seqNum: Int get() = getSeqNum(buffer, offset) set(value) = setSeqNum(buffer, offset, value) companion object { const val FMT = 4 // TODO: support multiple FCI? const val SIZE_BYTES = HEADER_SIZE + 8 const val MEDIA_SENDER_SSRC_OFFSET = FCI_OFFSET const val SEQ_NUM_OFFSET = MEDIA_SENDER_SSRC_OFFSET + 4 fun getMediaSenderSsrc(buf: ByteArray, baseOffset: Int): Long = buf.getInt(baseOffset + MEDIA_SENDER_SSRC_OFFSET).toPositiveLong() fun setMediaSenderSsrc(buf: ByteArray, baseOffset: Int, value: Long) = buf.putInt(baseOffset + MEDIA_SENDER_SSRC_OFFSET, value.toInt()) fun getSeqNum(buf: ByteArray, baseOffset: Int): Int = buf.get(baseOffset + SEQ_NUM_OFFSET).toPositiveInt() fun setSeqNum(buf: ByteArray, baseOffset: Int, value: Int) = buf.set(baseOffset + SEQ_NUM_OFFSET, value.toByte()) } } // TODO: we need an RtcpFbHeader so that we can fill out the mediaSourceSsrc for FB packets class RtcpFbFirPacketBuilder( val rtcpHeader: RtcpHeaderBuilder = RtcpHeaderBuilder(), var mediaSenderSsrc: Long = -1, var firCommandSeqNum: Int = -1 ) { fun build(): RtcpFbFirPacket { val buf = BufferPool.getArray(RtcpFbFirPacket.SIZE_BYTES) writeTo(buf, 0) return RtcpFbFirPacket(buf, 0, RtcpFbFirPacket.SIZE_BYTES) } fun writeTo(buf: ByteArray, offset: Int) { rtcpHeader.apply { packetType = PayloadSpecificRtcpFbPacket.PT reportCount = RtcpFbFirPacket.FMT length = RtpUtils.calculateRtcpLengthFieldValue(RtcpFbFirPacket.SIZE_BYTES) } rtcpHeader.writeTo(buf, offset) RtcpFbPacket.setMediaSourceSsrc(buf, offset, 0) // SHALL be 0 RtcpFbFirPacket.setMediaSenderSsrc(buf, offset, mediaSenderSsrc) RtcpFbFirPacket.setSeqNum(buf, offset, firCommandSeqNum) } }
apache-2.0
573f1f1b43ba70160bf1b7b825f13c32
41.958333
91
0.586615
4.130609
false
false
false
false
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/features/manual_machines/TileEntities.kt
2
2615
package com.cout970.magneticraft.features.manual_machines import com.cout970.magneticraft.misc.RegisterTileEntity import com.cout970.magneticraft.misc.block.getOrientationCentered import com.cout970.magneticraft.misc.inventory.Inventory import com.cout970.magneticraft.misc.tileentity.DoNotRemove import com.cout970.magneticraft.misc.vector.toBlockPos import com.cout970.magneticraft.misc.vector.xd import com.cout970.magneticraft.misc.vector.yd import com.cout970.magneticraft.misc.vector.zd import com.cout970.magneticraft.systems.tileentities.TileBase import com.cout970.magneticraft.systems.tilemodules.ModuleCrushingTable import com.cout970.magneticraft.systems.tilemodules.ModuleFabricator import com.cout970.magneticraft.systems.tilemodules.ModuleInventory import com.cout970.magneticraft.systems.tilemodules.ModuleSluiceBox import net.minecraft.util.EnumFacing import net.minecraft.util.ITickable import net.minecraft.util.math.AxisAlignedBB /** * Created by cout970 on 2017/08/10. */ @RegisterTileEntity("box") class TileBox : TileBase() { val inventory = Inventory(27) val invModule = ModuleInventory(inventory) init { initModules(invModule) } } @RegisterTileEntity("crushing_table") class TileCrushingTable : TileBase() { val inventory = Inventory(1) val invModule = ModuleInventory(inventory, capabilityFilter = { null }) val crushingModule = ModuleCrushingTable(inventory) init { initModules(invModule, crushingModule) } } @RegisterTileEntity("sluice_box") class TileSluiceBox : TileBase(), ITickable { val facing: EnumFacing get() = getBlockState().getOrientationCentered() val inventory = Inventory(1) val invModule = ModuleInventory(inventory, capabilityFilter = { null }) val sluiceBoxModule = ModuleSluiceBox({ facing }, inventory) init { initModules(sluiceBoxModule, invModule) } @DoNotRemove override fun update() { super.update() } override fun shouldRenderInPass(pass: Int): Boolean { return pass == 0 || pass == 1 } override fun getRenderBoundingBox(): AxisAlignedBB { val dir = facing.toBlockPos() return super.getRenderBoundingBox().expand(dir.xd, dir.yd, dir.zd) } } @RegisterTileEntity("fabricator") class TileFabricator : TileBase(), ITickable { val inventory = Inventory(9) val invModule = ModuleInventory(inventory) val fabricatorModule = ModuleFabricator(inventory) init { initModules(invModule, fabricatorModule) } @DoNotRemove override fun update() { super.update() } }
gpl-2.0
ebf4203bbd9209621b81f557cbdab153
28.066667
75
0.747228
4.054264
false
false
false
false
MichaelObi/PaperPlayer
app/src/main/java/xyz/michaelobi/paperplayer/data/model/Artist.kt
1
2316
/* * MIT License * * Copyright (c) 2017 MIchael Obi * * 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 xyz.michaelobi.paperplayer.data.model import android.database.Cursor import android.provider.MediaStore /** * PaperPlayer Michael Obi 21 01 2017 8:35 AM */ class Artist(var id: Long, var name: String?, var numOfAlbums: Int, var numOfSongs: Int, var artistKey: String?) { companion object { fun from(musicCursor: Cursor): Artist { val idColumn = musicCursor.getColumnIndex(MediaStore.Audio.Artists._ID) val artistColumn = musicCursor.getColumnIndex(MediaStore.Audio.Artists.ARTIST) val numOfSongsColumn = musicCursor.getColumnIndex(MediaStore.Audio.Artists.NUMBER_OF_TRACKS) val numOfAlbumsColumn = musicCursor.getColumnIndex(MediaStore.Audio.Artists.NUMBER_OF_ALBUMS) val artistKeyColumn = musicCursor.getColumnIndex(MediaStore.Audio.Artists.ARTIST_KEY) val artist = Artist(musicCursor.getLong(idColumn), musicCursor.getString(artistColumn), musicCursor.getInt(numOfAlbumsColumn), musicCursor.getInt(numOfSongsColumn), musicCursor.getString(artistKeyColumn)) return artist } } }
mit
7500e360919d6869260f3f4fe6e66c23
44.411765
114
0.721503
4.550098
false
false
false
false
ysl3000/PathfindergoalAPI
Pathfinder_1_16/src/main/java/com/github/ysl3000/bukkit/pathfinding/craftbukkit/v1_16_R2/pathfinding/CraftNavigation.kt
1
1382
package com.github.ysl3000.bukkit.pathfinding.craftbukkit.v1_16_R2.pathfinding import com.github.ysl3000.bukkit.pathfinding.AbstractNavigation import net.minecraft.server.v1_16_R2.* import org.bukkit.craftbukkit.v1_16_R2.entity.CraftEntity class CraftNavigation(private val navigationAbstract: NavigationAbstract, private val handle: EntityInsentient, private val defaultSpeed: Double) : AbstractNavigation( doneNavigating = { navigationAbstract.n() }, pathSearchRange = { handle.getAttributeInstance(GenericAttributes.FOLLOW_RANGE)?.let { it.value.toFloat() }?: 0f }, moveToPositionU = { x, y, z -> navigationAbstract.a(x, y, z, defaultSpeed) }, moveToPositionB = { x, y, z, speed -> navigationAbstract.a(x, y, z, speed) }, moveToEntityU = { entity -> navigationAbstract.a((entity as CraftEntity).handle, defaultSpeed) }, moveToentityB = { entity, speed -> navigationAbstract.a((entity as CraftEntity).handle, speed) }, speedU = navigationAbstract::a, clearPathEntityU = navigationAbstract::o, setCanPassDoors = navigationAbstract.q()::a, setCanOpenDoors = navigationAbstract.q()::b, setCanFloat = navigationAbstract.q()::c, canPassDoors = navigationAbstract.q()::c, canOpenDoors = navigationAbstract.q()::d, canFloat = navigationAbstract.q()::e )
mit
d1c7284a30705fa2845c42f7c659ad95
56.625
167
0.703329
4.200608
false
false
false
false
google-developer-training/android-demos
DonutTracker/NavigationUI/app/src/main/java/com/android/samples/donuttracker/donut/DonutEntryDialogFragment.kt
1
4486
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.samples.donuttracker.donut import android.annotation.SuppressLint import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.viewModels import androidx.lifecycle.observe import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.android.samples.donuttracker.Notifier import com.android.samples.donuttracker.R import com.android.samples.donuttracker.databinding.DonutEntryDialogBinding import com.android.samples.donuttracker.model.Donut import com.android.samples.donuttracker.storage.SnackDatabase import com.google.android.material.bottomsheet.BottomSheetDialogFragment /** * This dialog allows the user to enter information about a donut, either creating a new * entry or updating an existing one. */ class DonutEntryDialogFragment : BottomSheetDialogFragment() { private enum class EditingState { NEW_DONUT, EXISTING_DONUT } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return DonutEntryDialogBinding.inflate(inflater, container, false).root } @SuppressLint("SetTextI18n") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val donutDao = SnackDatabase.getDatabase(requireContext()).donutDao() val donutEntryViewModel: DonutEntryViewModel by viewModels { DonutViewModelFactory(donutDao) } val binding = DonutEntryDialogBinding.bind(view) var donut: Donut? = null val args: DonutEntryDialogFragmentArgs by navArgs() val editingState = if (args.itemId > 0) { EditingState.EXISTING_DONUT } else { EditingState.NEW_DONUT } // If we arrived here with an itemId of >= 0, then we are editing an existing item if (editingState == EditingState.EXISTING_DONUT) { // Request to edit an existing item, whose id was passed in as an argument. // Retrieve that item and populate the UI with its details donutEntryViewModel.get(args.itemId).observe(viewLifecycleOwner) { donutItem -> binding.apply { name.setText(donutItem.name) description.setText(donutItem.description) ratingBar.rating = donutItem.rating.toFloat() } donut = donutItem } } // When the user clicks the Done button, use the data here to either update // an existing item or create a new one binding.doneButton.setOnClickListener { // Grab these now since the Fragment may go away before the setupNotification // lambda below is called val context = requireContext().applicationContext val navController = findNavController() donutEntryViewModel.addData( donut?.id ?: 0, binding.name.text.toString(), binding.description.text.toString(), binding.ratingBar.rating.toInt() ) { actualId -> val arg = DonutEntryDialogFragmentArgs(actualId).toBundle() val pendingIntent = navController .createDeepLink() .setDestination(R.id.donutEntryDialogFragment) .setArguments(arg) .createPendingIntent() Notifier.postNotification(actualId, context, pendingIntent) } dismiss() } // User clicked the Cancel button; just exit the dialog without saving the data binding.cancelButton.setOnClickListener { dismiss() } } }
apache-2.0
fbef8a09e3e82d21bbb4d31a0dff9501
37.34188
91
0.663843
5.097727
false
false
false
false
xfournet/intellij-community
platform/platform-impl/src/com/intellij/ide/actions/project/convertModuleGroupsToQualifiedNames.kt
1
9175
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.actions.project import com.intellij.CommonBundle import com.intellij.application.runInAllowSaveMode import com.intellij.codeInsight.intention.IntentionManager import com.intellij.codeInspection.ex.InspectionProfileImpl import com.intellij.codeInspection.ex.InspectionProfileWrapper import com.intellij.codeInspection.ex.InspectionToolWrapper import com.intellij.codeInspection.ex.LocalInspectionToolWrapper import com.intellij.lang.StdLanguages import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.LineExtensionInfo import com.intellij.openapi.editor.SpellCheckingEditorCustomizationProvider import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.module.ModulePointerManager import com.intellij.openapi.module.impl.ModulePointerManagerImpl import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectBundle import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiDocumentManager import com.intellij.ui.* import com.intellij.ui.components.JBLabel import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.intellij.xml.util.XmlStringUtil import java.awt.Color import java.awt.Font import java.util.function.Function import java.util.function.Supplier import javax.swing.Action import javax.swing.JCheckBox import javax.swing.JPanel class ConvertModuleGroupsToQualifiedNamesDialog(val project: Project) : DialogWrapper(project) { private val editorArea: EditorTextField private val document: Document get() = editorArea.document private lateinit var modules: List<Module> private val recordPreviousNamesCheckBox: JCheckBox private var modified = false init { title = ProjectBundle.message("convert.module.groups.dialog.title") isModal = false setOKButtonText(ProjectBundle.message("convert.module.groups.button.text")) editorArea = EditorTextFieldProvider.getInstance().getEditorField(StdLanguages.TEXT, project, listOf(EditorCustomization { it.settings.apply { isLineNumbersShown = false isLineMarkerAreaShown = false isFoldingOutlineShown = false isRightMarginShown = false additionalLinesCount = 0 additionalColumnsCount = 0 isAdditionalPageAtBottom = false isShowIntentionBulb = false } (it as? EditorImpl)?.registerLineExtensionPainter(this::generateLineExtension) setupHighlighting(it) }, MonospaceEditorCustomization.getInstance())) document.addDocumentListener(object: DocumentListener { override fun documentChanged(event: DocumentEvent?) { modified = true } }, disposable) recordPreviousNamesCheckBox = JCheckBox(ProjectBundle.message("convert.module.groups.record.previous.names.text"), true) importRenamingScheme(emptyMap()) init() } private fun setupHighlighting(editor: Editor) { editor.putUserData(IntentionManager.SHOW_INTENTION_OPTIONS_KEY, false) val inspections = Supplier<List<InspectionToolWrapper<*, *>>> { listOf(LocalInspectionToolWrapper(ModuleNamesListInspection())) } val file = PsiDocumentManager.getInstance(project).getPsiFile(document) file?.putUserData(InspectionProfileWrapper.CUSTOMIZATION_KEY, Function { val profile = InspectionProfileImpl("Module names", inspections, null) for (spellCheckingToolName in SpellCheckingEditorCustomizationProvider.getInstance().spellCheckingToolNames) { profile.getToolsOrNull(spellCheckingToolName, project)?.isEnabled = false } InspectionProfileWrapper(profile) }) } override fun createCenterPanel(): JPanel { val text = XmlStringUtil.wrapInHtml(ProjectBundle.message("convert.module.groups.description.text")) val recordPreviousNames = com.intellij.util.ui.UI.PanelFactory.panel(recordPreviousNamesCheckBox) .withTooltip(ProjectBundle.message("convert.module.groups.record.previous.names.tooltip", ApplicationNamesInfo.getInstance().fullProductName)).createPanel() return JBUI.Panels.simplePanel(0, UIUtil.DEFAULT_VGAP) .addToCenter(editorArea) .addToTop(JBLabel(text)) .addToBottom(recordPreviousNames) } override fun getPreferredFocusedComponent() = editorArea.focusTarget private fun generateLineExtension(line: Int): Collection<LineExtensionInfo> { val lineText = document.charsSequence.subSequence(document.getLineStartOffset(line), document.getLineEndOffset(line)).toString() if (line !in modules.indices || modules[line].name == lineText) return emptyList() val name = LineExtensionInfo(" <- ${modules[line].name}", JBColor.GRAY, null, null, Font.PLAIN) val groupPath = ModuleManager.getInstance(project).getModuleGroupPath(modules[line]) if (groupPath == null) { return listOf(name) } val group = LineExtensionInfo(groupPath.joinToString(separator = "/", prefix = " (", postfix = ")"), Color.GRAY, null, null, Font.PLAIN) return listOf(name, group) } fun importRenamingScheme(renamingScheme: Map<String, String>) { val moduleManager = ModuleManager.getInstance(project) fun getDefaultName(module: Module) = (moduleManager.getModuleGroupPath(module)?.let { it.joinToString(".") + "." } ?: "") + module.name val names = moduleManager.modules.associateBy({ it }, { renamingScheme.getOrElse(it.name, { getDefaultName(it) }) }) modules = moduleManager.modules.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER, { names[it]!! })) runWriteAction { document.setText(modules.joinToString("\n") { names[it]!! }) } modified = false } fun getRenamingScheme(): Map<String, String> { val lines = document.charsSequence.split('\n') return modules.withIndex().filter { lines[it.index] != it.value.name }.associateByTo(LinkedHashMap(), { it.value.name }, { if (it.index in lines.indices) lines[it.index] else it.value.name }) } override fun doCancelAction() { if (modified) { val answer = Messages.showYesNoCancelDialog(project, ProjectBundle.message("convert.module.groups.do.you.want.to.save.scheme"), ProjectBundle.message("convert.module.groups.dialog.title"), null) when (answer) { Messages.CANCEL -> return Messages.YES -> { if (!saveModuleRenamingScheme(this)) { return } } } } super.doCancelAction() } override fun doOKAction() { ModuleNamesListInspection.checkModuleNames(document.charsSequence.lines(), project) { line, message -> Messages.showErrorDialog(project, ProjectBundle.message("convert.module.groups.error.at.text", line + 1, StringUtil.decapitalize(message)), CommonBundle.getErrorTitle()) return } val renamingScheme = getRenamingScheme() if (renamingScheme.isNotEmpty()) { val model = ModuleManager.getInstance(project).modifiableModel val byName = modules.associateBy { it.name } for (entry in renamingScheme) { model.renameModule(byName[entry.key]!!, entry.value) } modules.forEach { model.setModuleGroupPath(it, null) } runInAllowSaveMode(isSaveAllowed = false) { runWriteAction { model.commit() } if (recordPreviousNamesCheckBox.isSelected) { (ModulePointerManager.getInstance(project) as ModulePointerManagerImpl).setRenamingScheme(renamingScheme) } } project.save() } super.doOKAction() } override fun createActions(): Array<Action> { return arrayOf(okAction, SaveModuleRenamingSchemeAction(this, { modified = false }), LoadModuleRenamingSchemeAction(this), cancelAction) } } class ConvertModuleGroupsToQualifiedNamesAction : DumbAwareAction(ProjectBundle.message("convert.module.groups.action.text"), ProjectBundle.message("convert.module.groups.action.description"), null) { override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return ConvertModuleGroupsToQualifiedNamesDialog(project).show() } override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = e.project != null && ModuleManager.getInstance(e.project!!).hasModuleGroups() } }
apache-2.0
0a9752bddf1cea7eee05c0a33745a0c4
42.690476
140
0.73079
4.731821
false
false
false
false
tinypass/piano-sdk-for-android
composer-c1x/src/main/java/io/piano/android/composer/c1x/ShowRecommendationsDialogFragment.kt
1
1694
package io.piano.android.composer.c1x import android.content.DialogInterface import android.os.Bundle import android.webkit.WebView import io.piano.android.composer.Composer import io.piano.android.composer.c1x.ShowRecommendationsController.Companion.prepare import io.piano.android.showhelper.BaseJsInterface import io.piano.android.showhelper.BaseShowDialogFragment class ShowRecommendationsDialogFragment : BaseShowDialogFragment { constructor() : super() constructor(widgetId: String, siteId: String, trackingId: String) : super(ShowRecommendationsController.URL) { val args = arguments ?: Bundle() arguments = args.apply { putString(KEY_WIDGET_ID, widgetId) putString(KEY_SITE_ID, siteId) putString(KEY_TRACKING_ID, trackingId) } } private val widgetId: String by lazy { requireNotNull(arguments?.getString(KEY_WIDGET_ID)) } private val siteId: String by lazy { requireNotNull(arguments?.getString(KEY_SITE_ID)) } private val trackingId: String by lazy { arguments?.getString(KEY_TRACKING_ID) ?: "" } override fun WebView.configure(jsInterface: BaseJsInterface?) { prepare( jsInterface as? WidgetJs ?: WidgetJs(widgetId, siteId), this@ShowRecommendationsDialogFragment ) } override fun onCancel(dialog: DialogInterface) { super.onCancel(dialog) Composer.getInstance().trackExternalEvent(trackingId) } companion object { private const val KEY_WIDGET_ID = "widgetId" private const val KEY_SITE_ID = "siteId" private const val KEY_TRACKING_ID = "trackingId" } }
apache-2.0
75d97862d18042f6452be254c77b49d2
33.571429
114
0.697166
4.457895
false
false
false
false
Maxr1998/home-assistant-Android
app/src/main/java/io/homeassistant/android/ApiClient.kt
1
4288
package io.homeassistant.android import android.content.Context import android.content.SharedPreferences import android.util.Log import okhttp3.OkHttpClient import okhttp3.internal.tls.OkHostnameVerifier import java.net.HttpURLConnection import java.security.GeneralSecurityException import java.security.KeyStore import java.security.MessageDigest import java.security.cert.CertificateException import java.security.cert.X509Certificate import java.util.* import java.util.concurrent.TimeUnit import javax.net.ssl.* import javax.security.auth.x500.X500Principal import kotlin.experimental.and object ApiClient { @JvmStatic inline fun get(context: Context, crossinline callback: ((Boolean, Int, String?) -> Unit)): OkHttpClient { val trustManager = CustomTrustManager(Utils.getPrefs(context)) return OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .hostnameVerifier { hostname, session -> if (OkHostnameVerifier.INSTANCE.verify(hostname, session) || Utils.getAllowedHostMismatches(context).contains(hostname)) { return@hostnameVerifier true } callback(false, CommunicationHandler.FAILURE_REASON_SSL_MISMATCH, null) false } .authenticator { _, response -> Log.d(HassService.TAG, "Authenticator running..") if (response.code() == HttpURLConnection.HTTP_UNAUTHORIZED) { callback(false, CommunicationHandler.FAILURE_REASON_BASIC_AUTH, null) } null } .sslSocketFactory(trustManager.getSocketFactory(), trustManager) .build() } class CustomTrustManager(private val prefs: SharedPreferences) : X509TrustManager { private val defaultTrustManager = try { val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()) trustManagerFactory.init(null as KeyStore?) val trustManagers = trustManagerFactory.trustManagers if (trustManagers.size != 1 || trustManagers[0] !is X509TrustManager) { throw IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers)) } trustManagers[0] as X509TrustManager } catch (e: GeneralSecurityException) { throw AssertionError() // The system has no TLS. Just give up. } override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) { defaultTrustManager.checkClientTrusted(chain, authType) } override fun checkServerTrusted(chain: Array<out X509Certificate>, authType: String?) { try { defaultTrustManager.checkServerTrusted(chain, authType) } catch (e: CertificateException) { val hash = chain[0].encoded.toSHA256String() if (prefs.getAllowedSSLCerts().contains(hash)) return val certNameString = chain[0].subjectX500Principal.getName(X500Principal.RFC1779) + "|" + chain[0].issuerX500Principal.getName(X500Principal.RFC1779) + "|" + hash throw CertificateException(certNameString, e) } } override fun getAcceptedIssuers(): Array<X509Certificate> { return defaultTrustManager.acceptedIssuers } fun getSocketFactory(): SSLSocketFactory = try { SSLContext.getInstance("TLS").apply { init(null, arrayOf<TrustManager>(this@CustomTrustManager), null) }.socketFactory } catch (e: GeneralSecurityException) { throw AssertionError() // The system has no TLS. Just give up. } private fun ByteArray.toSHA256String(): String = MessageDigest.getInstance("SHA-256").digest(this).bytesToHex() private fun ByteArray.bytesToHex(): String { val result = StringBuffer() for (b: Byte in this) result.append(Integer.toString((b.and(0xff.toByte())) + 0x100, 16).substring(1)) return result.toString() } } }
gpl-3.0
10b06af77be4ea4698baa6f83a097778
43.677083
142
0.641791
5.229268
false
false
false
false
http4k/http4k
http4k-cloudevents/src/test/kotlin/io/cloudevents/http4k/CSVFormat.kt
1
2545
package io.cloudevents.http4k import io.cloudevents.CloudEvent import io.cloudevents.SpecVersion import io.cloudevents.core.builder.CloudEventBuilder import io.cloudevents.core.data.BytesCloudEventData import io.cloudevents.core.format.EventFormat import io.cloudevents.rw.CloudEventDataMapper import io.cloudevents.types.Time import java.net.URI import java.nio.charset.StandardCharsets.UTF_8 import java.util.Base64 import java.util.Objects import java.util.regex.Pattern class CSVFormat : EventFormat { override fun serialize(event: CloudEvent) = java.lang.String.join( ",", event.specVersion.toString(), event.id, event.type, event.source.toString(), Objects.toString(event.dataContentType), Objects.toString(event.dataSchema), Objects.toString(event.subject), if (event.time != null) Time.writeTime(event.time) else "null", if (event.data != null) String( Base64.getEncoder().encode(event.data?.toBytes() ?: ByteArray(0)), UTF_8 ) else "null" ).toByteArray() override fun deserialize(bytes: ByteArray, mapper: CloudEventDataMapper<*>): CloudEvent { val splitted = String(bytes, UTF_8).split(Pattern.quote(",").toRegex()) val sv = SpecVersion.parse(splitted[0]) val id = splitted[1] val type = splitted[2] val source = URI.create(splitted[3]) val datacontenttype = if (splitted[4] == "null") null else splitted[4] val dataschema = if (splitted[5] == "null") null else URI.create(splitted[5]) val subject = if (splitted[6] == "null") null else splitted[6] val time = if (splitted[7] == "null") null else Time.parseTime(splitted[7]) val data = if (splitted[8] == "null") null else Base64.getDecoder().decode(splitted[8].toByteArray()) val builder = CloudEventBuilder.fromSpecVersion(sv) .withId(id) .withType(type) .withSource(source) if (datacontenttype != null) builder.withDataContentType(datacontenttype) if (dataschema != null) builder.withDataSchema(dataschema) if (subject != null) builder.withSubject(subject) if (time != null) builder.withTime(time) if (data != null) builder.withData(mapper.map(BytesCloudEventData.wrap(data))) return builder.build() } override fun deserializableContentTypes(): Set<String> = setOf(serializedContentType()) override fun serializedContentType(): String = "application/cloudevents+csv" }
apache-2.0
5cc5a762e54b2733b77de8b47ebe8f5e
42.135593
109
0.6778
3.781575
false
false
false
false
googlecreativelab/digital-wellbeing-experiments-toolkit
notifications/notifications-listener/app/src/main/java/com/digitalwellbeingexperiments/toolkit/notificationlistener/NotificationListAdapter.kt
1
2116
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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.digitalwellbeingexperiments.toolkit.notificationlistener import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView class NotificationListAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private val items = ArrayList<NotificationItem>() fun setData(newItems: List<NotificationItem>) { items.clear() items.addAll(newItems) items.sortBy { it.postTime } notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return ViewHolder( LayoutInflater.from(parent.context).inflate( R.layout.list_item_notification, parent, false ) ) } override fun getItemCount() = items.size override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val item = items[position] holder.itemView.apply { findViewById<TextView>(R.id.app_name).text = context.packageManager.getApplicationLabel(item.packageName) findViewById<TextView>(R.id.notification_timestamp).text = formatTimestamp(item.postTime) findViewById<TextView>(R.id.notification_title).text = item.title findViewById<TextView>(R.id.notification_message).text = item.text } } } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
apache-2.0
b0d4eaf334a31755c105cb728571ee16
36.140351
117
0.70983
4.702222
false
false
false
false
asarkar/spring
touchstone/src/main/kotlin/execution/gradle/GradleAgent.kt
1
3456
package org.abhijitsarkar.touchstone.execution.gradle import org.gradle.tooling.GradleConnector import org.gradle.tooling.ProjectConnection import org.slf4j.LoggerFactory import java.io.ByteArrayOutputStream import java.net.URI import java.nio.charset.StandardCharsets.UTF_8 import java.nio.file.Files import java.nio.file.Path /** * @author Abhijit Sarkar */ interface GradleAgent { companion object { internal fun isGradleProject(path: Path) = Files.isDirectory(path) && Files.exists(path.resolve("build.gradle")) } fun build(path: Path, gradleTasks: Array<String> = emptyArray()) } class GradleAgentImpl(private val gradleProperties: GradleProperties) : GradleAgent { companion object { private val LOGGER = LoggerFactory.getLogger(GradleAgent::class.java) } private fun connection(path: Path): ProjectConnection { val gradleDistroUrl: URI? = gradleDistroUrl(path) return if (gradleDistroUrl != null) { LOGGER.debug("Using Gradle distribution: {} defined by the project: {}.", gradleDistroUrl, path.fileName) GradleConnector.newConnector() .useDistribution(gradleDistroUrl) .forProjectDirectory(path.toFile()) } else { GradleConnector.newConnector() .forProjectDirectory(path.toFile()) } .connect() } internal fun gradleDistroUrl(path: Path) = path .resolve("gradle") .resolve("wrapper") .resolve("gradle-wrapper.properties") .let { if (Files.exists(it)) { Files.readAllLines(it, UTF_8) .filter { it.contains("distributionUrl") && it.contains("=") } .map { it.split("=".toRegex(), 2)[1] } .map { it.replace("\\\\".toRegex(), "") } .firstOrNull() ?.let(URI::create) } else { null } } override fun build(path: Path, gradleTasks: Array<String>) { val tasks = if (gradleTasks.isEmpty()) gradleProperties.tasks else gradleTasks LOGGER.info("Running Gradle tasks: {} on project: {}", tasks, path.fileName) val out = ByteArrayOutputStream() val err = ByteArrayOutputStream() connection(path) .run { try { with(newBuild()) { forTasks(*tasks) if (gradleProperties.options.isNotEmpty()) { withArguments(*gradleProperties.options) } setStandardOutput(out) setStandardError(err) run() } } finally { if (out.size() > 0) { LOGGER.debug("Build output:\n{}", out.toString(UTF_8.name())) } if (err.size() > 0) { LOGGER.warn("Build has the following warnings/errors:\n{}", err.toString(UTF_8.name())) } out.close() err.close() close() } } } }
gpl-3.0
a01958fbd0369a5b6cc28dffdce4b71d
34.27551
120
0.503183
5.150522
false
false
false
false
xiaopansky/Sketch
sample/src/main/java/me/panpf/sketch/sample/ui/ShapeSizeImageShaperTestFragment.kt
1
4852
package me.panpf.sketch.sample.ui import android.os.Bundle import android.view.View import android.widget.ImageView import android.widget.SeekBar import kotlinx.android.synthetic.main.fragment_resize.* import me.panpf.sketch.display.TransitionImageDisplayer import me.panpf.sketch.request.ShapeSize import me.panpf.sketch.sample.AssetImage import me.panpf.sketch.sample.base.BaseFragment import me.panpf.sketch.sample.base.BindContentView import me.panpf.sketch.sample.R @BindContentView(R.layout.fragment_resize) class ShapeSizeImageShaperTestFragment : BaseFragment() { private var widthProgress = 50 private var heightProgress = 50 private var scaleType: ImageView.ScaleType = ImageView.ScaleType.FIT_CENTER private var currentCheckedButton: View? = null override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) image_resizeFragment.options.displayer = TransitionImageDisplayer() seekBar_resizeFragment_width.max = 100 seekBar_resizeFragment_width.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { if (progress < 20) { seekBar_resizeFragment_width.progress = 20 return } val width = (seekBar_resizeFragment_width.progress / 100f * 1000).toInt() text_resizeFragment_width.text = String.format("%d/%d", width, 1000) } override fun onStartTrackingTouch(seekBar: SeekBar) { } override fun onStopTrackingTouch(seekBar: SeekBar) { widthProgress = seekBar_resizeFragment_width.progress apply(currentCheckedButton) } }) seekBar_resizeFragment_width.progress = widthProgress seekBar_resizeFragment_height.max = 100 seekBar_resizeFragment_height.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { if (progress < 20) { seekBar_resizeFragment_height.progress = 20 return } val height = (seekBar_resizeFragment_height.progress / 100f * 1000).toInt() text_resizeFragment_height.text = String.format("%d/%d", height, 1000) } override fun onStartTrackingTouch(seekBar: SeekBar) { } override fun onStopTrackingTouch(seekBar: SeekBar) { heightProgress = seekBar_resizeFragment_height.progress apply(currentCheckedButton) } }) seekBar_resizeFragment_height.progress = heightProgress button_resizeFragment_fixStart.tag = ImageView.ScaleType.FIT_START button_resizeFragment_fixCenter.tag = ImageView.ScaleType.FIT_CENTER button_resizeFragment_fixEnd.tag = ImageView.ScaleType.FIT_END button_resizeFragment_fixXY.tag = ImageView.ScaleType.FIT_XY button_resizeFragment_center.tag = ImageView.ScaleType.CENTER button_resizeFragment_centerCrop.tag = ImageView.ScaleType.CENTER_CROP button_resizeFragment_centerInside.tag = ImageView.ScaleType.CENTER_INSIDE button_resizeFragment_matrix.tag = ImageView.ScaleType.MATRIX val buttonOnClickListener = View.OnClickListener { v -> scaleType = v.tag as ImageView.ScaleType apply(v) } button_resizeFragment_fixStart.setOnClickListener(buttonOnClickListener) button_resizeFragment_fixCenter.setOnClickListener(buttonOnClickListener) button_resizeFragment_fixEnd.setOnClickListener(buttonOnClickListener) button_resizeFragment_fixXY.setOnClickListener(buttonOnClickListener) button_resizeFragment_center.setOnClickListener(buttonOnClickListener) button_resizeFragment_centerCrop.setOnClickListener(buttonOnClickListener) button_resizeFragment_centerInside.setOnClickListener(buttonOnClickListener) button_resizeFragment_matrix.setOnClickListener(buttonOnClickListener) if (currentCheckedButton == null) { currentCheckedButton = button_resizeFragment_fixCenter } apply(currentCheckedButton) } private fun apply(button: View?) { val width = (widthProgress / 100f * 1000).toInt() val height = (heightProgress / 100f * 1000).toInt() image_resizeFragment.options.shapeSize = ShapeSize(width, height, scaleType) image_resizeFragment.displayImage(AssetImage.MEI_NV) currentCheckedButton?.isEnabled = true button?.isEnabled = false currentCheckedButton = button } }
apache-2.0
e979e7cec65e23ef79524fb6aa3220b6
42.321429
107
0.694353
4.966223
false
false
false
false
square/duktape-android
zipline/src/engineTest/kotlin/app/cash/zipline/StrictModeTest.kt
1
1762
/* * Copyright (C) 2022 Block, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.cash.zipline import kotlin.test.AfterTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith /** * Confirm our JavaScript engine executes in strict mode. * * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode */ class StrictModeTest { private val quickJs = QuickJs.create() @AfterTest fun tearDown() { quickJs.close() } @Test fun quickJsIsStrictInEvaluate() { val code = """ |const obj2 = { get x() { return 17; } }; |obj2.x = 5; // throws a TypeError """.trimMargin() val e = assertFailsWith<Exception> { quickJs.evaluate(code, "shouldFailInStrictMode.js") } assertEquals("no setter for property", e.message) } @Test fun quickJsIsStrictInCompileAndRun() { val code = """ |const obj2 = { get x() { return 17; } }; |obj2.x = 5; // throws a TypeError """.trimMargin() val bytecode = quickJs.compile(code, "shouldFailInStrictMode.js") val e = assertFailsWith<Exception> { quickJs.execute(bytecode) } assertEquals("no setter for property", e.message) } }
apache-2.0
bcbf5fff804f326f29cd28e2a5e0cc3b
26.107692
80
0.678207
3.872527
false
true
false
false
alashow/music-android
modules/core-playback/src/main/java/tm/alashow/datmusic/playback/AudioFocusHelper.kt
1
4651
/* * Copyright (C) 2021, Alashov Berkeli * All rights reserved. */ package tm.alashow.datmusic.playback import android.content.Context import android.content.Context.AUDIO_SERVICE import android.media.AudioAttributes import android.media.AudioFocusRequest import android.media.AudioManager import android.media.AudioManager.AUDIOFOCUS_GAIN import android.media.AudioManager.AUDIOFOCUS_LOSS import android.media.AudioManager.AUDIOFOCUS_LOSS_TRANSIENT import android.media.AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK import android.media.AudioManager.AUDIOFOCUS_REQUEST_GRANTED import android.media.AudioManager.FLAG_PLAY_SOUND import android.media.AudioManager.OnAudioFocusChangeListener import android.media.AudioManager.STREAM_MUSIC import dagger.hilt.android.qualifiers.ApplicationContext import javax.inject.Inject import tm.alashow.base.ui.utils.extensions.systemService import tm.alashow.base.util.extensions.isOreo typealias OnAudioFocusGain = AudioFocusHelper.() -> Unit typealias OnAudioFocusLoss = AudioFocusHelper.() -> Unit typealias OnAudioFocusLossTransient = AudioFocusHelper.() -> Unit typealias OnAudioFocusLossTransientCanDuck = AudioFocusHelper.() -> Unit interface AudioFocusHelper { var isAudioFocusGranted: Boolean fun requestPlayback(): Boolean fun abandonPlayback() fun onAudioFocusGain(audioFocusGain: OnAudioFocusGain) fun onAudioFocusLoss(audioFocusLoss: OnAudioFocusLoss) fun onAudioFocusLossTransient(audioFocusLossTransient: OnAudioFocusLossTransient) fun onAudioFocusLossTransientCanDuck(audioFocusLossTransientCanDuck: OnAudioFocusLossTransientCanDuck) fun setVolume(volume: Int) } class AudioFocusHelperImpl @Inject constructor( @ApplicationContext context: Context ) : AudioFocusHelper, OnAudioFocusChangeListener { private val audioManager: AudioManager = context.systemService(AUDIO_SERVICE) private var audioFocusGainCallback: OnAudioFocusGain = {} private var audioFocusLossCallback: OnAudioFocusLoss = {} private var audioFocusLossTransientCallback: OnAudioFocusLossTransient = {} private var audioFocusLossTransientCanDuckCallback: OnAudioFocusLossTransientCanDuck = {} override fun onAudioFocusChange(focusChange: Int) { when (focusChange) { AUDIOFOCUS_GAIN -> audioFocusGainCallback() AUDIOFOCUS_LOSS -> audioFocusLossCallback() AUDIOFOCUS_LOSS_TRANSIENT -> audioFocusLossTransientCallback() AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> audioFocusLossTransientCanDuckCallback() } } override var isAudioFocusGranted: Boolean = false override fun requestPlayback(): Boolean { val state = if (isOreo()) { val attr = AudioAttributes.Builder().apply { setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) setUsage(AudioAttributes.USAGE_MEDIA) }.build() audioManager.requestAudioFocus( AudioFocusRequest.Builder(AUDIOFOCUS_GAIN) .setAudioAttributes(attr) .setAcceptsDelayedFocusGain(true) .setOnAudioFocusChangeListener(this) .build() ) } else audioManager.requestAudioFocus(this, STREAM_MUSIC, AUDIOFOCUS_GAIN) return state == AUDIOFOCUS_REQUEST_GRANTED } override fun abandonPlayback() { if (isOreo()) { val attr = AudioAttributes.Builder().apply { setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) setUsage(AudioAttributes.USAGE_MEDIA) }.build() audioManager.abandonAudioFocusRequest( AudioFocusRequest.Builder(AUDIOFOCUS_GAIN) .setOnAudioFocusChangeListener(this) .setAudioAttributes(attr) .build() ) } else audioManager.abandonAudioFocus(this) } override fun onAudioFocusGain(audioFocusGain: OnAudioFocusGain) { audioFocusGainCallback = audioFocusGain } override fun onAudioFocusLoss(audioFocusLoss: OnAudioFocusLoss) { audioFocusLossCallback = audioFocusLoss } override fun onAudioFocusLossTransient(audioFocusLossTransient: OnAudioFocusLossTransient) { audioFocusLossTransientCallback = audioFocusLossTransient } override fun onAudioFocusLossTransientCanDuck(audioFocusLossTransientCanDuck: OnAudioFocusLossTransientCanDuck) { audioFocusLossTransientCanDuckCallback = audioFocusLossTransientCanDuck } override fun setVolume(volume: Int) { audioManager.adjustVolume(volume, FLAG_PLAY_SOUND) } }
apache-2.0
d39acbcbcddea9a9da8c8bd9e7efa721
39.443478
117
0.735541
5.03355
false
false
false
false
mehulsbhatt/emv-bertlv
src/test/java/io/github/binaryfoo/DecodedDataTest.kt
1
2155
package io.github.binaryfoo import org.hamcrest.MatcherAssert.assertThat import org.junit.Test import io.github.binaryfoo.tlv.BerTlv import io.github.binaryfoo.tlv.Tag import org.hamcrest.Matchers import org.hamcrest.Matchers.`is` import org.hamcrest.MatcherAssert import kotlin.test.assertEquals import kotlin.test.assertNull public class DecodedDataTest { Test public fun hexDumpReferenceIncludesTlvTagAndLengthPosition() { val decoded = DecodedData.fromTlv(BerTlv.newInstance(Tag.fromHex("9F1B"), "112233"), EmvTags.METADATA, "", 42, 48) assertEquals(42..47, decoded.positionInHexDump) assertEquals(42..43, decoded.tagPositionInHexDump) assertEquals(44..44, decoded.lengthPositionInHexDump) } Test public fun hexDumpReferenceWithTagOnlyHasNoTagOrLengthPosition() { val decoded = DecodedData.withTag(Tag.fromHex("9F1B"), EmvTags.METADATA, "112233", 42, 45) assertEquals(42..44, decoded.positionInHexDump) assertEquals(null, decoded.tagPositionInHexDump) assertEquals(null, decoded.lengthPositionInHexDump) } Test public fun hexDumpReferenceWithNoTagOrTlv() { val decoded = DecodedData.primitive("332211", "", 42, 45) assertEquals(42..44, decoded.positionInHexDump) assertEquals(null, decoded.tagPositionInHexDump) assertEquals(null, decoded.lengthPositionInHexDump) } Test public fun findAll() { val first91 = DecodedData(Tag.fromHex("91"), "1st 91", "value") val second91 = DecodedData(Tag.fromHex("91"), "2nd 91", "") val nested91 = DecodedData(Tag.fromHex("91"), "nested 91", "value") val decoded = listOf(DecodedData(Tag.fromHex("6C"), "template", "", kids = listOf( DecodedData(Tag.fromHex("92"), "92", ""), first91, second91, DecodedData(Tag.fromHex("93"), "93", "", kids = listOf(nested91)) ))) assertThat(decoded.findAllForTag(Tag.fromHex("91")), `is`(listOf(first91, second91, nested91))) assertThat(decoded.findAllForValue("value"), `is`(listOf(first91, nested91))) } }
mit
ab7463875638d333dbbe651e842f7662
37.482143
122
0.683063
3.990741
false
true
false
false
googlecodelabs/android-paging
advanced/end/app/src/main/java/com/example/android/codelabs/paging/ui/ReposAdapter.kt
1
2674
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.codelabs.paging.ui import android.view.ViewGroup import androidx.paging.PagingDataAdapter import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView.ViewHolder import com.example.android.codelabs.paging.R /** * Adapter for the list of repositories. */ class ReposAdapter : PagingDataAdapter<UiModel, ViewHolder>(UIMODEL_COMPARATOR) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return if (viewType == R.layout.repo_view_item) { RepoViewHolder.create(parent) } else { SeparatorViewHolder.create(parent) } } override fun getItemViewType(position: Int): Int { return when (getItem(position)) { is UiModel.RepoItem -> R.layout.repo_view_item is UiModel.SeparatorItem -> R.layout.separator_view_item null -> throw UnsupportedOperationException("Unknown view") } } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val uiModel = getItem(position) uiModel.let { when (uiModel) { is UiModel.RepoItem -> (holder as RepoViewHolder).bind(uiModel.repo) is UiModel.SeparatorItem -> (holder as SeparatorViewHolder).bind(uiModel.description) } } } companion object { private val UIMODEL_COMPARATOR = object : DiffUtil.ItemCallback<UiModel>() { override fun areItemsTheSame(oldItem: UiModel, newItem: UiModel): Boolean { return (oldItem is UiModel.RepoItem && newItem is UiModel.RepoItem && oldItem.repo.fullName == newItem.repo.fullName) || (oldItem is UiModel.SeparatorItem && newItem is UiModel.SeparatorItem && oldItem.description == newItem.description) } override fun areContentsTheSame(oldItem: UiModel, newItem: UiModel): Boolean = oldItem == newItem } } }
apache-2.0
e76563f590b225c21d78ddbd3df27756
37.768116
101
0.663052
4.775
false
false
false
false
MFlisar/Lumberjack
library-filelogger/src/main/java/com/michaelflisar/lumberjack/FileLoggingTree.kt
1
5296
package com.michaelflisar.lumberjack import android.os.Handler import android.os.HandlerThread import android.util.Log import ch.qos.logback.classic.Level import ch.qos.logback.classic.LoggerContext import ch.qos.logback.classic.encoder.PatternLayoutEncoder import ch.qos.logback.classic.spi.ILoggingEvent import ch.qos.logback.core.rolling.* import ch.qos.logback.core.util.FileSize import com.michaelflisar.lumberjack.data.StackData import org.slf4j.LoggerFactory import org.slf4j.MarkerFactory import timber.log.BaseTree /** * Created by Michael on 17.10.2016. */ class FileLoggingTree( setup: FileLoggingSetup? ) : BaseTree() { private var handlerThread: HandlerThread? = null private var backgroundHandler: Handler? = null init { if (setup == null) { throw RuntimeException("You can't create a FileLoggingTree without providing a setup!") } if (setup.logOnBackgroundThread) { handlerThread = HandlerThread("FileLoggingTree").apply { start() backgroundHandler = Handler(looper) } } init(setup) } private fun init(setup: FileLoggingSetup) { val lc = LoggerFactory.getILoggerFactory() as LoggerContext lc.reset() // 1) FileLoggingSetup - Encoder for File val encoder1 = PatternLayoutEncoder() encoder1.context = lc encoder1.pattern = setup.setup.logPattern encoder1.start() // 2) FileLoggingSetup - rolling file appender val rollingFileAppender = RollingFileAppender<ILoggingEvent>() rollingFileAppender.isAppend = true rollingFileAppender.context = lc //rollingFileAppender.setFile(setup.folder + "/" + setup.fileName + "." + setup.fileExtension); // 3) FileLoggingSetup - Rolling policy (one log per day) var triggeringPolicy: TriggeringPolicy<ILoggingEvent>? = null when (setup) { is FileLoggingSetup.DateFiles -> { val timeBasedRollingPolicy = TimeBasedRollingPolicy<ILoggingEvent>() timeBasedRollingPolicy.fileNamePattern = setup.folder + "/" + setup.setup.fileName + "_%d{yyyyMMdd}." + setup.setup.fileExtension timeBasedRollingPolicy.maxHistory = setup.setup.logsToKeep timeBasedRollingPolicy.isCleanHistoryOnStart = true timeBasedRollingPolicy.setParent(rollingFileAppender) timeBasedRollingPolicy.context = lc triggeringPolicy = timeBasedRollingPolicy } is FileLoggingSetup.NumberedFiles -> { val fixedWindowRollingPolicy = FixedWindowRollingPolicy() fixedWindowRollingPolicy.fileNamePattern = setup.folder + "/" + setup.setup.fileName + "%i." + setup.setup.fileExtension fixedWindowRollingPolicy.minIndex = 1 fixedWindowRollingPolicy.maxIndex = setup.setup.logsToKeep fixedWindowRollingPolicy.setParent(rollingFileAppender) fixedWindowRollingPolicy.context = lc val sizeBasedTriggeringPolicy = SizeBasedTriggeringPolicy<ILoggingEvent>() sizeBasedTriggeringPolicy.maxFileSize = FileSize.valueOf(setup.sizeLimit) triggeringPolicy = sizeBasedTriggeringPolicy rollingFileAppender.file = setup.baseFilePath rollingFileAppender.rollingPolicy = fixedWindowRollingPolicy fixedWindowRollingPolicy.start() } } triggeringPolicy.start() rollingFileAppender.triggeringPolicy = triggeringPolicy rollingFileAppender.encoder = encoder1 rollingFileAppender.start() // add the newly created appenders to the root logger; // qualify Logger to disambiguate from org.slf4j.Logger val root = mLogger as ch.qos.logback.classic.Logger root.detachAndStopAllAppenders() root.addAppender(rollingFileAppender) // enable all log level root.level = Level.ALL } override fun log(priority: Int, prefix: String, message: String, t: Throwable?, stackData: StackData) { val logMessage = formatLine(prefix, message) backgroundHandler?.post { doRealLog(priority, logMessage) } ?: doRealLog(priority, logMessage) } private val WTF_MARKER = MarkerFactory.getMarker("WTF-") private fun doRealLog(priority: Int, logMessage: String) { // slf4j: TRACE < DEBUG < INFO < WARN < ERROR < FATAL // Android: VERBOSE < DEBUG < INFO < WARN < ERROR < ASSERT when (priority) { Log.VERBOSE -> mLogger.trace(logMessage) Log.DEBUG -> mLogger.debug(logMessage) Log.INFO -> mLogger.info(logMessage) Log.WARN -> mLogger.warn(logMessage) Log.ERROR -> mLogger.error(logMessage) Log.ASSERT -> mLogger.error(WTF_MARKER, logMessage) } } companion object { const val DATE_FILE_NAME_PATTERN = "%s_\\d{8}.%s" const val NUMBERED_FILE_NAME_PATTERN = "%s\\d*.%s" internal var mLogger = LoggerFactory.getLogger(FileLoggingTree::class.java)//Logger.ROOT_LOGGER_NAME); } }
apache-2.0
76c8d580982644046654e12bf2a7a08d
36.835714
108
0.653134
4.690877
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/data/sync/SyncNotification.kt
1
1664
package de.westnordost.streetcomplete.data.sync import android.app.* import android.content.Context import android.content.Intent import androidx.core.app.NotificationChannelCompat import androidx.core.app.NotificationManagerCompat.IMPORTANCE_LOW import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import de.westnordost.streetcomplete.ApplicationConstants.NAME import de.westnordost.streetcomplete.ApplicationConstants.NOTIFICATIONS_CHANNEL_SYNC import de.westnordost.streetcomplete.MainActivity import de.westnordost.streetcomplete.R /** Creates the notification for syncing in the Android notifications area. Used both by the upload * and by the download service. */ fun createSyncNotification(context: Context): Notification { val intent = Intent(context, MainActivity::class.java) val pendingIntent = PendingIntent.getActivity(context, 0, intent, 0) val manager = NotificationManagerCompat.from(context) if (manager.getNotificationChannelCompat(NOTIFICATIONS_CHANNEL_SYNC) == null) { manager.createNotificationChannel( NotificationChannelCompat.Builder(NOTIFICATIONS_CHANNEL_SYNC, IMPORTANCE_LOW) .setName(context.getString(R.string.notification_channel_sync)) .build() ) } return NotificationCompat.Builder(context, NOTIFICATIONS_CHANNEL_SYNC) .setSmallIcon(R.mipmap.ic_notification) .setContentTitle(NAME) .setContentText(context.resources.getString(R.string.notification_syncing)) .setContentIntent(pendingIntent) .setCategory(NotificationCompat.CATEGORY_PROGRESS) .build() }
gpl-3.0
db53e7dfcd14489540e90200683c7ab5
45.222222
99
0.777644
4.952381
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/data/quest/QuestController.kt
1
10062
package de.westnordost.streetcomplete.data.quest import android.util.Log import de.westnordost.streetcomplete.ApplicationConstants import de.westnordost.streetcomplete.data.meta.KEYS_THAT_SHOULD_BE_REMOVED_WHEN_SHOP_IS_REPLACED import de.westnordost.streetcomplete.data.osm.edits.* import de.westnordost.streetcomplete.data.osm.edits.delete.DeletePoiNodeAction import de.westnordost.streetcomplete.data.osm.edits.split_way.SplitPolylineAtPosition import de.westnordost.streetcomplete.data.osm.edits.split_way.SplitWayAction import de.westnordost.streetcomplete.data.osm.edits.update_tags.* import de.westnordost.streetcomplete.data.osm.geometry.ElementPolylinesGeometry import de.westnordost.streetcomplete.data.osm.mapdata.Element import de.westnordost.streetcomplete.data.osm.mapdata.LatLon import de.westnordost.streetcomplete.data.osm.mapdata.Way import de.westnordost.streetcomplete.data.osm.osmquests.OsmQuest import de.westnordost.streetcomplete.data.osm.osmquests.OsmQuestController import de.westnordost.streetcomplete.data.osmnotes.edits.NoteEditAction import de.westnordost.streetcomplete.data.osmnotes.edits.NoteEditsController import de.westnordost.streetcomplete.data.osmnotes.notequests.OsmNoteQuest import de.westnordost.streetcomplete.data.osmnotes.notequests.OsmNoteQuestController import de.westnordost.streetcomplete.quests.note_discussion.NoteAnswer import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import javax.inject.Inject import javax.inject.Singleton import kotlin.collections.ArrayList /** Controls the workflow of quests: Solving them, hiding them instead, splitting the way instead, * undoing, etc. */ @Singleton class QuestController @Inject constructor( private val osmQuestController: OsmQuestController, private val osmNoteQuestController: OsmNoteQuestController, private val elementEditsController: ElementEditsController, private val noteEditsController: NoteEditsController, private val mapDataSource: MapDataWithEditsSource ) { /** Create a note for the given OSM Quest instead of answering it. * @return true if successful */ suspend fun createNote( questKey: QuestKey, questTitle: String, text: String, imagePaths: List<String> ): Boolean = withContext(Dispatchers.IO) { val q = get(questKey) ?: return@withContext false var fullText = "Unable to answer \"$questTitle\"" if (q is OsmQuest && q.elementId > 0) { val lowercaseTypeName = q.elementType.name.lowercase() val elementId = q.elementId fullText += " for https://osm.org/$lowercaseTypeName/$elementId" } fullText += " via ${ApplicationConstants.OSM_USER_AGENT}:\n\n$text" noteEditsController.add(0, NoteEditAction.CREATE, q.position, fullText, imagePaths) return@withContext true } /** Create a note at the given position. */ suspend fun createNote( text: String, imagePaths: List<String>, position: LatLon ) = withContext(Dispatchers.IO) { val fullText = "$text\n\nvia ${ApplicationConstants.OSM_USER_AGENT}" noteEditsController.add(0, NoteEditAction.CREATE, position, fullText, imagePaths) } /** Split a way for the given OSM Quest. * @return true if successful */ suspend fun splitWay( q: OsmQuest, splits: List<SplitPolylineAtPosition>, source: String ): Boolean = withContext(Dispatchers.IO) { val w = getOsmElement(q) as? Way ?: return@withContext false val geom = q.geometry as? ElementPolylinesGeometry ?: return@withContext false elementEditsController.add( q.osmElementQuestType, w, geom, source, SplitWayAction(ArrayList(splits)) ) return@withContext true } /** Delete the element referred to by the given OSM quest id. * @return true if successful */ suspend fun deletePoiElement( q: OsmQuest, source: String ): Boolean = withContext(Dispatchers.IO) { val e = getOsmElement(q) ?: return@withContext false Log.d(TAG, "Deleted ${q.elementType.name} #${q.elementId} in frame of quest ${q.type::class.simpleName!!}") elementEditsController.add( q.osmElementQuestType, e, q.geometry, source, DeletePoiNodeAction ) return@withContext true } /** Replaces the previous element which is assumed to be a shop/amenity of sort with another * feature. * @return true if successful */ suspend fun replaceShopElement( q: OsmQuest, tags: Map<String, String>, source: String ): Boolean = withContext(Dispatchers.IO) { val e = getOsmElement(q) ?: return@withContext false val changes = createReplaceShopChanges(e.tags, tags) Log.d(TAG, "Replaced ${q.elementType.name} #${q.elementId} in frame of quest ${q.type::class.simpleName!!} with $changes") elementEditsController.add( q.osmElementQuestType, e, q.geometry, source, UpdateElementTagsAction(changes) ) return@withContext true } private fun createReplaceShopChanges(previousTags: Map<String, String>, newTags: Map<String, String>): StringMapChanges { val changesList = mutableListOf<StringMapEntryChange>() // first remove old tags for ((key, value) in previousTags) { val isOkToRemove = KEYS_THAT_SHOULD_BE_REMOVED_WHEN_SHOP_IS_REPLACED.any { it.matches(key) } if (isOkToRemove && !newTags.containsKey(key)) { changesList.add(StringMapEntryDelete(key, value)) } } // then add new tags for ((key, value) in newTags) { val valueBefore = previousTags[key] if (valueBefore != null) changesList.add(StringMapEntryModify(key, valueBefore, value)) else changesList.add(StringMapEntryAdd(key, value)) } return StringMapChanges(changesList) } /** Apply the user's answer to the given quest. * @return true if successful */ suspend fun solve(quest: Quest, answer: Any, source: String): Boolean { return when(quest) { is OsmNoteQuest -> solveOsmNoteQuest(quest, answer as NoteAnswer) is OsmQuest -> solveOsmQuest(quest, answer, source) else -> throw NotImplementedError() } } suspend fun getOsmElement(quest: OsmQuest): Element? = withContext(Dispatchers.IO) { mapDataSource.get(quest.elementType, quest.elementId) } private suspend fun solveOsmNoteQuest( q: OsmNoteQuest, answer: NoteAnswer ): Boolean = withContext(Dispatchers.IO) { require(answer.text.isNotEmpty()) { "NoteQuest has been answered with an empty comment!" } // for note quests: questId == noteId noteEditsController.add(q.id, NoteEditAction.COMMENT, q.position, answer.text, answer.imagePaths) return@withContext true } private suspend fun solveOsmQuest( q: OsmQuest, answer: Any, source: String ): Boolean = withContext(Dispatchers.IO) { val e = getOsmElement(q) ?: return@withContext false /** When OSM data is being updated (e.g. during download), first that data is persisted to * the database and after that, the quests are updated on the new data. * * Depending on the volume of the data, this may take some seconds. So in this time, OSM * data and the quests are out of sync: If in this time, a quest is solved, the quest may * not be applicable to the element anymore. So we need to check that before trying to * apply the changes. * * Why not synchronize the updating of OSM data and generated quests so that they never can * go out of sync? It was like this (since v32) initially, but it made using the app * (opening quests, solving quests) unusable and seemingly unresponsive while the app was * downloading/updating data. See issue #2876 */ if (q.osmElementQuestType.isApplicableTo(e) == false) return@withContext false val changes = createOsmQuestChanges(q, e, answer) require(!changes.isEmpty()) { "OsmQuest ${q.key} has been answered by the user but there are no changes!" } Log.d(TAG, "Solved a ${q.type::class.simpleName!!} quest: $changes") elementEditsController.add( q.osmElementQuestType, e, q.geometry, source, UpdateElementTagsAction(changes) ) return@withContext true } private fun createOsmQuestChanges(quest: OsmQuest, element: Element, answer: Any) : StringMapChanges { val changesBuilder = StringMapChangesBuilder(element.tags) quest.osmElementQuestType.applyAnswerToUnsafe(answer, changesBuilder) return changesBuilder.create() } /** Make the given quest invisible (per user interaction). */ suspend fun hide(questKey: QuestKey) = withContext(Dispatchers.IO) { when (questKey) { is OsmNoteQuestKey -> osmNoteQuestController.hide(questKey.noteId) is OsmQuestKey -> osmQuestController.hide(questKey) } } /** Unhide all previously hidden quests */ suspend fun unhideAll(): Int = withContext(Dispatchers.IO) { osmQuestController.unhideAll() + osmNoteQuestController.unhideAll() } /** Retrieve the given quest from local database */ suspend fun get(questKey: QuestKey): Quest? = withContext(Dispatchers.IO) { when (questKey) { is OsmNoteQuestKey -> osmNoteQuestController.get(questKey.noteId) is OsmQuestKey -> osmQuestController.get(questKey) } } companion object { private const val TAG = "QuestController" } }
gpl-3.0
3340527d6e6d9b254c1a840442c8b316
38.770751
130
0.673822
4.518186
false
false
false
false
pokk/mvp-magazine
app/src/main/kotlin/taiwan/no1/app/ui/adapter/CommonRecyclerAdapter.kt
1
1859
package taiwan.no1.app.ui.adapter import android.support.v7.widget.RecyclerView import android.view.View import android.view.ViewGroup import taiwan.no1.app.App import taiwan.no1.app.internal.di.components.AdapterComponent import taiwan.no1.app.mvp.models.IVisitable import taiwan.no1.app.ui.adapter.viewholder.BaseViewHolder import taiwan.no1.app.ui.adapter.viewholder.viewtype.IViewTypeFactory import taiwan.no1.app.ui.adapter.viewholder.viewtype.ViewTypeFactory import javax.inject.Inject /** * A common recycler view's adapter for vary view holders. * * @author Jieyi * @since 1/7/17 */ class CommonRecyclerAdapter(var models: List<IVisitable>, val fragmentTag: Int = -1): RecyclerView.Adapter<BaseViewHolder<IVisitable>>() { @Inject lateinit var typeFactory: IViewTypeFactory init { AdapterComponent.Initializer.init(App.appComponent()).inject(CommonRecyclerAdapter@ this) } override fun onBindViewHolder(holder: BaseViewHolder<IVisitable>, position: Int) { holder.initView(this.models[position], position, this) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder<IVisitable> { val itemView: View = View.inflate(parent.context, ViewTypeFactory.TypeResource.values()[viewType].id, null) return this.typeFactory.createViewHolder(viewType, itemView) as BaseViewHolder<IVisitable> } override fun getItemCount(): Int = this.models.size override fun getItemViewType(position: Int): Int = this.models[position].type(this.typeFactory) /** * Add new data list into the recycler view. * * @param newModels new data as belong [IVisitable]. */ fun addItem(newModels: List<IVisitable>) { // TODO: 1/10/17 Maybe memory leak?! this.models = newModels this.notifyDataSetChanged() } }
apache-2.0
9e8530b4652efd279b26e0f9a48b3765
33.444444
115
0.735342
4.006466
false
false
false
false
rusinikita/movies-shmoovies
app/src/main/kotlin/com/nikita/movies_shmoovies/common/utils/PropertyBindingUtils.kt
1
6118
package com.nikita.movies_shmoovies.common.utils import android.app.Activity import android.support.annotation.IdRes import android.support.v4.app.Fragment import android.view.View import java.lang.IllegalStateException import java.util.* import kotlin.properties.ReadOnlyProperty import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty interface UnbindableProperty { fun unbind() } /** * Holds references on all lifecycle related properties to prevent memory leaks. * * [viewContainer] - view container, where view can be found if it not null. * It will help to control binding lifecycle * (for example, use binded views in the [Fragment.onCreateView]). */ class PropertyBinder() { private val bindedProperties = LinkedList<UnbindableProperty>() var viewContainer: View? = null fun register(managed: UnbindableProperty) { synchronized(bindedProperties) { bindedProperties.add(managed) } } fun reset() { // Synchronize to make sure the timing of a unbind() call and new inits do not collide synchronized(bindedProperties) { bindedProperties.forEach { it.unbind() } bindedProperties.clear() viewContainer = null } } } private class ViewProperty<in T, VIEW_TYPE>(private val binder: PropertyBinder, val initializer: (container: View?) -> VIEW_TYPE) : ReadOnlyProperty<T, VIEW_TYPE>, UnbindableProperty { @Volatile var lazyHolder = initLazyProperty() override fun getValue(thisRef: T, property: KProperty<*>): VIEW_TYPE = lazyHolder.value override fun unbind() { lazyHolder = initLazyProperty() } fun initLazyProperty(): Lazy<VIEW_TYPE> { return lazy { binder.register(this) initializer.invoke(binder.viewContainer) } } } private abstract class Property<in T, TYPE>(private val binder: PropertyBinder) : ReadWriteProperty<T, TYPE>, UnbindableProperty { @Volatile protected var lazyHolder = initLazyProperty() override fun unbind() { lazyHolder = initLazyProperty() } override fun setValue(thisRef: T, property: KProperty<*>, value: TYPE) { lazyHolder = initLazyProperty(value) } protected fun initLazyProperty(value: TYPE? = null): Lazy<TYPE?> { return lazy { if (value != null) { binder.register(this) } value } } } private class PropertyReq<in T, TYPE : Any>(binder: PropertyBinder) : Property<T, TYPE>(binder) { override fun getValue(thisRef: T, property: KProperty<*>): TYPE { return lazyHolder.value ?: propertyNotInitialized() } } private class PropertyOpt<in T, TYPE : Any>(binder: PropertyBinder) : Property<T, TYPE?>(binder) { override fun getValue(thisRef: T, property: KProperty<*>) = lazyHolder.value } private fun viewNotFound(id: Int): Nothing = throw IllegalStateException("View with ID $id not found. Probable causes: " + "viewContainer of PropertyBinder didn't set; " + "tried to use property after end of view lifecycle.") private fun propertyNotInitialized(): Nothing = throw IllegalStateException("PropertyReq is null. Probable causes: " + "property didn't initialize before using;" + "tried to use property after end of view lifecycle.") /** * Function to bind views in the fragments instead of **lateinit** directive * to avoid Context leaks (for example, after rotation). * * Binded views can be used in the [Fragment.onCreateView] if [PropertyBinder.viewContainer] was set, * or only **after** [Fragment.onCreateView] otherwise (for example, in the [Fragment.onAttach]). * * Without setting [PropertyBinder.viewContainer] will be thrown IllegalStateException. * * **NOTE**: [PropertyBinder] should be created as soon as possible and shouldn't be null or lazy * **NOTE**: binder.unbind() should be invoked before content view will be destroy. * For example, on [Fragment.onDestroyView]. */ @Suppress("UNCHECKED_CAST") fun <VIEW_TYPE : View> Fragment.bindView(propertyBinder: PropertyBinder, @IdRes id: Int): ReadOnlyProperty<Fragment, VIEW_TYPE> { return ViewProperty(propertyBinder, { viewContainer -> (viewContainer ?: view)?.findViewById(id) as? VIEW_TYPE ?: viewNotFound(id) }) } @Suppress("UNCHECKED_CAST") fun <VIEW_TYPE : View> Fragment.bindViewOpt(propertyBinder: PropertyBinder, @IdRes id: Int): ReadOnlyProperty<Fragment, VIEW_TYPE?> { return ViewProperty(propertyBinder, { viewContainer -> (viewContainer ?: view)?.findViewById(id) as? VIEW_TYPE }) } /** * Functions to bind views in activities. Just for consistency with fragments */ @Suppress("UNCHECKED_CAST") fun <VIEW_TYPE : View> Activity.bindView(propertyBinder: PropertyBinder, @IdRes id: Int): ReadOnlyProperty<Activity, VIEW_TYPE> { return ViewProperty(propertyBinder, { findViewById(id) as? VIEW_TYPE ?: viewNotFound(id) }) } @Suppress("UNCHECKED_CAST") fun <VIEW_TYPE : View> Activity.bindViewOpt(propertyBinder: PropertyBinder, @IdRes id: Int): ReadOnlyProperty<Activity, VIEW_TYPE?> { return ViewProperty(propertyBinder, { findViewById(id) as? VIEW_TYPE }) } /** * Overloaded [bindView] fun for Views. */ @Suppress("UNCHECKED_CAST") fun <VIEW_TYPE : View> View.bindView(propertyBinder: PropertyBinder, @IdRes id: Int): ReadOnlyProperty<View, VIEW_TYPE> { return ViewProperty(propertyBinder, { viewContainer -> (viewContainer ?: this).findViewById(id) as? VIEW_TYPE ?: viewNotFound(id) }) } /** * Function to bind properties in the lifecycle related classes * instead of **lateinit** directive to avoid Context leaks * (for example, after rotation). */ fun <TYPE : Any> bindProperty(propertyBinder: PropertyBinder): ReadWriteProperty<Any, TYPE> { return PropertyReq(propertyBinder) } /** * Same as [bindProperty] but with nullable support */ fun <TYPE : Any> bindPropertyOpt(propertyBinder: PropertyBinder): ReadWriteProperty<Any, TYPE?> { return PropertyOpt(propertyBinder) }
apache-2.0
9134bfd5b796736e02dd17c4f2400899
32.620879
101
0.699412
4.230982
false
false
false
false
bravelocation/yeltzland-android
app/src/main/java/com/bravelocation/yeltzlandnew/views/YouTubeChannelView.kt
1
4243
package com.bravelocation.yeltzlandnew.views import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.* import androidx.compose.material.MaterialTheme.colors import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Refresh import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.bravelocation.yeltzlandnew.dataproviders.YouTubePreviewDataProvider import com.bravelocation.yeltzlandnew.models.LoadingState import com.bravelocation.yeltzlandnew.models.YouTubeVideo import com.bravelocation.yeltzlandnew.ui.AppColors import com.bravelocation.yeltzlandnew.ui.YeltzlandTheme import com.bravelocation.yeltzlandnew.utilities.LinkHelper import com.bravelocation.yeltzlandnew.viewmodels.YouTubeViewModel import com.google.accompanist.swiperefresh.SwipeRefresh import com.google.accompanist.swiperefresh.rememberSwipeRefreshState @ExperimentalAnimationApi @Composable fun YouTubeChannelView(model: YouTubeViewModel) { val videos: List<YouTubeVideo> by model.videos.collectAsState() val loadingState: LoadingState by model.loadingState.observeAsState(LoadingState.LOADING) val swipeRefreshState = rememberSwipeRefreshState(false) val context = LocalContext.current YeltzlandTheme { Scaffold(topBar = { TopAppBar( title = { TitleWithLogo(title = "YeltzTV") }, actions = { IconButton(onClick = { model.load() }) { Icon(Icons.Outlined.Refresh,"Reload", tint = colors.onPrimary) } }, backgroundColor = colors.primary, contentColor = colors.onPrimary ) }) { padding -> SwipeRefresh( state = swipeRefreshState, onRefresh = { model.load() } ) { Box(modifier = Modifier .fillMaxSize() .background(colors.background) .padding(padding) ) { LazyColumn( modifier = Modifier.padding(bottom = 56.dp) ) { items(videos) { video -> YouTubeVideoView(video) } item { TextButton( onClick = { LinkHelper.openExternalUrl(context, model.channelUrl) } ) { Text( when (loadingState) { LoadingState.LOADING -> { "Loading ..." } else -> { "View all Yeltz TV videos ..." } }, color = AppColors.linkColor(), modifier = Modifier .padding(vertical = 8.dp, horizontal = 8.dp) ) } } } LoadingOverlay(loadingState == LoadingState.LOADING) ErrorMessageOverlay(isDisplayed = loadingState == LoadingState.ERROR) } } } } } @ExperimentalAnimationApi @Preview @Composable fun PreviewYouTubeChannelView() { YouTubeChannelView(YouTubeViewModel(YouTubePreviewDataProvider())) }
mit
45bd9390bf1617aa63b30ec6eb95ce23
39.037736
93
0.581664
5.812329
false
false
false
false
coinbase/coinbase-java
app/src/main/java/com/coinbase/sample/AccountsActivity.kt
1
4207
/* * Copyright 2018 Coinbase, 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.coinbase.sample import android.annotation.SuppressLint import android.graphics.Color import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.coinbase.resources.accounts.Account import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.activity_accounts.* import kotlinx.android.synthetic.main.item_account.view.* import java.util.* class AccountsActivity : AppCompatActivity() { private val onDestroyDisposable = CompositeDisposable() private val accountsAdapter = AccountsAdapter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_accounts) accountsRecyclerView.layoutManager = LinearLayoutManager(applicationContext) accountsRecyclerView.adapter = accountsAdapter supportActionBar?.setDisplayHomeAsUpEnabled(true) coinbase.accountResource .accountsRx .observeOn(AndroidSchedulers.mainThread()) .addToDisposable(onDestroyDisposable) .withProgress(this::showProgress) .subscribe({ pagedResponse -> accountsAdapter.setAccounts(pagedResponse.data) }) { throwable -> showError(throwable) } } override fun onDestroy() { super.onDestroy() onDestroyDisposable.dispose() } private fun showProgress(show: Boolean) { progressBar.isVisible = show accountsRecyclerView.isVisible = !show } internal inner class AccountsAdapter : RecyclerView.Adapter<AccountsActivity.AccountViewHolder>() { private val accountsList = ArrayList<Account>() fun setAccounts(transactions: List<Account>) { accountsList.clear() accountsList.addAll(transactions) notifyDataSetChanged() } override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): AccountsActivity.AccountViewHolder { val inflater = LayoutInflater.from(viewGroup.context) val view = inflater.inflate(R.layout.item_account, viewGroup, false) return [email protected](view) } override fun onBindViewHolder(accountViewHolder: AccountsActivity.AccountViewHolder, i: Int) { accountViewHolder.bind(accountsList[i]) } override fun getItemCount(): Int { return accountsList.size } } internal inner class AccountViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val name: TextView = itemView.name val currencyAmount: TextView = itemView.currencyAmount val primary: TextView = itemView.primary @SuppressLint("SetTextI18n") fun bind(account: Account) { val accountNameWithIcon = account.nameWithIcon name.text = accountNameWithIcon name.setTextColor(Color.parseColor(account.currency.color)) currencyAmount.text = account.balance.formatAmount primary.visibility = if (account.primary) View.VISIBLE else View.GONE itemView.setOnClickListener { TransactionsActivity.start(account.id, accountNameWithIcon, this@AccountsActivity) } } } }
apache-2.0
b6463f6c411540a8ddbdfc26beac081a
36.238938
107
0.704302
5.111786
false
false
false
false
nickthecoder/paratask
paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/parameters/fields/GridGroupField.kt
1
3817
/* ParaTask Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.paratask.parameters.fields import javafx.geometry.HPos import javafx.geometry.VPos import javafx.scene.Node import javafx.scene.layout.ColumnConstraints import javafx.scene.layout.GridPane import javafx.scene.layout.Priority import javafx.scene.layout.RowConstraints import uk.co.nickthecoder.paratask.parameters.GroupParameter import uk.co.nickthecoder.paratask.parameters.LabelPosition import uk.co.nickthecoder.paratask.parameters.ParameterListener class GridGroupField( groupParameter: GroupParameter, val labelPosition: LabelPosition, val columns: Int = groupParameter.children.size, isBoxed: Boolean) : SingleErrorGroupField(groupParameter, isBoxed = isBoxed), FieldParent, ParameterListener { val grid = GridPane() val fieldSet = mutableListOf<ParameterField>() val containers = mutableListOf<Node>() override fun iterator(): Iterator<ParameterField> { return fieldSet.iterator() } override fun createContent(): Node { if (labelPosition == LabelPosition.TOP) { grid.styleClass.add("labels-above-grid-group") } else { grid.styleClass.add("grid-group") } val controlCC = ColumnConstraints() controlCC.hgrow = Priority.ALWAYS val labelCC = ColumnConstraints() val labelsAboveCC = ColumnConstraints() labelsAboveCC.hgrow = Priority.ALWAYS labelsAboveCC.halignment = HPos.CENTER val rowC = RowConstraints() rowC.valignment = VPos.CENTER var column = 0 var row = 0 groupParameter.children.forEach { child -> val field = child.createField() field.fieldParent = this if (labelPosition == LabelPosition.TOP) { field.label.styleClass?.add("small-bottom-pad") if (row != groupParameter.children.size / columns - 1) { field.controlContainer?.styleClass?.add("bottom-pad") } grid.add(field.label, column, row * 2) grid.add(field.controlContainer, column, row * 2 + 1) if (row == 0) { grid.columnConstraints.add(labelsAboveCC) } } else if (labelPosition == LabelPosition.LEFT) { if (row == 0) { grid.columnConstraints.add(labelCC) grid.columnConstraints.add(controlCC) } if (column == 0) { grid.rowConstraints.add(rowC) } grid.add(field.label, column * 2, row) grid.add(field.controlContainer, column * 2 + 1, row) } else { grid.add(field.controlContainer, column, row) } fieldSet.add(field) column++ if (column >= columns) { column = 0 row++ } } return grid } override fun updateField(field: ParameterField) { // Do nothing. When fields become visible/hidden, the layout doesn't change. } }
gpl-3.0
e0e5603e37b0225379931e6d8d3e79fd
30.545455
96
0.62929
4.58774
false
false
false
false
LachlanMcKee/gsonpath
compiler/standard/src/main/java/gsonpath/adapter/enums/EnumGsonAdapterGenerator.kt
1
4977
package gsonpath.adapter.enums import com.google.gson.Gson import com.squareup.javapoet.ClassName import com.squareup.javapoet.MethodSpec import com.squareup.javapoet.ParameterizedTypeName import gsonpath.LazyFactoryMetadata import gsonpath.ProcessingException import gsonpath.adapter.AdapterGenerationResult import gsonpath.adapter.AdapterMethodBuilder import gsonpath.adapter.Constants import gsonpath.adapter.standard.adapter.properties.PropertyFetcher import gsonpath.adapter.util.writeFile import gsonpath.annotation.EnumGsonAdapter import gsonpath.audit.AuditJsonReader import gsonpath.audit.AuditLog import gsonpath.compiler.generateClassName import gsonpath.internal.GsonPathTypeAdapter import gsonpath.internal.GsonUtil import gsonpath.util.* import javax.lang.model.element.Modifier import javax.lang.model.element.TypeElement class EnumGsonAdapterGenerator( private val fileWriter: FileWriter, private val enumAdapterPropertiesFactory: EnumAdapterPropertiesFactory ) { @Throws(ProcessingException::class) fun handle( enumElement: TypeElement, autoGsonAnnotation: EnumGsonAdapter, lazyFactoryMetadata: LazyFactoryMetadata): AdapterGenerationResult { val propertyFetcher = PropertyFetcher(enumElement) val fieldNamingPolicy = propertyFetcher.getProperty("fieldNamingPolicy", autoGsonAnnotation.fieldNamingPolicy, lazyFactoryMetadata.annotation.fieldNamingPolicy) val properties = enumAdapterPropertiesFactory.create( autoGsonAnnotation.ignoreDefaultValue, enumElement, fieldNamingPolicy) val typeName = properties.enumTypeName val adapterClassName = ClassName.get(typeName.packageName(), generateClassName(typeName, "GsonTypeAdapter")) createEnumAdapterSpec(adapterClassName, properties) .writeFile(fileWriter, adapterClassName.packageName()) { it.addStaticImport(GsonUtil::class.java, "*") } return AdapterGenerationResult(arrayOf(typeName), adapterClassName) } private fun createEnumAdapterSpec( adapterClassName: ClassName, properties: EnumAdapterProperties) = TypeSpecExt.finalClassBuilder(adapterClassName).apply { superclass(ParameterizedTypeName.get(ClassName.get(GsonPathTypeAdapter::class.java), properties.enumTypeName)) addAnnotation(Constants.GENERATED_ANNOTATION) // Add the constructor which takes a gson instance for future use. constructor { addModifiers(Modifier.PUBLIC) addParameter(Gson::class.java, "gson") code { addStatement("super(gson)") } } addMethod(createReadMethod(properties)) addMethod(createWriteMethod(properties)) } private fun createReadMethod(properties: EnumAdapterProperties): MethodSpec { val enumTypeName = properties.enumTypeName return AdapterMethodBuilder.createReadMethodBuilder(properties.enumTypeName).applyAndBuild { code { createVariable(String::class.java, "enumValue", "in.nextString()") switch("enumValue") { properties.fields.forEach { (enumValueTypeName, label) -> case("\"$label\"", addBreak = false) { `return`("\$T", enumValueTypeName) } } default(addBreak = false) { if (properties.defaultValue != null) { createVariable(AuditLog::class.java, "auditLog", "\$T.getAuditLogFromReader(in)", AuditJsonReader::class.java) `if`("auditLog != null") { addStatement( "auditLog.addUnexpectedEnumValue(new \$T(\"${properties.enumTypeName}\", in.getPath(), enumValue))", AuditLog.UnexpectedEnumValue::class.java) } `return`("\$T", properties.defaultValue.enumValueTypeName) } else { addEscapedStatement("""throw new gsonpath.exception.JsonUnexpectedEnumValueException(enumValue, "$enumTypeName")""") } } } } } } private fun createWriteMethod(properties: EnumAdapterProperties): MethodSpec { return AdapterMethodBuilder.createWriteMethodBuilder(properties.enumTypeName).applyAndBuild { code { switch("value") { properties.fields.forEach { (enumValueTypeName, label) -> case(enumValueTypeName.simpleName()) { addStatement("out.value(\"$label\")") } } } } } } }
mit
75b721a8e263719d8a31fc432953e814
41.913793
144
0.633514
5.72069
false
false
false
false
Ganet/rxaerospike
src/main/kotlin/com/github/ganet/rx/aerospike/AerospikeRxClient.kt
1
19737
/* * Copyright 2016 Jose Ignacio Acin Pozo. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.ganet.rx.aerospike import com.aerospike.client.AerospikeException import com.aerospike.client.BatchRead import com.aerospike.client.Bin import com.aerospike.client.Key import com.aerospike.client.Language import com.aerospike.client.Operation import com.aerospike.client.Record import com.aerospike.client.Value import com.aerospike.client.async.AsyncClient import com.aerospike.client.async.IAsyncClient import com.aerospike.client.listener.BatchListListener import com.aerospike.client.listener.BatchSequenceListener import com.aerospike.client.listener.DeleteListener import com.aerospike.client.listener.ExecuteListener import com.aerospike.client.listener.ExistsArrayListener import com.aerospike.client.listener.ExistsListener import com.aerospike.client.listener.ExistsSequenceListener import com.aerospike.client.listener.RecordArrayListener import com.aerospike.client.listener.RecordListener import com.aerospike.client.listener.RecordSequenceListener import com.aerospike.client.listener.WriteListener import com.aerospike.client.policy.BatchPolicy import com.aerospike.client.policy.Policy import com.aerospike.client.policy.QueryPolicy import com.aerospike.client.policy.ScanPolicy import com.aerospike.client.policy.WritePolicy import com.aerospike.client.query.IndexCollectionType import com.aerospike.client.query.IndexType import com.aerospike.client.query.Statement import com.github.ganet.rx.aerospike.data.AerospikeArrayResult import com.github.ganet.rx.aerospike.data.AerospikeResult import io.reactivex.BackpressureStrategy import io.reactivex.BackpressureStrategy.MISSING import io.reactivex.Completable import io.reactivex.Flowable import io.reactivex.Single /** * Created by JoseIgnacio on 09/11/2016. */ class AerospikeRxClient(val client: AsyncClient) : IAsyncClient by client { /* AsyncClient Async Operations */ fun rxAsyncPut(policy: WritePolicy?, key: Key, vararg bins: Bin): Single<Key> { return Single.create { client.put(policy, object : WriteListener { override fun onFailure(exception: AerospikeException?) { it.onError(exception) } override fun onSuccess(key: Key?) { it.onSuccess(key) } }, key, *bins) } } fun rxAsyncAppend(policy: WritePolicy?, key: Key, vararg bins: Bin): Single<Key> { return Single.create { client.append(policy, object : WriteListener { override fun onFailure(exception: AerospikeException?) { it.onError(exception) } override fun onSuccess(key: Key?) { it.onSuccess(key) } }, key, *bins) } } fun rxAsyncPrepend(policy: WritePolicy?, key: Key, vararg bins: Bin): Single<Key> { return Single.create { client.prepend(policy, object : WriteListener { override fun onFailure(exception: AerospikeException?) { it.onError(exception) } override fun onSuccess(key: Key?) { it.onSuccess(key) } }, key, *bins) } } fun rxAsyncAdd(policy: WritePolicy?, key: Key, vararg bins: Bin): Single<Key> { return Single.create { client.add(policy, object : WriteListener { override fun onFailure(exception: AerospikeException?) { it.onError(exception) } override fun onSuccess(key: Key?) { it.onSuccess(key) } }, key, *bins) } } fun rxAsyncDelete(policy: WritePolicy?, key: Key): Single<AerospikeResult<Boolean>> { return Single.create { client.delete(policy, object : DeleteListener { override fun onSuccess(key: Key, success: Boolean) { // Nice wordplay :) it.onSuccess(AerospikeResult(key, success)) } override fun onFailure(exception: AerospikeException?) { it.onError(exception) } }, key) } } fun rxAsyncTouch(policy: WritePolicy?, key: Key): Single<Key> { return Single.create { client.touch(policy, object : WriteListener { override fun onFailure(exception: AerospikeException?) { it.onError(exception) } override fun onSuccess(key: Key?) { it.onSuccess(key) } }, key) } } fun rxAsyncExists(policy: Policy?, key: Key): Single<AerospikeResult<Boolean>> { return Single.create { client.exists(policy, object : ExistsListener { override fun onSuccess(key: Key, success: Boolean) { // Nice wordplay :)! it.onSuccess(AerospikeResult(key, success)) } override fun onFailure(exception: AerospikeException?) { it.onError(exception) } }, key) } } fun rxAsyncExists(policy: BatchPolicy?, keys: Array<Key>): Single<AerospikeArrayResult<BooleanArray>> { return Single.create { client.exists(policy, object : ExistsArrayListener { override fun onSuccess(keyArray: Array<Key>, booleanArray: BooleanArray) { it.onSuccess(AerospikeArrayResult(keyArray, booleanArray)) } override fun onFailure(exception: AerospikeException?) { it.onError(exception) } }, keys) } } @JvmOverloads fun rxAsyncExistsSequence(policy: BatchPolicy?, keys: Array<Key>, backPressure: BackpressureStrategy = MISSING): Flowable<AerospikeResult<Boolean>> { return Flowable.create({ client.exists(policy, object : ExistsSequenceListener { override fun onSuccess() { it.onComplete() } override fun onExists(key: Key, exist: Boolean) { it.onNext(AerospikeResult(key, exist)) } override fun onFailure(exception: AerospikeException?) { it.onError(exception) } }, keys) }, backPressure) } fun rxAsyncGet(policy: Policy?, key: Key): Single<AerospikeResult<Record?>> { return Single.create { client.get(policy, object : RecordListener { override fun onSuccess(key: Key, record: Record?) { it.onSuccess(AerospikeResult(key, record)) } override fun onFailure(exception: AerospikeException?) { it.onError(exception) } }, key) } } fun rxAsyncGet(policy: Policy?, key: Key, vararg binNames: String): Single<AerospikeResult<Record?>> { return Single.create { client.get(policy, object : RecordListener { override fun onSuccess(key: Key, record: Record?) { it.onSuccess(AerospikeResult(key, record)) } override fun onFailure(exception: AerospikeException?) { it.onError(exception) } }, key, *binNames) } } fun rxAsyncGetHeader(policy: Policy?, key: Key): Single<AerospikeResult<Record?>> { return Single.create { client.getHeader(policy, object : RecordListener { override fun onSuccess(key: Key, record: Record?) { it.onSuccess(AerospikeResult(key,record)) } override fun onFailure(exception: AerospikeException?) { it.onError(exception) } }, key) } } fun rxAsyncGet(policy: BatchPolicy?, records: List<BatchRead>): Single<List<BatchRead>> { return Single.create { client.get(policy, object : BatchListListener { override fun onSuccess(list: MutableList<BatchRead>?) { it.onSuccess(list) } override fun onFailure(exception: AerospikeException?) { it.onError(exception) } }, records) } } @JvmOverloads fun rxAsyncGetSequence(policy: BatchPolicy?, records: List<BatchRead>, backPressure: BackpressureStrategy = MISSING): Flowable<BatchRead> { return Flowable.create({ client.get(policy, object : BatchSequenceListener { override fun onRecord(read: BatchRead?) { it.onNext(read) } override fun onSuccess() { it.onComplete() } override fun onFailure(exception: AerospikeException?) { it.onError(exception) } }, records) }, backPressure) } fun rxAsyncGet(policy: BatchPolicy?, keys: Array<Key>): Single<AerospikeArrayResult<Array<Record?>>> { return Single.create { client.get(policy, object : RecordArrayListener { override fun onSuccess(keyArray: Array<Key>, records: Array<Record?>) { it.onSuccess(AerospikeArrayResult(keyArray, records)) } override fun onFailure(exception: AerospikeException?) { it.onError(exception) } }, keys) } } @JvmOverloads fun rxAsyncGetSequence(policy: BatchPolicy?, keys: Array<Key>, backPressure: BackpressureStrategy = MISSING): Flowable<AerospikeResult<Record?>> { return Flowable.create({ client.get(policy, object : RecordSequenceListener { override fun onRecord(key: Key, record: Record?) { it.onNext(AerospikeResult(key, record)) } override fun onSuccess() { it.onComplete() } override fun onFailure(exception: AerospikeException?) { it.onError(exception) } }, keys) }, backPressure) } fun rxAsyncGet(policy: BatchPolicy?, keys: Array<Key>, vararg binNames: String): Single<AerospikeArrayResult<Array<Record?>>> { return Single.create { client.get(policy, object : RecordArrayListener { override fun onSuccess(keyArray: Array<Key>, records: Array<Record?>) { it.onSuccess(AerospikeArrayResult(keyArray, records)) } override fun onFailure(exception: AerospikeException?) { it.onError(exception) } }, keys, *binNames) } } @JvmOverloads fun rxAsyncGetSequence(policy: BatchPolicy?, keys: Array<Key>, vararg binNames: String, backPressure: BackpressureStrategy = MISSING): Flowable<AerospikeResult<Record?>> { return Flowable.create({ client.get(policy, object : RecordSequenceListener { override fun onRecord(key: Key, record: Record?) { it.onNext(AerospikeResult(key, record)) } override fun onSuccess() { it.onComplete() } override fun onFailure(exception: AerospikeException?) { it.onError(exception) } }, keys, *binNames) }, backPressure) } fun rxAsyncGetHeader(policy: BatchPolicy?, keys: Array<Key>): Single<AerospikeArrayResult<Array<Record?>>> { return Single.create { client.getHeader(policy, object : RecordArrayListener { override fun onSuccess(keyArray: Array<Key>, records: Array<Record?>) { it.onSuccess(AerospikeArrayResult(keyArray, records)) } override fun onFailure(exception: AerospikeException?) { it.onError(exception) } }, keys) } } @JvmOverloads fun rxAsyncGetHeaderSequence(policy: BatchPolicy?, keys: Array<Key>, backPressure: BackpressureStrategy = MISSING): Flowable<AerospikeResult<Record?>> { return Flowable.create({ client.getHeader(policy, object : RecordSequenceListener { override fun onRecord(key: Key, record: Record?) { it.onNext(AerospikeResult(key, record)) } override fun onSuccess() { it.onComplete() } override fun onFailure(exception: AerospikeException?) { it.onError(exception) } }, keys) }, backPressure) } fun rxAsyncOperate(policy: WritePolicy?, key: Key, vararg operations: Operation): Single<AerospikeResult<Record?>> { return Single.create { client.operate(policy, object : RecordListener { override fun onSuccess(key: Key, record: Record?) { it.onSuccess(AerospikeResult(key, record)) } override fun onFailure(exception: AerospikeException?) { it.onError(exception) } }, key, *operations) } } @JvmOverloads fun rxAsyncScanAll(policy: ScanPolicy?, namespace: String, setName: String, vararg binNames: String, backPressure: BackpressureStrategy = MISSING): Flowable<AerospikeResult<Record?>> { return Flowable.create({ client.scanAll(policy, object : RecordSequenceListener { override fun onRecord(key: Key, record: Record?) { it.onNext(AerospikeResult(key, record)) } override fun onSuccess() { it.onComplete() } override fun onFailure(exception: AerospikeException?) { it.onError(exception) } }, namespace, setName, *binNames) }, backPressure) } fun rxAsyncExecute(policy: WritePolicy?, key: Key, packageName: String, functionName: String, vararg functionArgs: Value): Single<AerospikeResult<Any?>> { return Single.create { client.execute(policy, object : ExecuteListener { override fun onSuccess(key: Key, obj: Any?) { it.onSuccess(AerospikeResult(key, obj)) } override fun onFailure(exception: AerospikeException?) { it.onError(exception) } }, key, packageName, functionName, *functionArgs) } } @JvmOverloads fun rxAsyncQuery(policy: QueryPolicy?, statement: Statement, backPressure: BackpressureStrategy = MISSING): Flowable<AerospikeResult<Record?>> { return Flowable.create({ client.query(policy, object : RecordSequenceListener { override fun onRecord(key: Key, record: Record?) { it.onNext(AerospikeResult(key, record)) } override fun onSuccess() { it.onComplete() } override fun onFailure(exception: AerospikeException?) { it.onError(exception) } }, statement) }, backPressure) } /* End of Async Operations */ /* Register/Create/Execute operations. This operations need to be polled, so ideally you should observe on background threads. */ @JvmOverloads fun rxRegister(policy: Policy?, clientPath: String, serverPath: String, language: Language, sleepInterval: Int = 1000): Completable { return Completable.create { try { client.register(policy, clientPath, serverPath, language).waitTillComplete(sleepInterval) it.onComplete() } catch(e: RuntimeException) { it.onError(e) } } } @JvmOverloads fun rxRegister(policy: Policy?, resourceLoader: ClassLoader, resourcePath: String, serverPath: String, language: Language, sleepInterval: Int = 1000): Completable { return Completable.create { try { client.register(policy, resourceLoader, resourcePath, serverPath, language).waitTillComplete(sleepInterval) it.onComplete() } catch(e: RuntimeException) { it.onError(e) } } } @JvmOverloads fun rxRegisterUdfString(policy: Policy?, code: String, serverPath: String, language: Language, sleepInterval: Int = 1000): Completable { return Completable.create { try { client.registerUdfString(policy, code, serverPath, language).waitTillComplete(sleepInterval) it.onComplete() } catch(e: RuntimeException) { it.onError(e) } } } @JvmOverloads fun rxExecute( policy: WritePolicy?, statement: Statement, packageName: String, functionName: String, sleepInterval: Int = 1000, vararg functionArgs: Value): Completable { return Completable.create { try { client.execute(policy, statement, packageName, functionName, *functionArgs).waitTillComplete(sleepInterval) it.onComplete() } catch(e: RuntimeException) { it.onError(e) } } } @JvmOverloads fun rxCreateIndex( policy: Policy?, namespace: String, setName: String?, indexName: String, binName: String, indexType: IndexType, sleepInterval: Int = 1000): Completable { return Completable.create { try { client.createIndex(policy, namespace, setName, indexName, binName, indexType).waitTillComplete(sleepInterval) it.onComplete() } catch(e: RuntimeException) { it.onError(e) } } } @JvmOverloads fun rxCreateIndex( policy: Policy?, namespace: String, setName: String?, indexName: String, binName: String, indexType: IndexType, indexCollectionType: IndexCollectionType, sleepInterval: Int = 1000): Completable { return Completable.create { try { client.createIndex(policy, namespace, setName, indexName, binName, indexType, indexCollectionType).waitTillComplete(sleepInterval) it.onComplete() } catch(e: RuntimeException) { it.onError(e) } } } /* End of Register/Create/Execute operations */ }
apache-2.0
bae97fdadb2bcc19164b8c0244f73741
35.415129
188
0.57795
4.692582
false
false
false
false
SrirangaDigital/shankara-android
app/src/main/java/co/ideaportal/srirangadigital/shankaraandroid/home/BookNavFragment.kt
1
6637
package co.ideaportal.srirangadigital.shankaraandroid.home import android.content.Intent import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearSnapHelper import androidx.recyclerview.widget.RecyclerView import co.ideaportal.srirangadigital.shankaraandroid.Constants.PARENT import co.ideaportal.srirangadigital.shankaraandroid.R import co.ideaportal.srirangadigital.shankaraandroid.books.BookActivity import co.ideaportal.srirangadigital.shankaraandroid.db.Datasource import co.ideaportal.srirangadigital.shankaraandroid.db.OpenHelperManager import co.ideaportal.srirangadigital.shankaraandroid.event.BookLinkClicked import co.ideaportal.srirangadigital.shankaraandroid.home.bindings.BookRvAdapter import co.ideaportal.srirangadigital.shankaraandroid.home.bindings.RecentBookAdapter import co.ideaportal.srirangadigital.shankaraandroid.home.db.TableControllerRecentBooks import co.ideaportal.srirangadigital.shankaraandroid.home.rowdata.RecentBookObject import co.ideaportal.srirangadigital.shankaraandroid.model.Level import co.ideaportal.srirangadigital.shankaraandroid.model.Link import co.ideaportal.srirangadigital.shankaraandroid.util.AdapterClickListener import co.ideaportal.srirangadigital.shankaraandroid.util.EqualSpacingItemDecoration import co.ideaportal.srirangadigital.shankaraandroid.util.GridSpacingItemDecoration import co.ideaportal.srirangadigital.shankaraandroid.util.ItemOffsetDecoration import de.greenrobot.event.EventBus import kotlinx.android.synthetic.main.fragment_book_navigation.* import java.util.* /** * A simple [Fragment] subclass. * */ class BookNavFragment : Fragment(), AdapterClickListener, RecentBookClickInterface { companion object { val BOOK_ACTIVITY_CODE = 1000 } private lateinit var dataSource: Datasource private lateinit var bookLinks : ArrayList<Link> private var parentId: Int = 0 private lateinit var recentBookAdapter: RecentBookAdapter override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_book_navigation, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initViews() } private fun initViews() { dataSource = OpenHelperManager.getDataSource(activity) getBookLinks() initRecentBooksRecyclerView() initAllBooksRecyclerView() } private fun initRecentBooksRecyclerView() { recentBookAdapter = RecentBookAdapter(activity!!, MainActivity.recentBookLinks, this@BookNavFragment) val recentBookLinearLayoutManager = LinearLayoutManager(activity!!, RecyclerView.HORIZONTAL, false) val itemOffsetDecoration = EqualSpacingItemDecoration(56,EqualSpacingItemDecoration.HORIZONTAL) rvRecentBooks.addItemDecoration(itemOffsetDecoration) rvRecentBooks.layoutManager = recentBookLinearLayoutManager rvRecentBooks.adapter = recentBookAdapter val snapHelper = LinearSnapHelper() snapHelper.attachToRecyclerView(rvRecentBooks) } override fun onResume() { if (MainActivity.mutableList.size > 0) { tvRecentBooks.visibility = View.VISIBLE rvRecentBooks.visibility = View.VISIBLE } else { tvRecentBooks.visibility = View.GONE rvRecentBooks.visibility = View.GONE } recentBookAdapter = activity?.let { RecentBookAdapter(it, MainActivity.recentBookLinks, this) }!! rvRecentBooks.swapAdapter(recentBookAdapter, true) super.onResume() } private fun initAllBooksRecyclerView() { //Entire list of books recycler view val bookRvAdapter = BookRvAdapter(activity!!, bookLinks, this@BookNavFragment) val bookRvLinearLayoutManager = GridLayoutManager(activity, 3) rvBooks.layoutManager = bookRvLinearLayoutManager val gridSpacingItemDecoration = GridSpacingItemDecoration(3, 16,false) rvBooks.addItemDecoration(gridSpacingItemDecoration) rvBooks.adapter = bookRvAdapter } private fun getBookLinks(): List<Link> { bookLinks = ArrayList() // bookLinks.add(Link(-1, context?.resources?.getString(R.string.upanishat_display), null, Level.BOOK_TYPE, null, 0, null, 0, 0, null, null, false, 0)) val count = dataSource.getNavigableChildrenCount(parentId) for (i in 0 until count) { val childLink = dataSource.getNavigableChildAt(parentId, i) bookLinks.add(childLink) } bookLinks.reverse() return bookLinks } override fun onClick(pos: Int) { val link = bookLinks.get(pos) if (link.level == Level.BOOK_TYPE) return val intent = Intent(activity, BookActivity::class.java) intent.putExtra(PARENT, link) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) startActivityForResult(intent, BOOK_ACTIVITY_CODE) EventBus.getDefault().post(BookLinkClicked(link)) storeRecentBook(link) } private fun storeRecentBook(link: Link) { val recentBookObject = RecentBookObject() recentBookObject.id = link.id recentBookObject.bookName = link.name for (recentBook in MainActivity.recentBookLinks) { if (link.id == recentBook.id) { TableControllerRecentBooks(activity).delete(link.id) } } val createSuccessful = TableControllerRecentBooks(activity).create(recentBookObject) if (createSuccessful) Log.d("RecentBooks", "Details saved successfully") else Log.d("RecentBooks", "Unable to save") } override fun onClick(pos: Int, view: View) { } override fun onRecentBookClick(pos: Int) { val link = MainActivity.recentBookLinks.get(pos) if (link.level == Level.BOOK_TYPE) return val intent = Intent(activity, BookActivity::class.java) intent.putExtra(PARENT, link) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) startActivityForResult(intent, BOOK_ACTIVITY_CODE) EventBus.getDefault().post(BookLinkClicked(link)) link.let { storeRecentBook(it) } } }
gpl-2.0
3b976f78e43023dfed6fa748d8e1629c
36.925714
158
0.734669
4.761119
false
false
false
false
goodwinnk/intellij-community
platform/platform-impl/src/com/intellij/internal/statistic/collectors/fus/ui/FontSizeInfoUsageCollector.kt
1
2584
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.statistic.collectors.fus.ui import com.intellij.ide.ui.UISettings import com.intellij.ide.util.PropertiesComponent import com.intellij.internal.statistic.CollectUsagesException import com.intellij.internal.statistic.beans.UsageDescriptor import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector import com.intellij.internal.statistic.service.fus.collectors.FUSUsageContext import com.intellij.internal.statistic.service.fus.collectors.UsageDescriptorKeyValidator.ensureProperKey import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.colors.impl.AppEditorFontOptions /** * @author Konstantin Bulenkov */ class FontSizeInfoUsageCollector : ApplicationUsagesCollector() { @Throws(CollectUsagesException::class) override fun getUsages(): Set<UsageDescriptor> { val scheme = EditorColorsManager.getInstance().globalScheme val ui = UISettings.shadowInstance var usages = setOf( UsageDescriptor("UI.font.size[${ui.fontSize}]"), UsageDescriptor(ensureProperKey("UI.font.name[${ui.fontFace}]")), UsageDescriptor("Presentation.mode.font.size[${ui.presentationModeFontSize}]") ) if (!scheme.isUseAppFontPreferencesInEditor) { usages += setOf( UsageDescriptor("Editor.font.size[${scheme.editorFontSize}]"), UsageDescriptor(ensureProperKey("Editor.font.name[${scheme.editorFontName}]")) ) } else { val appPrefs = AppEditorFontOptions.getInstance().fontPreferences usages += setOf( UsageDescriptor("IDE.editor.font.size[${appPrefs.getSize(appPrefs.fontFamily)}]"), UsageDescriptor(ensureProperKey("IDE.editor.font.name[${appPrefs.fontFamily}]")) ) } if (!scheme.isUseEditorFontPreferencesInConsole) { usages += setOf( UsageDescriptor("Console.font.size[${scheme.consoleFontSize}]"), UsageDescriptor(ensureProperKey("Console.font.name[${scheme.consoleFontName}]")) ) } val quickDocFontSize = PropertiesComponent.getInstance().getValue("quick.doc.font.size") if (quickDocFontSize != null) { usages += setOf( UsageDescriptor("QuickDoc.font.size[" + quickDocFontSize +"]") ) } return usages } override fun getGroupId(): String { return "statistics.ui.fonts" } override fun getContext(): FUSUsageContext? { return FUSUsageContext.OS_CONTEXT } }
apache-2.0
32611ffc58625d6b35693fe7ea773b89
40.677419
140
0.741486
4.639138
false
false
false
false
yukuku/androidbible
Alkitab/src/main/java/yuku/alkitab/base/verses/VersesDataModel.kt
1
7862
package yuku.alkitab.base.verses import yuku.alkitab.base.util.AppLog import yuku.alkitab.model.PericopeBlock import yuku.alkitab.model.SingleChapterVerses import yuku.alkitab.model.Version import yuku.alkitab.util.Ari private const val TAG = "VersesDataModel" @JvmInline value class LocateResult constructor(private val raw: Long) { constructor(verse_1: Int, distanceToNextVerse: Int) : this( verse_1.toLong() or (distanceToNextVerse.toLong() shl 32) ) val verse_1 get() = raw.toInt() val distanceToNextVerse get() = (raw shr 32).toInt() companion object { val EMPTY = LocateResult(0L) } } data class VersesDataModel( @JvmField val ari_bc_: Int, @JvmField val verses_: SingleChapterVerses, @JvmField val pericopeBlockCount_: Int = 0, @JvmField val pericopeAris_: List<Int> = emptyList(), @JvmField val pericopeBlocks_: List<PericopeBlock> = emptyList(), @JvmField val version_: Version? = null, @JvmField val versionId_: String? = null, @JvmField val versesAttributes: VersesAttributes = VersesAttributes.createEmpty(verses_.verseCount) ) { enum class ItemType { verseText, pericope, } /** * For each element, if 0 or more, it refers to the 0-based verse number. * If negative, -1 is the index 0 of pericope, -2 (a) is index 1 (b) of pericope, etc. * * Convert a to b: b = -a-1; * Convert b to a: a = -b-1; */ private val itemPointer_: IntArray by lazy { val nverse = verses_.verseCount val res = IntArray(nverse + pericopeBlockCount_) var pos_block = 0 var pos_verse = 0 var pos_itemPointer = 0 while (true) { // check if we still have pericopes remaining if (pos_block < pericopeBlockCount_) { // still possible if (Ari.toVerse(pericopeAris_[pos_block]) - 1 == pos_verse) { // We have a pericope. res[pos_itemPointer++] = -pos_block - 1 pos_block++ continue } } // check if there is no verses remaining if (pos_verse >= nverse) { break } // there is no more pericopes, OR not the time yet for pericopes. So we insert a verse. res[pos_itemPointer++] = pos_verse pos_verse++ } if (res.size != pos_itemPointer) { throw RuntimeException("Algorithm to insert pericopes error!! pos_itemPointer=$pos_itemPointer pos_verse=$pos_verse pos_block=$pos_block nverse=$nverse pericopeBlockCount_=$pericopeBlockCount_ pericopeAris_:$pericopeAris_ pericopeBlocks_:$pericopeBlocks_") } res } val itemCount get() = itemPointer_.size fun getItemViewType(position: Int): ItemType { val id = itemPointer_[position] return if (id >= 0) { ItemType.verseText } else { ItemType.pericope } } fun getVerse_0(position: Int): Int { val id = itemPointer_[position] return if (id >= 0) { id } else { throw IllegalArgumentException("getVerse_0: position=$position has id of $id") } } fun getPericopeIndex(position: Int): Int { val id = itemPointer_[position] return if (id < 0) { id.inv() } else { throw IllegalArgumentException("getPericopeIndex: position=$position has id of $id") } } /** * For example, when pos=0 is a pericope and pos=1 is the first verse, * this method returns 0. * * @return position on this adapter, or -1 if not found */ fun getPositionOfPericopeBeginningFromVerse(verse_1: Int): Int { val verse_0 = verse_1 - 1 var i = 0 val len = itemPointer_.size while (i < len) { if (itemPointer_[i] == verse_0) { // we've found it, but if we can move back to pericopes, it is better. for (j in i - 1 downTo 0) { if (itemPointer_[j] < 0) { // it's still pericope, so let's continue i = j } else { // no longer a pericope (means, we are on the previous verse) break } } return i } i++ } return -1 } /** * Let's say pos 0 is pericope and pos 1 is verse_1 1; * then this method called with verse_1=1 returns 1. * * @return position or -1 if not found */ fun getPositionIgnoringPericopeFromVerse(verse_1: Int): Int { val verse_0 = verse_1 - 1 var i = 0 val len = itemPointer_.size while (i < len) { if (itemPointer_[i] == verse_0) return i i++ } return -1 } /** * Get the 1-based verse number from the position given. * If the position points to a pericope, the next verse number is returned. * @return verse_1 or 0 if doesn't make sense */ fun getVerse_1FromPosition(position: Int): Int { if (position < 0) return 0 val pos = position.coerceAtMost(itemPointer_.size - 1) var id = itemPointer_[pos] if (id >= 0) { return id + 1 } // it's a pericope. Let's move forward until we get a verse for (i in pos + 1 until itemPointer_.size) { id = itemPointer_[i] if (id >= 0) { return id + 1 } } AppLog.w(TAG, "pericope title at the last position? does not make sense.") return 0 } /** * Get the 1-based verse number and the distance to the verse from the position given. * If the position points to a pericope, the next verse number is returned. * @return [LocateResult.EMPTY] if the position points to a pericope without following verse. */ fun locateVerse_1FromPosition(position: Int): LocateResult { val pos = position.coerceAtMost(itemPointer_.size - 1) var id = itemPointer_[pos] if (id >= 0) { return LocateResult(id + 1, 0) } // it's a pericope. Let's move forward until we get a verse var distance = 0 for (i in pos + 1 until itemPointer_.size) { distance++ id = itemPointer_[i] if (id >= 0) { return LocateResult(id + 1, distance) } } AppLog.w(TAG, "pericope title at the last position? does not make sense.") return LocateResult(0, 0) } /** * Similar to [getVerse_1FromPosition], but returns 0 if the specified position is a pericope or doesn't make sense. */ fun getVerseOrPericopeFromPosition(position: Int): Int { if (position < 0 || position >= itemPointer_.size) { return 0 } val id = itemPointer_[position] return if (id >= 0) { id + 1 } else { 0 } } fun getVerseText(verse_1: Int): String? { return if (verse_1 in 1..verses_.verseCount) { verses_.getVerse(verse_1 - 1) } else { null } } fun isEnabled(position: Int): Boolean { // guard against wild ListView.onInitializeAccessibilityNodeInfoForItem return when { position >= itemPointer_.size -> false itemPointer_[position] >= 0 -> true else -> false } } companion object { @JvmField val EMPTY = VersesDataModel( ari_bc_ = 0, verses_ = SingleChapterVerses.EMPTY ) } }
apache-2.0
b0ebfcbecfd244666bd93ed67309c75f
28.118519
268
0.548079
4.175252
false
false
false
false
soywiz/korge
@old/korge-spriter/src/commonMain/kotlin/com/soywiz/korge/ext/spriter/com/brashmonkey/spriter/Spriter.kt
1
8799
package com.soywiz.korge.ext.spriter.com.brashmonkey.spriter import com.soywiz.kmem.* import com.soywiz.korio.* import com.soywiz.korio.file.* import com.soywiz.korio.file.std.* import com.soywiz.korio.lang.* import com.soywiz.korio.lang.FileNotFoundException import com.soywiz.korio.stream.* import kotlin.reflect.* /** * A utility class for managing multiple [Loader] and [Player] instances. * @author Trixt0r */ object Spriter { private var loaderDependencies = arrayOfNulls<Any>(1) private var drawerDependencies = arrayOfNulls<Any>(1) private var loaderTypes = arrayOfNulls<KClass<*>>(1) private var drawerTypes = arrayOfNulls<KClass<*>>(1) init { loaderTypes[0] = Data::class drawerTypes[0] = Loader::class } private var loaderClass: KClass<out Loader<*>>? = null private val loadedData = HashMap<String, Data>() private val players = ArrayList<Player>() private val loaders = ArrayList<Loader<*>>() private var drawer: Drawer<*>? = null private val entityToLoader = HashMap<Entity, Loader<*>>() private var initialized = false /** * Sets the dependencies for implemented [Loader]. * @param loaderDependencies the dependencies a loader has to get */ fun setLoaderDependencies(vararg loaderDependencies: Any) { if (loaderDependencies == null) return Spriter.loaderDependencies = arrayOfNulls<Any>(loaderDependencies.size + 1) arraycopy( (loaderDependencies as Array<Any>), 0, Spriter.loaderDependencies as Array<Any>, 1, loaderDependencies.size ) loaderTypes = arrayOfNulls<KClass<*>>(loaderDependencies.size + 1) loaderTypes[0] = Data::class for (i in loaderDependencies.indices) loaderTypes[i + 1] = loaderDependencies[i]::class } /** * Sets the dependencies for implemented [Drawer]. * @param drawerDependencies the dependencies a drawer has to get */ fun setDrawerDependencies(vararg drawerDependencies: Any?) { if (drawerDependencies == null) return Spriter.drawerDependencies = arrayOfNulls<Any>(drawerDependencies.size + 1) Spriter.drawerDependencies[0] = null arraycopy( (drawerDependencies as Array<Any>), 0, Spriter.drawerDependencies as Array<Any>, 1, drawerDependencies.size ) drawerTypes = arrayOfNulls<KClass<*>>(drawerDependencies.size + 1) drawerTypes[0] = Loader::class for (i in drawerDependencies.indices) if (drawerDependencies[i] != null) drawerTypes[i + 1] = drawerDependencies[i]!!::class } /** * Initializes this class with the implemented [Loader] class and [Drawer] class. * Before calling this method make sure that you have set all necessary dependecies with [.setDrawerDependencies] and [.setLoaderDependencies]. * A drawer is created with this method. * @param loaderClass the loader class * * * @param drawerClass the drawer class */ fun init(loaderClass: KClass<out Loader<*>>, drawerClass: KClass<out Drawer<*>>) { TODO() //Spriter.loaderClass = loaderClass //try { // drawer = drawerClass.getDeclaredConstructor(*drawerTypes).newInstance(*drawerDependencies) //} catch (e: Exception) { // e.printStackTrace() //} // //initialized = drawer != null } /** * Loads a SCML file with the given path. * @param scmlFile the path to the SCML file */ suspend fun load(scmlFile: String) { load(com.soywiz.korio.file.std.resourcesVfs[scmlFile]) } /** * Loads the given SCML file. * @param scmlFile the scml file */ suspend fun load(scmlFile: VfsFile) { try { load(scmlFile.readAsSyncStream(), scmlFile.path.replace("\\\\".toRegex(), "/")) } catch (e: FileNotFoundException) { e.printStackTrace() } } /** * Loads the given SCML stream pointing to a file saved at the given path. * @param stream the SCML stream * * * @param scmlFile the path to the SCML file */ suspend fun load(stream: SyncStream, scmlFile: String) { TODO() //val reader = SCMLReader(stream) //val data = reader.data //loadedData.put(scmlFile, data) //loaderDependencies[0] = data //try { // val loader = loaderClass!!.getDeclaredConstructor(*loaderTypes).newInstance(*loaderDependencies) // loader.load(LocalVfs(scmlFile)) // loaders.add(loader) // for (entity in data.entities) entityToLoader.put(entity, loader) //} catch (e: Exception) { // e.printStackTrace() //} } /** * Creates a new [Player] instance based on the given SCML file with the given entity index and the given class extending a [Player] * @param scmlFile name of the SCML file * * * @param entityIndex the index of the entity * * * @param playerFactory the class extending a [Player] class, e.g. [PlayerTweener]. * * * @return a [Player] instance managed by this class * * * @throws SpriterException if the given SCML file was not loaded yet */ fun newPlayer(scmlFile: String, entityIndex: Int, playerFactory: (Entity) -> Player = { Player(it) }): Player? { if (!loadedData.containsKey(scmlFile)) throw SpriterException("You have to load \"$scmlFile\" before using it!") try { val player = playerFactory(loadedData[scmlFile]!!.getEntity(entityIndex)) players.add(player) return player } catch (e: Exception) { e.printStackTrace() } return null } /** * Creates a new [Player] instance based on the given SCML file with the given entity name * @param scmlFile name of the SCML file * * * @param entityName name of the entity * * * @return a [Player] instance managed by this class * * * @throws SpriterException if the given SCML file was not loaded yet */ fun newPlayer(scmlFile: String, entityName: String): Player? { if (!loadedData.containsKey(scmlFile)) throw SpriterException("You have to load \"$scmlFile\" before using it!") return newPlayer(scmlFile, loadedData[scmlFile]!!.getEntityIndex(entityName)) } /** * Returns a loader for the given SCML filename. * @param scmlFile the name of the SCML file * * * @return the loader for the given SCML filename * * * @throws NullPointerException if the SCML file was not loaded yet */ fun getLoader(scmlFile: String): Loader<*>? { return entityToLoader[getData(scmlFile).getEntity(0)] } /** * Updates each created player by this class and immediately draws it. * This method should only be called if you want to update and render on the same thread. * @throws SpriterException if [.init] was not called before */ fun updateAndDraw() { if (!initialized) throw SpriterException("Call init() before updating!") for (i in players.indices) { players[i].update() drawer!!.loader = entityToLoader[players[i].getEntity()]!! drawer!!.draw(players[i]) } } /** * Updates each created player by this class. * @throws SpriterException if [.init] was not called before */ fun update() { if (!initialized) throw SpriterException("Call init() before updating!") for (i in players.indices) { players[i].update() } } /** * Draws each created player by this class. * @throws SpriterException if [.init] was not called before */ fun draw() { if (!initialized) throw SpriterException("Call init() before drawing!") for (i in players.indices) { drawer!!.loader = entityToLoader[players[i].getEntity()]!! drawer!!.draw(players[i]) } } /** * Returns the drawer instance this class is using. * @return the drawer which draws all players */ fun drawer(): Drawer<*> { return drawer!! } /** * Returns the data for the given SCML filename. * @param fileName the name of the SCML file * * * @return the data for the given SCML filename or null if not loaed yet */ fun getData(fileName: String): Data { return loadedData[fileName]!! } /** * The number of players this class is managing. * @return number of players */ fun players(): Int { return players.size } /** * Clears all previous created players, Spriter datas, disposes all loaders, deletes the drawer and resets all internal lists. * After this methods was called [.init] has to be called again so that everything works again. */ fun dispose() { drawer = null drawerDependencies = arrayOfNulls<Any>(1) drawerTypes = arrayOfNulls<KClass<*>>(1) drawerTypes[0] = Loader::class entityToLoader.clear() for (i in loaders.indices) { loaders[i].dispose() } loaders.clear() loadedData.clear() loaderClass = null loaderTypes = arrayOfNulls<KClass<*>>(1) loaderTypes[0] = Data::class loaderDependencies = arrayOfNulls<Any>(1) players.clear() initialized = false } } /** * Creates a new [Player] instance based on the given SCML file with the given entity index * @param scmlFile name of the SCML file * * * @param entityIndex the index of the entity * * * @return a [Player] instance managed by this class * * * @throws SpriterException if the given SCML file was not loaded yet */
apache-2.0
02c7a1654ac73e900028112c3336f073
28.726351
144
0.701443
3.620988
false
false
false
false
Yopu/OpenGrave
src/main/kotlin/opengrave/TileEntityGrave.kt
1
4444
package opengrave import net.minecraft.entity.player.EntityPlayer import net.minecraft.inventory.IInventory import net.minecraft.inventory.InventoryBasic import net.minecraft.inventory.InventoryHelper import net.minecraft.item.ItemStack import net.minecraft.nbt.NBTTagCompound import net.minecraft.tileentity.TileEntity import net.minecraft.util.text.ITextComponent import java.util.* class TileEntityGrave : TileEntity() { companion object { const val ID = "opengrave.tileentitygrave" const val INVENTORY_NBT_KEY = "inventory" const val DEATH_MESSAGE_NBT_KEY = "death_message" const val ENTITY_PLAYER_ID_NBT_KEY = "entity_player_id" const val BAUBLES_NBT_KEY = "baubles" } var entityPlayerID: UUID? = null var inventory: Array<ItemStack?> = emptyArray() var baubles: Array<ItemStack?> = emptyArray() var deathMessage: ITextComponent? = null private val inventoryWrapper: IInventory get() = InventoryBasic("throwaway", false, inventory.size + baubles.size).apply { (inventory + baubles).forEachIndexed { i, stack -> if (stack == null) { setInventorySlotContents(i, ItemStack.EMPTY) } else { setInventorySlotContents(i, stack) } } } fun takeDrops(entityPlayerID: UUID, items: Array<ItemStack?>, baubles: Array<ItemStack?>, deathMessage: ITextComponent?) { this.entityPlayerID = entityPlayerID this.inventory = items this.baubles = baubles this.deathMessage = deathMessage } fun dropItems() = InventoryHelper.dropInventoryItems(world, pos, inventoryWrapper) fun returnPlayerItems(player: EntityPlayer) { if (player.persistentID != entityPlayerID) return player.inventory.dispenseItems(inventory) inventory = emptyArray() val baublesInventory = player.safeGetBaubles() if (baublesInventory != null) { baublesInventory.dispenseItems(baubles) baubles = emptyArray() } } private fun IInventory.dispenseItems(items: Array<ItemStack?>) { for ((index, itemStack) in items.withIndex()) { if (itemStack == null) continue var dispensed = false var possibleIndex = index while (possibleIndex < sizeInventory) { if (getStackInSlot(possibleIndex).isEmpty && isItemValidForSlot(possibleIndex, itemStack)) { setInventorySlotContents(possibleIndex, itemStack) dispensed = true break } else { possibleIndex++ } } if (!dispensed) itemStack.dropInWorld(world, pos) } } override fun readFromNBT(compound: NBTTagCompound) { super.readFromNBT(compound) val rootTagCompound = compound.getCompoundTag(ID) val entityPlayerIDString = rootTagCompound.getString(ENTITY_PLAYER_ID_NBT_KEY) if (!entityPlayerIDString.isNullOrBlank()) { entityPlayerID = try { UUID.fromString(entityPlayerIDString) } catch (e: IllegalArgumentException) { null } } inventory = rootTagCompound.getItemStackArray(INVENTORY_NBT_KEY) baubles = rootTagCompound.getItemStackArray(BAUBLES_NBT_KEY) val json = rootTagCompound.getString(DEATH_MESSAGE_NBT_KEY) if (json.isNotBlank()) { deathMessage = ITextComponent.Serializer.jsonToComponent(json) } } override fun writeToNBT(compound: NBTTagCompound): NBTTagCompound { super.writeToNBT(compound) val rootTagCompound = NBTTagCompound() val entityPlayerIDString = entityPlayerID?.toString() ?: "" rootTagCompound.setString(ENTITY_PLAYER_ID_NBT_KEY, entityPlayerIDString) rootTagCompound.setTag(INVENTORY_NBT_KEY, inventory.toNBTTag()) rootTagCompound.setTag(BAUBLES_NBT_KEY, baubles.toNBTTag()) deathMessage?.let { val deathMessageJson = ITextComponent.Serializer.componentToJson(it) rootTagCompound.setString(DEATH_MESSAGE_NBT_KEY, deathMessageJson) } compound.setTag(ID, rootTagCompound) return compound } override fun toString() = "TileEntityGrave@$pos" }
mit
d8e68cb641c04aa9d39a20c6bed96d6c
33.71875
126
0.639964
4.658281
false
false
false
false
vondear/RxTools
RxUI/src/main/java/com/tamsiree/rxui/view/loadingview/style/ThreeBounce.kt
1
1746
package com.tamsiree.rxui.view.loadingview.style import android.animation.ValueAnimator import android.graphics.Rect import com.tamsiree.rxui.view.loadingview.animation.SpriteAnimatorBuilder import com.tamsiree.rxui.view.loadingview.sprite.CircleSprite import com.tamsiree.rxui.view.loadingview.sprite.Sprite import com.tamsiree.rxui.view.loadingview.sprite.SpriteContainer /** * @author tamsiree */ class ThreeBounce : SpriteContainer() { override fun onCreateChild(): Array<Sprite?>? { return arrayOf( Bounce(), Bounce(), Bounce() ) } override fun onChildCreated(vararg sprites: Sprite?) { super.onChildCreated(*sprites) sprites[1]?.setAnimationDelay(160) sprites[2]?.setAnimationDelay(320) } override fun onBoundsChange(bounds: Rect) { var bounds = bounds super.onBoundsChange(bounds) bounds = clipSquare(bounds) val radius = bounds.width() / 8 val top = bounds.centerY() - radius val bottom = bounds.centerY() + radius for (i in 0 until childCount) { val left = (bounds.width() * i / 3 + bounds.left) getChildAt(i)!!.setDrawBounds0( left, top, left + radius * 2, bottom ) } } private inner class Bounce internal constructor() : CircleSprite() { override fun onCreateAnimation(): ValueAnimator? { val fractions = floatArrayOf(0f, 0.4f, 0.8f, 1f) return SpriteAnimatorBuilder(this).scale(fractions, 0f, 1f, 0f, 0f).duration(1400).easeInOut(*fractions) .build() } init { setScale(0f) } } }
apache-2.0
3b453a40cb57a3496593036b99cde0df
30.763636
116
0.611111
4.37594
false
false
false
false
GoogleChromeLabs/android-web-payment
SamplePay/app/src/main/java/com/example/android/samplepay/model/AddressErrors.kt
1
2802
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.samplepay.model import android.os.Bundle data class AddressErrors( val addressLines: String?, val countryCode: String?, val city: String?, val dependentLocality: String?, val organization: String?, val phone: String?, val postalCode: String?, val recipient: String?, val region: String?, val sortingCode: String? ) { companion object { fun from(extras: Bundle): AddressErrors { return AddressErrors( addressLines = extras.getString("addressLines"), countryCode = extras.getString("countryCode"), city = extras.getString("city"), dependentLocality = extras.getString("dependentLocality"), organization = extras.getString("organization"), phone = extras.getString("phone"), postalCode = extras.getString("postalCode"), recipient = extras.getString("recipient"), region = extras.getString("region"), sortingCode = extras.getString("sortingCode") ) } } override fun toString(): String { return buildString { if (!addressLines.isNullOrEmpty()) { appendLine(addressLines) } if (!countryCode.isNullOrEmpty()) { appendLine(countryCode) } if (!city.isNullOrEmpty()) { appendLine(city) } if (!dependentLocality.isNullOrEmpty()) { appendLine(dependentLocality) } if (!organization.isNullOrEmpty()) { appendLine(organization) } if (!phone.isNullOrEmpty()) { appendLine(phone) } if (!postalCode.isNullOrEmpty()) { appendLine(postalCode) } if (!recipient.isNullOrEmpty()) { appendLine(recipient) } if (!region.isNullOrEmpty()) { appendLine(region) } if (!sortingCode.isNullOrEmpty()) { appendLine(sortingCode) } } } }
apache-2.0
aaec614c3717b068537898a644a81755
32.357143
75
0.571734
5.296786
false
false
false
false
mihmuh/IntelliJConsole
Konsole/src/com/intellij/idekonsole/results/KResults.kt
1
12086
package com.intellij.idekonsole.results import com.intellij.idekonsole.context.Context import com.intellij.idekonsole.context.runRead import com.intellij.idekonsole.scripting.ConsoleOutput import com.intellij.idekonsole.scripting.Refactoring import com.intellij.idekonsole.scripting.collections.SequenceLike import com.intellij.idekonsole.scripting.collections.asSequenceLike import com.intellij.idekonsole.scripting.collections.impl.wrapWithRead import com.intellij.idekonsole.scripting.collections.map import com.intellij.idekonsole.scripting.collections.toList import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElement import com.intellij.ui.JBColor import com.intellij.ui.components.JBLabel import com.intellij.usageView.UsageInfo import com.intellij.usages.Usage import com.intellij.usages.UsageInfo2UsageAdapter import com.intellij.usages.impl.UsageAdapter import com.intellij.util.ui.JBUI import java.awt.Color import java.awt.Font import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import java.io.PrintWriter import java.io.StringWriter import java.util.* import javax.swing.JComponent private val LOG = Logger.getInstance(KResult::class.java) private fun createLabel(text: String): JBLabel { val content = StringUtil.escapeXml(text).replace("\n", "<br>").replace(" ", "&nbsp;") return JBLabel(content).setCopyable(true) } class KCommandResult(text: String) : KResult { val panel: JComponent init { val label = createLabel("> " + if (text.contains('\n')) (text + "\n") else text) panel = JBUI.Panels.simplePanel(label) panel.background = null } override fun getPresentation(): JComponent = panel } class KStdoutResult(text: String) : KResult { val panel: JComponent init { val label = createLabel(text) label.foreground = JBColor.RED panel = label } override fun getPresentation(): JComponent = panel } class KHelpResult(text: String) : KResult { val panel: JComponent init { val label = createLabel(text) label.foreground = JBColor.GRAY panel = label } override fun getPresentation(): JComponent = panel } class KErrorResult(error: String) : KResult { val panel: JComponent init { LOG.warn(error) val prefix = JBLabel("ERROR: ") val label = createLabel(error) label.foreground = JBColor.RED panel = JBUI.Panels.simplePanel(label).addToLeft(prefix) panel.background = null } override fun getPresentation(): JComponent = panel } class KUsagesResult<T : PsiElement>(val elements: SequenceLike<T>, val searchQuery: String, val project: Project, val output: ConsoleOutput?, val refactoring: ((T) -> Unit)? = null): KResult { val usagesLabel = InteractiveLabel(Context.wrapCallback({ openUsagesView() })) val statusLabel = JBLabel("Searching... ") val panel = JBUI.Panels.simplePanel(usagesLabel.myLabel).addToLeft(statusLabel) val usagesList = ArrayList<T>() var myStopped = false var myFinished = false @Volatile var myUsageViewListener: UsagesViewUsagesListener? = null init { panel.background = null val context = Context.instance() val collectorListener = object: UsagesListener<T> { override fun processFirstUsage(usage: T) { if (myUsageViewListener != null) { myUsageViewListener!!.processFirstUsage(wrapUsage(usage)) } ApplicationManager.getApplication().invokeLater { usagesList.add(usage) usagesLabel.text = "1 element found." } } override fun processOthers(usage: T) { if (myUsageViewListener != null) { var wrappedUsage: Usage? = null runRead(context) { wrappedUsage = wrapUsage(usage) } myUsageViewListener!!.processOthers(wrappedUsage!!) } ApplicationManager.getApplication().invokeLater { if (!myStopped) { usagesList.add(usage) usagesLabel.text = (if (myStopped) "At least " else "") + "${usagesList.size} elements found." } } } override fun finished() { ApplicationManager.getApplication().invokeLater { //todo one node should be shown as a ref myStopped = true statusLabel.text = "Finished. " myFinished = true if (refactoring != null) { usagesLabel.text = "Refactor ${usagesList.size} elements." showFromList() } } } override fun empty() { ApplicationManager.getApplication().invokeLater { myStopped = true usagesLabel.text = "Nothing found." usagesLabel.deactivate() } } override fun askTooManyUsagesContinue(): Boolean { val shouldContinue = myUsageViewListener != null && myUsageViewListener!!.askTooManyUsagesContinue() if (!shouldContinue) { myStopped = true statusLabel.text = "Stopped. " usagesLabel.text = "At least ${usagesList.size} elements found." } return shouldContinue } override fun cancelled() { ApplicationManager.getApplication().invokeLater { myStopped = true statusLabel.text = "Cancelled. " } } } collectorListener.showUsages(project, elements) } private fun refactor(r: (T) -> Unit) { val elementsList = elements.toList() for (it in elementsList) { try { r.invoke(it) } catch (e: Exception) { val failedIndex = elementsList.indexOf(it) usagesLabel.text = usagesLabel.text.replace("" + elementsList.size + " element", "" + failedIndex + " element") + "successfully" val exception = KExceptionResult(project, e) output?.addResultAfter(exception, this) val remaining = usagesResult(elementsList.subList(failedIndex + 1, elementsList.size).asSequence(), searchQuery, project, output, refactoring) remaining.usagesLabel.text = remaining.usagesLabel.text.replace("Refactor", "Refactor remaining") output?.addResultAfter(remaining, exception) break } } usagesLabel.deactivate() usagesLabel.text = usagesLabel.text.replace("Refactor", "Refactored") } private fun openUsagesView() { if (!myStopped && myUsageViewListener == null) { myUsageViewListener = createUsageViewListener() initListenerFromList() } else if (myFinished) { showFromList() } else { createUsageViewListener().showUsages(project, elements.wrapWithRead().map { wrapUsage(it) }) } } fun initListenerFromList() { if (usagesList.isNotEmpty()) { myUsageViewListener!!.processFirstUsage(wrapUsage(usagesList.first())) } usagesList.asSequence().drop(1).forEach { myUsageViewListener!!.processOthers(wrapUsage(it)) } } fun wrapUsage(usage: T): Usage { return if (usage.isValid) UsageInfo2UsageAdapter(UsageInfo(usage)) else UsageAdapter() } private fun showFromList() { myUsageViewListener = createUsageViewListener() initListenerFromList() myUsageViewListener!!.finished() } fun createUsageViewListener(): UsagesViewUsagesListener { return UsagesViewUsagesListener(project, searchQuery, if (refactoring != null) { Runnable { refactor(refactoring) } } else { null }) } override fun getPresentation() = panel } class InteractiveLabel(private val action: () -> Unit) { val myLabel = JBLabel() val mouseListener: MouseAdapter = object : MouseAdapter() { override fun mouseClicked(e: MouseEvent?) = action.invoke() } var text: String get() = myLabel.text.substringAfter("<a>").substringBeforeLast("</a>") set(value) { myLabel.text = "<html><a>$value</a></html>" } init { myLabel.foreground = Color.BLUE myLabel.addMouseListener(mouseListener) } fun deactivate() { myLabel.removeMouseListener(mouseListener) myLabel.foreground = Color.GRAY myLabel.font = Font(myLabel.font.name, Font.ITALIC, myLabel.font.size) } } fun <T : PsiElement> usagesResult(elements: SequenceLike<T>, searchQuery: String, project: Project, output: ConsoleOutput?, refactoring: ((T) -> Unit)? = null): KUsagesResult<T> { return KUsagesResult(elements, searchQuery, project, output, refactoring) } fun <T : PsiElement> usagesResult(refactoring: Refactoring<T>, searchQuery: String, project: Project, output: ConsoleOutput?): KUsagesResult<T> { return usagesResult(refactoring.elements, searchQuery, project, output, refactoring.refactoring) } fun <T : PsiElement> usagesResult(elements: Sequence<T>, searchQuery: String, project: Project, output: ConsoleOutput?, refactoring: ((T) -> Unit)? = null): KUsagesResult<T> { return KUsagesResult(elements.asSequenceLike(), searchQuery, project, output, refactoring) } class KExceptionResult(val project: Project, t: Throwable) : KResult { val panel: JComponent val DARK_BLUE = Color(0, 0, 128) init { val prefix = JBLabel("Exception: ") val classLabel = JBLabel(underlineAndHighlight(shortPackageName(t.javaClass.name), DARK_BLUE, Color.PINK)) val messageLabel = JBLabel(": " + t.message.toString()) messageLabel.background = Color.PINK prefix.background = Color.PINK classLabel.background = Color.PINK val writer: StringWriter = StringWriter() t.printStackTrace(PrintWriter(writer)) classLabel.addMouseListener(object : MouseAdapter() { override fun mouseClicked(e: MouseEvent?) { val dialog: KAnalyzeStacktraceDialog = KAnalyzeStacktraceDialog(project, writer.toString()) dialog.show() } }) panel = JBUI.Panels.simplePanel(messageLabel).addToLeft(JBUI.Panels.simplePanel(classLabel).addToLeft(prefix)) panel.background = null } fun underlineAndHighlight(s: String?, foreground: Color, background: Color): String { if (s == null) { return "" } val htmlForeground = colorToHtml(foreground) val htmlBackground = colorToHtml(background) return "<HTML><U style=\"color:$htmlForeground ;background-color:$htmlBackground\">$s</U></HTML>" } private fun colorToHtml(color: Color): String { val rgb = Integer.toHexString(color.rgb) return rgb.substring(2, rgb.length) } fun shortPackageName(fqName: String?): String? { if (fqName == null) { return fqName } var start = 0 var dotIndex = fqName.indexOf('.', start) val stringBuilder = StringBuilder() while (dotIndex > 0) { stringBuilder.append(fqName[start]) stringBuilder.append('.') start = dotIndex + 1 dotIndex = fqName.indexOf('.', start) } stringBuilder.append(fqName.substring(start, fqName.length)) return stringBuilder.toString() } override fun getPresentation(): JComponent = panel }
gpl-3.0
2ae6bd4c8ae5913d0493b990fbafa455
35.624242
192
0.625434
4.741467
false
false
false
false
TeamWizardry/LibrarianLib
modules/facade/src/main/kotlin/com/teamwizardry/librarianlib/facade/layer/supporting/ContainerSpace.kt
1
1462
package com.teamwizardry.librarianlib.facade.layer.supporting import com.teamwizardry.librarianlib.facade.layer.GuiLayer import com.teamwizardry.librarianlib.math.CoordinateSpace2D import com.teamwizardry.librarianlib.math.Matrix3d import com.teamwizardry.librarianlib.math.Matrix3dView import com.teamwizardry.librarianlib.math.MutableMatrix3d /** * The "main" pixel coordinate space for container GUIs. Any layer within a container can convert points to * [ContainerSpace] to get the location within the "main", centered coordinate system. */ public object ContainerSpace: CoordinateSpace2D { public var guiLeft: Int = 0 public var guiTop: Int = 0 override val parentSpace: CoordinateSpace2D = ScreenSpace private val _transform = MutableMatrix3d() private val _inverseTransform = MutableMatrix3d() override val transform: Matrix3d = Matrix3dView(_transform) get() { updateMatrices() return field } override val inverseTransform: Matrix3d = Matrix3dView(_transform) get() { updateMatrices() return field } private fun updateMatrices() { _transform.set( 1.0, 0.0, -guiLeft.toDouble(), 0.0, 1.0, -guiTop.toDouble(), 0.0, 0.0, 1.0 ) _inverseTransform.set( 1.0, 0.0, guiLeft.toDouble(), 0.0, 1.0, guiTop.toDouble(), 0.0, 0.0, 1.0 ) } }
lgpl-3.0
c70740fad5d16e065f9888a3958818d4
31.511111
107
0.662107
4.141643
false
false
false
false
noud02/Akatsuki
src/main/kotlin/moe/kyubey/akatsuki/extensions/UTF8Control.kt
1
2424
/* * Copyright (c) 2017-2019 Yui * * 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 moe.kyubey.akatsuki.extensions import java.io.InputStream import java.io.InputStreamReader import java.util.* // https://stackoverflow.com/questions/4659929/how-to-use-utf-8-in-resource-properties-with-resourcebundle class UTF8Control : ResourceBundle.Control() { override fun newBundle(p0: String, p1: Locale, p2: String, p3: ClassLoader, p4: Boolean): ResourceBundle { val bundleName = toBundleName(p0, p1) val resourceName = toResourceName(bundleName, "properties") var bundle: ResourceBundle? = null var stream: InputStream? = null if (p4) { val url = p3.getResource(resourceName) if (url != null) { val connection = url.openConnection() if (connection != null) { connection.useCaches = false stream = connection.getInputStream() } } } else { stream = p3.getResourceAsStream(resourceName) } if (stream != null) { try { bundle = PropertyResourceBundle(InputStreamReader(stream, "UTF-8")) } finally { stream.close() } } return bundle as ResourceBundle } }
mit
e8e464ca7aeb056feb724b7efb4398b7
36.890625
110
0.653053
4.464088
false
false
false
false
HKMOpen/ExpandableLayout
library-ui-test/src/main/kotlin/com/github/aakira/expandablelayout/uitest/ExpandableLinearLayoutActivity3.kt
2
2349
package com.github.aakira.expandablelayout.uitest import android.os.Bundle import android.support.v7.app.AppCompatActivity import com.github.aakira.expandablelayout.ExpandableLinearLayout import rx.subscriptions.CompositeSubscription import kotlin.properties.Delegates /** * test for [com.github.aakira.expandablelayout.ExpandableLinearLayout#initlayout] * * The default value is {@link android.view.animation.AccelerateDecelerateInterpolator} * */ class ExpandableLinearLayoutActivity3 : AppCompatActivity() { private var expandableLayout: ExpandableLinearLayout by Delegates.notNull() private val subscriptions: CompositeSubscription = CompositeSubscription() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_expandable_linear_layout3) supportActionBar?.title = ExpandableLinearLayoutActivity::class.java.simpleName expandableLayout = findViewById(R.id.expandableLayout) as ExpandableLinearLayout findViewById(R.id.expandButton)?.setOnClickListener { expandableLayout.toggle() } findViewById(R.id.moveChildButton)?.setOnClickListener { expandableLayout.moveChild(0) } findViewById(R.id.moveChildButton2)?.setOnClickListener { expandableLayout.moveChild(1) } // uncomment if you want to check the #ExpandableLayout.initLayout() // val child1 = findViewById(R.id.child1) as TextView // subscriptions.add(Observable.timer(5, TimeUnit.SECONDS) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe { // child1.text = // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" // expandableLayout.initLayout() // expandableLayout.expand(0, null) // }) } override fun onDestroy() { subscriptions.unsubscribe() super.onDestroy() } }
apache-2.0
04650bb5d7f4f29b076fadf902061919
46
97
0.690081
5.488318
false
false
false
false
minecraft-dev/MinecraftDev
src/test/kotlin/platform/mixin/AccessorMixinTest.kt
1
11847
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin import com.demonwav.mcdev.framework.EdtInterceptor import com.demonwav.mcdev.platform.mixin.inspection.MixinAnnotationTargetInspection import com.demonwav.mcdev.platform.mixin.util.isAccessorMixin import com.intellij.psi.PsiClass import com.intellij.psi.PsiJavaFile import org.intellij.lang.annotations.Language import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(EdtInterceptor::class) @DisplayName("Accessor Mixin Extension Property Tests") class AccessorMixinTest : BaseMixinTest() { private fun doTest(className: String, @Language("JAVA") code: String, test: (psiClass: PsiClass) -> Unit) { var psiClass: PsiClass? = null buildProject { dir("test") { psiClass = java("$className.java", code).toPsiFile<PsiJavaFile>().classes[0] } } test(psiClass!!) } @Test @DisplayName("Valid Accessor Mixin Test") fun validAccessorMixinTest() = doTest( "AccessorMixin", """ package test; import com.demonwav.mcdev.mixintestdata.accessor.BaseMixin; import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.mixin.Mixin; @Mixin(BaseMixin.class) public interface AccessorMixin { @Accessor String getString(); @Accessor int getInt(); @Invoker void invoke(); @Invoker double doThing(); } """ ) { psiClass -> Assertions.assertTrue(psiClass.isAccessorMixin) } @Test @DisplayName("Missing Annotation Accessor Mixin Test") fun missingAnnotationAccessorMixinTest() = doTest( "MissingAnnotationAccessorMixin", """ package test; import com.demonwav.mcdev.mixintestdata.accessor.BaseMixin; import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.mixin.Mixin; @Mixin(BaseMixin.class) public interface MissingAnnotationAccessorMixin { @Accessor String getString(); @Accessor int getInt(); @Invoker void invoke(); double doThing(); } """ ) { psiClass -> Assertions.assertFalse(psiClass.isAccessorMixin) } @Test @DisplayName("Target Interface Accessor Mixin Test") fun targetInterfaceAccessorMixinTest() = doTest( "TargetInterface", """ package test; import com.demonwav.mcdev.mixintestdata.accessor.BaseMixinInterface; import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.mixin.Mixin; @Mixin(BaseMixinInterface.class) public interface TargetInterface { @Accessor String getString(); @Accessor int getInt(); @Invoker void invoke(); @Invoker double doThing(); } """ ) { psiClass -> Assertions.assertFalse(psiClass.isAccessorMixin) } @Test @DisplayName("Accessors Only Accessor Mixin Test") fun accessorsOnlyAccessorMixinTest() = doTest( "AccessorMixin", """ package test; import com.demonwav.mcdev.mixintestdata.accessor.BaseMixin; import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.asm.mixin.Mixin; @Mixin(BaseMixin.class) public interface AccessorMixin { @Accessor String getString(); @Accessor int getInt(); } """ ) { psiClass -> Assertions.assertTrue(psiClass.isAccessorMixin) } @Test @DisplayName("Invokers Only Accessor Mixin Test") fun invokersOnlyAccessorMixinTest() = doTest( "AccessorMixin", """ package test; import com.demonwav.mcdev.mixintestdata.accessor.BaseMixin; import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.mixin.Mixin; @Mixin(BaseMixin.class) public interface AccessorMixin { @Invoker void invoke(); @Invoker double doThing(); } """ ) { psiClass -> Assertions.assertTrue(psiClass.isAccessorMixin) } @Test @DisplayName("Non-Interface Accessor Mixin Test") fun nonInterfaceAccessorMixinTest() = doTest( "NonInterfaceAccessorMixin", """ package test; import com.demonwav.mcdev.mixintestdata.accessor.BaseMixin; import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.mixin.Mixin; @Mixin(BaseMixin.class) public class NonInterfaceAccessorMixin { @Accessor String getString(); @Invoker void invoke(); } """ ) { psiClass -> Assertions.assertFalse(psiClass.isAccessorMixin) } @Test @DisplayName("Non-Interface Targeting Interface Accessor Mixin Test") fun nonInterfaceTargetingInterfaceAccessorMixinTest() = doTest( "NonInterfaceTargetInterface", """ package test; import com.demonwav.mcdev.mixintestdata.accessor.BaseMixinInterface; import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.mixin.Mixin; @Mixin(BaseMixinInterface.class) public class NonInterfaceAccessorMixin { @Accessor String getString(); @Invoker void invoke(); } """ ) { psiClass -> Assertions.assertFalse(psiClass.isAccessorMixin) } @Test @DisplayName("Accessor Mixin Target Test") fun accessorMixinTargetTest() = doTest( "AccessorMixinTargetMixin", """ package test; import com.demonwav.mcdev.mixintestdata.shadow.MixinBase; import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mutable; @Mixin(MixinBase.class) public interface AccessorMixinTargetMixin { @Accessor static String getPrivateStaticString() { return null; } @Accessor static void setPrivateStaticString(String value) {} @Accessor String getPrivateString(); @Accessor void setPrivateString(String value); @Accessor @Mutable void setPrivateFinalString(String value); @Invoker static String callPrivateStaticMethod() { return null; } @Invoker String callPrivateMethod(); @Invoker static MixinBase createMixinBase() { return null; } } """ ) { fixture.enableInspections(MixinAnnotationTargetInspection::class.java) fixture.checkHighlighting(false, false, false) } @Test @DisplayName("Accessor Mixin Renamed Target Test") fun accessorMixinRenamedTargetTest() = doTest( "AccessorMixinRenamedTargetMixin", """ package test; import com.demonwav.mcdev.mixintestdata.shadow.MixinBase; import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.mixin.Mixin; @Mixin(MixinBase.class) public interface AccessorMixinRenamedTargetMixin { @Accessor("privateString") String foo1(); @Accessor("privateString") void foo2(String value); @Invoker("privateMethod") String foo3(); @Invoker("<init>") MixinBase foo4(); } """ ) { fixture.enableInspections(MixinAnnotationTargetInspection::class.java) fixture.checkHighlighting(false, false, false) } @Test @DisplayName("Invalid Accessor Target") fun invalidAccessorTarget() = doTest( "AccessorMixinTargetMixin", """ package test; import com.demonwav.mcdev.mixintestdata.shadow.MixinBase; import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.asm.mixin.Mixin; @Mixin(MixinBase.class) public interface AccessorMixinTargetMixin { @<error descr="Cannot find field foo in target class">Accessor</error> String getFoo(); } """ ) { fixture.enableInspections(MixinAnnotationTargetInspection::class.java) fixture.checkHighlighting(false, false, false) } @Test @DisplayName("Invalid Named Accessor Target") fun invalidNamedAccessorTarget() = doTest( "AccessorMixinTargetMixin", """ package test; import com.demonwav.mcdev.mixintestdata.shadow.MixinBase; import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.asm.mixin.Mixin; @Mixin(MixinBase.class) public interface AccessorMixinTargetMixin { @<error descr="Cannot find field foo in target class">Accessor</error>("foo") String bar(); } """ ) { fixture.enableInspections(MixinAnnotationTargetInspection::class.java) fixture.checkHighlighting(false, false, false) } @Test @DisplayName("Invalid Invoker Target") fun invalidInvokerTarget() = doTest( "AccessorMixinTargetMixin", """ package test; import com.demonwav.mcdev.mixintestdata.shadow.MixinBase; import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.mixin.Mixin; @Mixin(MixinBase.class) public interface AccessorMixinTargetMixin { @<error descr="Cannot find method foo in target class">Invoker</error> String callFoo(); } """ ) { fixture.enableInspections(MixinAnnotationTargetInspection::class.java) fixture.checkHighlighting(false, false, false) } @Test @DisplayName("Invalid Named Invoker Target") fun invalidNamedInvokerTarget() = doTest( "AccessorMixinTargetMixin", """ package test; import com.demonwav.mcdev.mixintestdata.shadow.MixinBase; import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.mixin.Mixin; @Mixin(MixinBase.class) public interface AccessorMixinTargetMixin { @<error descr="Cannot find method foo in target class">Invoker</error>("foo") String bar(); } """ ) { fixture.enableInspections(MixinAnnotationTargetInspection::class.java) fixture.checkHighlighting(false, false, false) } @Test @DisplayName("Invalid Constructor Invoker Target") fun invalidConstructorInvokerTarget() = doTest( "AccessorMixinTargetMixin", """ package test; import com.demonwav.mcdev.mixintestdata.shadow.MixinBase; import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.mixin.Mixin; @Mixin(MixinBase.class) public interface AccessorMixinTargetMixin { @<error descr="Cannot find method <init> in target class">Invoker</error>("<init>") String construct(String invalidArg); } """ ) { fixture.enableInspections(MixinAnnotationTargetInspection::class.java) fixture.checkHighlighting(false, false, false) } }
mit
425c2251e04c6a742e117663b7b9f330
32.27809
132
0.643623
5.080189
false
true
false
false
y2k/JoyReactor
core/src/main/kotlin/y2k/joyreactor/services/requests/UserImageRequest.kt
1
447
package y2k.joyreactor.services.requests /** * Created by y2k on 01/10/15. */ class UserImageRequest { fun execute(name: String): String? { sStorage = IconStorage.get(sStorage, "user.names", "user.icons") val id = sStorage!!.getImageId(name) return if (id == null) null else "http://img0.joyreactor.cc/pics/avatar/user/" + id } companion object { private var sStorage: IconStorage? = null } }
gpl-2.0
5120bb79f98f577334d204a49e888b45
22.578947
91
0.635347
3.492188
false
false
false
false
teobaranga/T-Tasks
t-tasks/src/main/java/com/teo/ttasks/ui/views/TaskDateView.kt
1
1717
package com.teo.ttasks.ui.views import android.content.Context import android.util.AttributeSet import android.view.Gravity import android.view.LayoutInflater import android.widget.LinearLayout import com.teo.ttasks.R import com.teo.ttasks.util.DateUtils import kotlinx.android.synthetic.main.view_task_date.view.* import org.threeten.bp.ZonedDateTime /** * See [R.styleable.TaskDateView] * * @attr ref R.styleable.TaskDateView_dueDate */ class TaskDateView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, defStyleRes: Int = 0 ) : LinearLayout(context, attrs, defStyleAttr, defStyleRes) { /** * The date shown in this view. Can be a due date or a completion date. */ var date: ZonedDateTime? = null set(value) { val equals = field == value if (value == null) { dayOfWeek.text = null dayOfMonth.text = null } else { dayOfWeek.text = value.format(DateUtils.formatterDayName) dayOfMonth.text = value.format(DateUtils.formatterDayNumber) } field = value if (!equals) { invalidate() requestLayout() } } init { LayoutInflater.from(context).inflate(R.layout.view_task_date, this, true) orientation = VERTICAL gravity = Gravity.CENTER_HORIZONTAL val a = context.theme.obtainStyledAttributes(attrs, R.styleable.TaskDateView, 0, 0) try { date = a.getString(R.styleable.TaskDateView_date)?.let { ZonedDateTime.parse(it) } } finally { a.recycle() } } }
apache-2.0
ccc0e2ba22fda5508e7c5d1103f9d6a3
29.122807
94
0.622015
4.281796
false
false
false
false
inorichi/tachiyomi-extensions
src/all/mangaplus/src/eu/kanade/tachiyomi/extension/all/mangaplus/MangaPlusUrlActivity.kt
1
1128
package eu.kanade.tachiyomi.extension.all.mangaplus import android.app.Activity import android.content.ActivityNotFoundException import android.content.Intent import android.os.Bundle import android.util.Log import kotlin.system.exitProcess class MangaPlusUrlActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val pathSegments = intent?.data?.pathSegments if (pathSegments != null && pathSegments.size > 1) { val titleId = pathSegments[1] val mainIntent = Intent().apply { action = "eu.kanade.tachiyomi.SEARCH" putExtra("query", MangaPlus.PREFIX_ID_SEARCH + titleId) putExtra("filter", packageName) } try { startActivity(mainIntent) } catch (e: ActivityNotFoundException) { Log.e("MangaPlusUrlActivity", e.toString()) } } else { Log.e("MangaPlusUrlActivity", "Could not parse URI from intent $intent") } finish() exitProcess(0) } }
apache-2.0
890ea0223ebeddf1f1ec402eb22c79f1
29.486486
84
0.621454
4.904348
false
false
false
false
anlun/haskell-idea-plugin
plugin/src/org/jetbrains/haskell/debugger/frames/ForceEvaluationAction.kt
1
2124
package org.jetbrains.haskell.debugger.frames import com.intellij.xdebugger.impl.ui.tree.actions.XDebuggerTreeActionBase import com.intellij.xdebugger.impl.ui.tree.nodes.XValueNodeImpl import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.xdebugger.frame.presentation.XRegularValuePresentation import com.intellij.openapi.actionSystem.LangDataKeys import org.jetbrains.haskell.debugger.parser.LocalBinding import com.intellij.xdebugger.XDebuggerManager import org.jetbrains.haskell.debugger.HaskellDebugProcess /** * Determines action performed when user select 'Force evaluation' in context menu of variable in current frame. * This action is called by IDEA, so class is registered in plugin.xml * * @author Habibullin Marat */ public class ForceEvaluationAction(): XDebuggerTreeActionBase() { override fun perform(node: XValueNodeImpl?, nodeName: String, actionEvent: AnActionEvent?) { if(node == null || actionEvent == null) { return } val debugProcess = tryGetDebugProcess(actionEvent) if(debugProcess == null) { return } forceSetValue(node, debugProcess) } private fun tryGetDebugProcess(actionEvent: AnActionEvent): HaskellDebugProcess? { val project = actionEvent.getProject() if(project == null) { return null } val debuggerManager = XDebuggerManager.getInstance(project) if(debuggerManager == null) { return null } val session = debuggerManager.getCurrentSession() if(session == null) { return null } return session.getDebugProcess() as HaskellDebugProcess } private fun forceSetValue(node: XValueNodeImpl, debugProcess: HaskellDebugProcess) { val hsDebugValue = node.getValueContainer() as HsDebugValue debugProcess.forceSetValue(hsDebugValue.binding) if(hsDebugValue.binding.value != null) { node.setPresentation(null, XRegularValuePresentation(hsDebugValue.binding.value as String, hsDebugValue.binding.typeName), false) } } }
apache-2.0
c75632a5c3193ee271c81e52ff993d13
39.09434
141
0.717514
4.838269
false
false
false
false
sybila/ode-generator
src/main/java/com/github/sybila/ode/generator/LazyStateMap.kt
1
697
package com.github.sybila.ode.generator import com.github.sybila.checker.StateMap class LazyStateMap<out Params : Any>( val stateCount: Int, val default: Params, val test: (Int) -> Params? ) : StateMap<Params> { override val sizeHint: Int = stateCount override fun contains(state: Int): Boolean = test(state) != null override fun entries(): Iterator<Pair<Int, Params>> = (0 until stateCount).asSequence() .filter { it in this }.map { it to test(it)!! }.iterator() override fun get(state: Int): Params = test(state) ?: default override fun states(): Iterator<Int> = (0 until stateCount).asSequence().filter { it in this }.iterator() }
gpl-3.0
a5e667c7b8f298c035c8a5198da37651
30.727273
109
0.659971
4.005747
false
true
false
false
jakubveverka/SportApp
app/src/main/java/com/example/jakubveverka/sportapp/Models/EventsDbHelper.kt
1
3377
package com.example.jakubveverka.sportapp.Models import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import android.content.ContentValues import com.example.jakubveverka.sportapp.Entities.Event import java.util.* /** * Created by jakubveverka on 12.06.17. * Classic Db helper for Event table */ class EventsDbHelper private constructor(context: Context) : SQLiteOpenHelper(context, EventsDbHelper.DATABASE_NAME, null, EventsDbHelper.DATABASE_VERSION) { companion object { val DATABASE_VERSION = 1 val DATABASE_NAME = "SportApp.db" private var instance: EventsDbHelper? = null @Synchronized fun getInstance(context: Context): EventsDbHelper { if(instance == null) instance = EventsDbHelper(context.applicationContext) return instance!! } } override fun onCreate(db: SQLiteDatabase) { db.execSQL(Event.SQL_CREATE_EVENTS) } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { // This database is only a cache for online data, so its upgrade policy is // to simply to discard the data and start over db.execSQL(Event.SQL_DELETE_EVENTS) onCreate(db) } override fun onDowngrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { onUpgrade(db, oldVersion, newVersion) } fun saveEvent(event: Event): Boolean { val db = this.writableDatabase val values = ContentValues() values.put(Event.COLUMN_NAME, event.name) values.put(Event.COLUMN_PLACE, event.place) values.put(Event.COLUMN_START_TIME, event.startTime) values.put(Event.COLUMN_END_TIME, event.endTime) values.put(Event.COLUMN_USER_UID, event.userUid) return db.insert(Event.TABLE_NAME, null, values) != -1L } fun getAllEventsOfUserWithUid(userUid: String): LinkedList<Event> { val db = this.readableDatabase val selection = Event.COLUMN_USER_UID + " = ?" val selectionArgs = arrayOf(userUid) val sortOrder = Event.COLUMN_START_TIME + " ASC" val cursor = db.query( Event.TABLE_NAME, // The table to query null, // The columns to return selection, // The columns for the WHERE clause selectionArgs, // don't group the rows null, null, // don't filter by row groups sortOrder // The sort order )// The values for the WHERE clause val events = LinkedList<Event>() val nameColumnIndex = cursor.getColumnIndexOrThrow(Event.COLUMN_NAME) val placeColumnIndex = cursor.getColumnIndexOrThrow(Event.COLUMN_PLACE) val startDateColumnIndex = cursor.getColumnIndexOrThrow(Event.COLUMN_START_TIME) val endDateColumnIndex = cursor.getColumnIndexOrThrow(Event.COLUMN_END_TIME) while (cursor.moveToNext()) { val name = cursor.getString(nameColumnIndex) val place = cursor.getString(placeColumnIndex) val startDate = cursor.getLong(startDateColumnIndex) val endDate = cursor.getLong(endDateColumnIndex) events.add(Event(name, place, startDate, endDate, Event.EventStorage.LOCAL, userUid)) } cursor.close() return events } }
mit
e35f74eca685d60f35eb32562fde7a9f
36.955056
157
0.669825
4.437582
false
false
false
false
robovm/robovm-studio
plugins/settings-repository/testSrc/TestCase.kt
1
2647
/* * 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.test import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.impl.stores.StreamProvider import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.io.FileUtil import com.intellij.testFramework.FixtureRule import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.TemporaryDirectory import com.intellij.testFramework.TestLoggerFactory import org.eclipse.jgit.lib.Repository import org.jetbrains.jgit.dirCache.AddFile import org.jetbrains.jgit.dirCache.edit import org.jetbrains.settingsRepository.IcsManager import org.jetbrains.settingsRepository.git import org.junit.Rule import org.junit.rules.TestRule import java.io.File import kotlin.properties.Delegates val testDataPath: String = "${PlatformTestUtil.getCommunityPath()}/plugins/settings-repository/testData" fun StreamProvider.save(path: String, data: ByteArray) { saveContent(path, data, data.size(), RoamingType.PER_USER) } fun Repository.add(data: ByteArray, path: String): Repository { FileUtil.writeToFile(File(getWorkTree(), path), data) edit(AddFile(path)) return this } abstract class TestCase { val fixtureManager = FixtureRule() val tempDirManager = TemporaryDirectory() public Rule fun getTemporaryFolder(): TemporaryDirectory = tempDirManager public Rule fun getFixtureRule(): TestRule = fixtureManager val testHelper = RespositoryHelper() open val icsManager by Delegates.lazy { val icsManager = IcsManager(tempDirManager.newDirectory()) icsManager.repositoryManager.createRepositoryIfNeed() icsManager.repositoryActive = true icsManager } Rule public fun getTestWatcher(): RespositoryHelper = testHelper val remoteRepository: Repository get() = testHelper.repository!! companion object { init { Logger.setFactory(javaClass<TestLoggerFactory>()) } } } fun TemporaryDirectory.createRepository(directoryName: String? = null) = git.createRepository(newDirectory(directoryName))
apache-2.0
fd4985b655edece90462652919b24e7a
32.935897
122
0.788818
4.532534
false
true
false
false
da1z/intellij-community
platform/script-debugger/backend/src/debugger/sourcemap/SourceMap.kt
4
3684
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger.sourcemap import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.Url // sources - is not originally specified, but canonicalized/normalized // lines and columns are zero-based according to specification interface SourceMap { val outFile: String? /** * note: Nested map returns only parent sources */ val sources: Array<Url> val generatedMappings: Mappings val hasNameMappings: Boolean val sourceResolver: SourceResolver fun findSourceMappings(sourceIndex: Int): Mappings fun findSourceIndex(sourceUrls: List<Url>, sourceFile: VirtualFile?, resolver: Lazy<SourceFileResolver?>?, localFileUrlOnly: Boolean): Int fun findSourceMappings(sourceUrls: List<Url>, sourceFile: VirtualFile?, resolver: Lazy<SourceFileResolver?>?, localFileUrlOnly: Boolean): Mappings? { val sourceIndex = findSourceIndex(sourceUrls, sourceFile, resolver, localFileUrlOnly) return if (sourceIndex >= 0) findSourceMappings(sourceIndex) else null } fun getSourceLineByRawLocation(rawLine: Int, rawColumn: Int) = generatedMappings.get(rawLine, rawColumn)?.sourceLine ?: -1 fun findSourceIndex(sourceFile: VirtualFile, localFileUrlOnly: Boolean): Int fun processSourceMappingsInLine(sourceIndex: Int, sourceLine: Int, mappingProcessor: MappingsProcessorInLine): Boolean fun processSourceMappingsInLine(sourceUrls: List<Url>, sourceLine: Int, mappingProcessor: MappingsProcessorInLine, sourceFile: VirtualFile?, resolver: Lazy<SourceFileResolver?>?, localFileUrlOnly: Boolean): Boolean { val sourceIndex = findSourceIndex(sourceUrls, sourceFile, resolver, localFileUrlOnly) return sourceIndex >= 0 && processSourceMappingsInLine(sourceIndex, sourceLine, mappingProcessor) } } class OneLevelSourceMap(override val outFile: String?, override val generatedMappings: Mappings, private val sourceIndexToMappings: Array<MappingList?>, override val sourceResolver: SourceResolver, override val hasNameMappings: Boolean) : SourceMap { override val sources: Array<Url> get() = sourceResolver.canonicalizedUrls override fun findSourceIndex(sourceUrls: List<Url>, sourceFile: VirtualFile?, resolver: Lazy<SourceFileResolver?>?, localFileUrlOnly: Boolean): Int { val index = sourceResolver.findSourceIndex(sourceUrls, sourceFile, localFileUrlOnly) if (index == -1 && resolver != null) { return resolver.value?.let { sourceResolver.findSourceIndex(it) } ?: -1 } return index } // returns SourceMappingList override fun findSourceMappings(sourceIndex: Int) = sourceIndexToMappings.get(sourceIndex)!! override fun findSourceIndex(sourceFile: VirtualFile, localFileUrlOnly: Boolean) = sourceResolver.findSourceIndexByFile(sourceFile, localFileUrlOnly) override fun processSourceMappingsInLine(sourceIndex: Int, sourceLine: Int, mappingProcessor: MappingsProcessorInLine): Boolean { return findSourceMappings(sourceIndex).processMappingsInLine(sourceLine, mappingProcessor) } }
apache-2.0
364af5c91b3f1f90e22275503144ab8e
44.493827
218
0.761129
4.89243
false
false
false
false
sn3d/nomic
nomic-app/src/test/kotlin/nomic/NomicFactionsTest.kt
1
3545
/* * Copyright 2017 [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nomic import com.google.common.jimfs.Configuration import com.google.common.jimfs.Jimfs import nomic.app.NomicApp import nomic.core.BoxRef import nomic.core.Bundle import nomic.core.NomicInstance import nomic.core.SimpleConfig import nomic.hdfs.HdfsPlugin import nomic.hdfs.ResourceFact import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import java.nio.file.FileSystem import java.nio.file.Files /** * @author [email protected] */ class NomicFactionsTest { private lateinit var fs: FileSystem private lateinit var app: NomicInstance @Before fun `setup FileSystem`() { // prepare FS fs = Jimfs.newFileSystem(Configuration.unix()); //fs = FileSystems.getDefault() //prepare HDFS folder Files.createDirectories(fs.getPath("./build/hdfs")); //prepare test data for 'factions-bundle' Files.createDirectories(fs.getPath("./build/bundles/factions-bundle")); fs.copyResource("/bundles/factions-bundle/nomic.box", "./build/bundles/factions-bundle/nomic.box") fs.copyResource("/bundles/factions-bundle/global.txt", "./build/bundles/factions-bundle/global.txt") fs.copyResource("/bundles/factions-bundle/phase1.txt", "./build/bundles/factions-bundle/phase1.txt") fs.copyResource("/bundles/factions-bundle/phase2.txt", "./build/bundles/factions-bundle/phase2.txt") fs.copyResource("/bundles/factions-bundle/phase3.txt", "./build/bundles/factions-bundle/phase3.txt") } @Before fun `create testing Nomic app instance`() { // create Nomic app instance val conf = SimpleConfig( "nomic.user" to "testuser", "hdfs.simulator.basedir" to "./build/hdfs", "nomic.hdfs.home" to "/user/testuser", "nomic.hdfs.app.dir" to "/user/testuser/app", "nomic.hdfs.repository.dir" to "/user/testuser/nomic" ) app = NomicApp(conf, listOf(HdfsPlugin.initSimulator(conf, fs))) } @Test fun `the box with factions should install resources in right order`() { val bundle = Bundle.create(fs.getPath("./build/bundles/factions-bundle")) // check the order of facts they will be installed val box = app.compile(bundle) assertThat((box.facts[3] as ResourceFact).source).isEqualTo("/global.txt") assertThat((box.facts[4] as ResourceFact).source).isEqualTo("/phase1.txt") assertThat((box.facts[5] as ResourceFact).source).isEqualTo("/phase2.txt") assertThat((box.facts[6] as ResourceFact).source).isEqualTo("/phase3.txt") // install the bundle app.install(bundle) // check the order of facts how they were installed val installedBox = app.details(BoxRef.createReferenceTo(box))!! assertThat((installedBox.facts[3] as ResourceFact).source).isEqualTo("/global.txt") assertThat((installedBox.facts[4] as ResourceFact).source).isEqualTo("/phase1.txt") assertThat((installedBox.facts[5] as ResourceFact).source).isEqualTo("/phase2.txt") assertThat((installedBox.facts[6] as ResourceFact).source).isEqualTo("/phase3.txt") } }
apache-2.0
6bb0fd4b617b2373e6fcdea0ff75dac6
35.927083
102
0.746403
3.527363
false
true
false
false
square/wire
wire-library/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/ProtoFile.kt
1
6361
/* * Copyright (C) 2015 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 import com.squareup.wire.Syntax import com.squareup.wire.schema.Extend.Companion.fromElements import com.squareup.wire.schema.Service.Companion.fromElements import com.squareup.wire.schema.Type.Companion.fromElements import com.squareup.wire.schema.internal.parser.ProtoFileElement data class ProtoFile( val location: Location, val imports: List<String>, val publicImports: List<String>, val packageName: String?, val types: List<Type>, val services: List<Service>, val extendList: List<Extend>, val options: Options, val syntax: Syntax?, ) { private var javaPackage: Any? = null fun toElement(): ProtoFileElement { return ProtoFileElement( location, packageName, syntax, imports, publicImports, Type.toElements(types), Service.toElements(services), Extend.toElements(extendList), options.elements ) } /** * Returns the name of this proto file, like `simple_message` for * `squareup/protos/person/simple_message.proto`. */ fun name(): String { var result = location.path val slashIndex = result.lastIndexOf('/') if (slashIndex != -1) { result = result.substring(slashIndex + 1) } if (result.endsWith(".proto")) { result = result.substring(0, result.length - ".proto".length) } return result } /** * Returns all types and subtypes which are found in the proto file. */ fun typesAndNestedTypes(): List<Type> { val typesAndNestedTypes = mutableListOf<Type>() for (type in types) { typesAndNestedTypes.addAll(type.typesAndNestedTypes()) } return typesAndNestedTypes } fun javaPackage(): String? { return javaPackage?.toString() } fun wirePackage(): String? { return options.get(WIRE_PACKAGE)?.toString() } /** * Returns a new proto file that omits types, services, extensions, and options not in * `pruningRules`. */ fun retainAll(schema: Schema, markSet: MarkSet): ProtoFile { val retainedTypes = types.mapNotNull { it.retainAll(schema, markSet) } val retainedServices = services.mapNotNull { it.retainAll(schema, markSet) } val retainedExtends = extendList.mapNotNull { it.retainAll(schema, markSet) } val retainedOptions = options.retainAll(schema, markSet) val result = ProtoFile( location, imports, publicImports, packageName, retainedTypes, retainedServices, retainedExtends, retainedOptions, syntax ) result.javaPackage = javaPackage return result } /** Return a copy of this file with only the marked types. */ fun retainLinked(linkedTypes: Set<ProtoType>, linkedFields: Set<Field>): ProtoFile { val retainedTypes = types.mapNotNull { it.retainLinked(linkedTypes, linkedFields) } val retainedExtends = extendList.mapNotNull { it.retainLinked(linkedFields) } // Other .proto files can't link to our services so strip them unconditionally. val retainedServices = emptyList<Service>() val retainedOptions = options.retainLinked() val result = ProtoFile( location, imports, publicImports, packageName, retainedTypes, retainedServices, retainedExtends, retainedOptions, syntax ) result.javaPackage = javaPackage return result } /** Returns a new proto file that omits unnecessary imports. */ fun retainImports(retained: List<ProtoFile>): ProtoFile { val retainedImports = mutableListOf<String>() for (path in imports) { val importedProtoFile = findProtoFile(retained, path) ?: continue if (path == "google/protobuf/descriptor.proto" && extendList.any { it.name.startsWith("google.protobuf.") } ) { // If we extend a google protobuf type, we should keep the import. retainedImports.add(path) } else if (importedProtoFile.types.isNotEmpty() || importedProtoFile.services.isNotEmpty() || importedProtoFile.extendList.isNotEmpty() ) { retainedImports.add(path) } } return if (imports.size != retainedImports.size) { val result = ProtoFile( location, retainedImports, publicImports, packageName, types, services, extendList, options, syntax ) result.javaPackage = javaPackage result } else { this } } fun linkOptions(linker: Linker, validate: Boolean) { options.link(linker, location, validate) javaPackage = options.get(JAVA_PACKAGE) } override fun toString(): String { return location.path } fun toSchema(): String { return toElement().toSchema() } companion object { val JAVA_PACKAGE = ProtoMember.get(Options.FILE_OPTIONS, "java_package") val WIRE_PACKAGE = ProtoMember.get(Options.FILE_OPTIONS, "wire.wire_package") fun get(protoFileElement: ProtoFileElement): ProtoFile { val packageName = protoFileElement.packageName val syntax = protoFileElement.syntax ?: Syntax.PROTO_2 val types = fromElements(packageName, protoFileElement.types, syntax) val services = fromElements(packageName, protoFileElement.services) val namespaces = when { packageName == null -> listOf() else -> listOf(packageName) } val wireExtends = fromElements(namespaces, protoFileElement.extendDeclarations) val options = Options(Options.FILE_OPTIONS, protoFileElement.options) return ProtoFile( protoFileElement.location, protoFileElement.imports, protoFileElement.publicImports, packageName, types, services, wireExtends, options, protoFileElement.syntax ) } private fun findProtoFile(protoFiles: List<ProtoFile>, path: String): ProtoFile? { return protoFiles.find { it.location.path == path } } } }
apache-2.0
a0a20a7a7dbc9aa9e482ac85d321d308
30.181373
91
0.695803
4.347915
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/compilation/CodeFragmentCompiler.kt
2
14843
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.evaluate.compilation import com.intellij.openapi.application.ReadAction import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.util.registry.Registry import org.jetbrains.kotlin.backend.common.output.OutputFile import org.jetbrains.kotlin.codegen.ClassBuilderFactories import org.jetbrains.kotlin.codegen.KotlinCodegenFacade import org.jetbrains.kotlin.codegen.state.GenerationState import org.jetbrains.kotlin.config.CompilerConfiguration import org.jetbrains.kotlin.config.languageVersionSettings import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.annotations.Annotations import org.jetbrains.kotlin.descriptors.impl.* import org.jetbrains.kotlin.idea.FrontendInternals import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.debugger.evaluate.EvaluationStatus import org.jetbrains.kotlin.idea.debugger.evaluate.ExecutionContext import org.jetbrains.kotlin.idea.debugger.evaluate.classLoading.ClassToLoad import org.jetbrains.kotlin.idea.debugger.evaluate.classLoading.GENERATED_CLASS_NAME import org.jetbrains.kotlin.idea.debugger.evaluate.classLoading.GENERATED_FUNCTION_NAME import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.CompiledDataDescriptor.MethodSignature import org.jetbrains.kotlin.idea.debugger.evaluate.getResolutionFacadeForCodeFragment import org.jetbrains.kotlin.incremental.components.LookupLocation import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.ResolveSession import org.jetbrains.kotlin.resolve.lazy.data.KtClassOrObjectInfo import org.jetbrains.kotlin.resolve.lazy.data.KtScriptInfo import org.jetbrains.kotlin.resolve.lazy.declarations.PackageMemberDeclarationProvider import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyPackageDescriptor import org.jetbrains.kotlin.resolve.scopes.ChainedMemberScope import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.scopes.MemberScope import org.jetbrains.kotlin.resolve.scopes.MemberScopeImpl import org.jetbrains.kotlin.resolve.source.KotlinSourceElement import org.jetbrains.kotlin.storage.LockBasedStorageManager import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.SimpleType import org.jetbrains.kotlin.utils.Printer class CodeFragmentCodegenException(val reason: Exception) : Exception() class CodeFragmentCompiler(private val executionContext: ExecutionContext, private val status: EvaluationStatus) { companion object { fun useIRFragmentCompiler(): Boolean = Registry.get("debugger.kotlin.evaluator.use.jvm.ir.backend").asBoolean() } data class CompilationResult( val classes: List<ClassToLoad>, val parameterInfo: CodeFragmentParameterInfo, val localFunctionSuffixes: Map<CodeFragmentParameter.Dumb, String>, val mainMethodSignature: MethodSignature ) fun compile( codeFragment: KtCodeFragment, filesToCompile: List<KtFile>, bindingContext: BindingContext, moduleDescriptor: ModuleDescriptor ): CompilationResult { val result = ReadAction.nonBlocking<Result<CompilationResult>> { try { Result.success(doCompile(codeFragment, filesToCompile, bindingContext, moduleDescriptor)) } catch (ex: ProcessCanceledException) { throw ex } catch (ex: Exception) { Result.failure(ex) } }.executeSynchronously() return result.getOrThrow() } private fun initBackend(codeFragment: KtCodeFragment): FragmentCompilerCodegen { return if (useIRFragmentCompiler()) { IRFragmentCompilerCodegen() } else { OldFragmentCompilerCodegen(codeFragment) } } private fun doCompile( codeFragment: KtCodeFragment, filesToCompile: List<KtFile>, bindingContext: BindingContext, moduleDescriptor: ModuleDescriptor ): CompilationResult { require(codeFragment is KtBlockCodeFragment || codeFragment is KtExpressionCodeFragment) { "Unsupported code fragment type: $codeFragment" } val project = codeFragment.project val resolutionFacade = getResolutionFacadeForCodeFragment(codeFragment) @OptIn(FrontendInternals::class) val resolveSession = resolutionFacade.getFrontendService(ResolveSession::class.java) val moduleDescriptorWrapper = EvaluatorModuleDescriptor(codeFragment, moduleDescriptor, filesToCompile, resolveSession) val defaultReturnType = moduleDescriptor.builtIns.unitType val returnType = getReturnType(codeFragment, bindingContext, defaultReturnType) val fragmentCompilerBackend = initBackend(codeFragment) val compilerConfiguration = CompilerConfiguration().apply { languageVersionSettings = codeFragment.languageVersionSettings fragmentCompilerBackend.configureCompiler(this) } val parameterInfo = fragmentCompilerBackend.computeFragmentParameters(executionContext, codeFragment, bindingContext, status) val (classDescriptor, methodDescriptor) = createDescriptorsForCodeFragment( codeFragment, Name.identifier(GENERATED_CLASS_NAME), Name.identifier(GENERATED_FUNCTION_NAME), parameterInfo, returnType, moduleDescriptorWrapper.packageFragmentForEvaluator ) fragmentCompilerBackend.initCodegen(classDescriptor, methodDescriptor, parameterInfo) val generationState = GenerationState.Builder( project, ClassBuilderFactories.BINARIES, moduleDescriptorWrapper, bindingContext, filesToCompile, compilerConfiguration ).apply { fragmentCompilerBackend.configureGenerationState( this, bindingContext, compilerConfiguration, classDescriptor, methodDescriptor, parameterInfo ) generateDeclaredClassFilter(GeneratedClassFilterForCodeFragment(codeFragment)) }.build() try { KotlinCodegenFacade.compileCorrectFiles(generationState) return fragmentCompilerBackend.extractResult(methodDescriptor, parameterInfo, generationState).also { generationState.destroy() } } catch (e: ProcessCanceledException) { throw e } catch (e: Exception) { throw CodeFragmentCodegenException(e) } finally { fragmentCompilerBackend.cleanupCodegen() } } private class GeneratedClassFilterForCodeFragment(private val codeFragment: KtCodeFragment) : GenerationState.GenerateClassFilter() { override fun shouldGeneratePackagePart(@Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE") file: KtFile) = file == codeFragment override fun shouldAnnotateClass(processingClassOrObject: KtClassOrObject) = true override fun shouldGenerateClass(processingClassOrObject: KtClassOrObject) = processingClassOrObject.containingFile == codeFragment override fun shouldGenerateCodeFragment(script: KtCodeFragment) = script == this.codeFragment override fun shouldGenerateScript(script: KtScript) = false } private fun getReturnType( codeFragment: KtCodeFragment, bindingContext: BindingContext, defaultReturnType: SimpleType ): KotlinType { return when (codeFragment) { is KtExpressionCodeFragment -> { val typeInfo = bindingContext[BindingContext.EXPRESSION_TYPE_INFO, codeFragment.getContentElement()] typeInfo?.type ?: defaultReturnType } is KtBlockCodeFragment -> { val blockExpression = codeFragment.getContentElement() val lastStatement = blockExpression.statements.lastOrNull() ?: return defaultReturnType val typeInfo = bindingContext[BindingContext.EXPRESSION_TYPE_INFO, lastStatement] typeInfo?.type ?: defaultReturnType } else -> defaultReturnType } } private fun createDescriptorsForCodeFragment( declaration: KtCodeFragment, className: Name, methodName: Name, parameterInfo: CodeFragmentParameterInfo, returnType: KotlinType, packageFragmentDescriptor: PackageFragmentDescriptor ): Pair<ClassDescriptor, FunctionDescriptor> { val classDescriptor = ClassDescriptorImpl( packageFragmentDescriptor, className, Modality.FINAL, ClassKind.OBJECT, emptyList(), KotlinSourceElement(declaration), false, LockBasedStorageManager.NO_LOCKS ) val methodDescriptor = SimpleFunctionDescriptorImpl.create( classDescriptor, Annotations.EMPTY, methodName, CallableMemberDescriptor.Kind.SYNTHESIZED, classDescriptor.source ) val parameters = parameterInfo.parameters.mapIndexed { index, parameter -> ValueParameterDescriptorImpl( methodDescriptor, null, index, Annotations.EMPTY, Name.identifier("p$index"), parameter.targetType, declaresDefaultValue = false, isCrossinline = false, isNoinline = false, varargElementType = null, source = SourceElement.NO_SOURCE ) } methodDescriptor.initialize( null, classDescriptor.thisAsReceiverParameter, emptyList(), emptyList(), parameters, returnType, Modality.FINAL, DescriptorVisibilities.PUBLIC ) val memberScope = EvaluatorMemberScopeForMethod(methodDescriptor) val constructor = ClassConstructorDescriptorImpl.create(classDescriptor, Annotations.EMPTY, true, classDescriptor.source) classDescriptor.initialize(memberScope, setOf(constructor), constructor) return Pair(classDescriptor, methodDescriptor) } } private class EvaluatorMemberScopeForMethod(private val methodDescriptor: SimpleFunctionDescriptor) : MemberScopeImpl() { override fun getContributedFunctions(name: Name, location: LookupLocation): Collection<SimpleFunctionDescriptor> { return if (name == methodDescriptor.name) { listOf(methodDescriptor) } else { emptyList() } } override fun getContributedDescriptors( kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean ): Collection<DeclarationDescriptor> { return if (kindFilter.accepts(methodDescriptor) && nameFilter(methodDescriptor.name)) { listOf(methodDescriptor) } else { emptyList() } } override fun getFunctionNames() = setOf(methodDescriptor.name) override fun printScopeStructure(p: Printer) { p.println(this::class.java.simpleName) } } private class EvaluatorModuleDescriptor( val codeFragment: KtCodeFragment, val moduleDescriptor: ModuleDescriptor, filesToCompile: List<KtFile>, resolveSession: ResolveSession ) : ModuleDescriptor by moduleDescriptor { private val declarationProvider = object : PackageMemberDeclarationProvider { private val rootPackageFiles = filesToCompile.filter { it.packageFqName == FqName.ROOT } + codeFragment override fun getPackageFiles() = rootPackageFiles override fun containsFile(file: KtFile) = file in rootPackageFiles override fun getDeclarationNames() = emptySet<Name>() override fun getDeclarations(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean) = emptyList<KtDeclaration>() override fun getClassOrObjectDeclarations(name: Name) = emptyList<KtClassOrObjectInfo<*>>() override fun getAllDeclaredSubPackages(nameFilter: (Name) -> Boolean) = emptyList<FqName>() override fun getFunctionDeclarations(name: Name) = emptyList<KtNamedFunction>() override fun getPropertyDeclarations(name: Name) = emptyList<KtProperty>() override fun getTypeAliasDeclarations(name: Name) = emptyList<KtTypeAlias>() override fun getDestructuringDeclarationsEntries(name: Name) = emptyList<KtDestructuringDeclarationEntry>() override fun getScriptDeclarations(name: Name) = emptyList<KtScriptInfo>() } // NOTE: Without this override, psi2ir complains when introducing new symbol // when creating an IrFileImpl in `createEmptyIrFile`. override fun getOriginal(): DeclarationDescriptor { return this } val packageFragmentForEvaluator = LazyPackageDescriptor(this, FqName.ROOT, resolveSession, declarationProvider) val rootPackageDescriptorWrapper: PackageViewDescriptor = object : DeclarationDescriptorImpl(Annotations.EMPTY, FqName.ROOT.shortNameOrSpecial()), PackageViewDescriptor { private val rootPackageDescriptor = moduleDescriptor.safeGetPackage(FqName.ROOT) override fun getContainingDeclaration() = rootPackageDescriptor.containingDeclaration override val fqName get() = rootPackageDescriptor.fqName override val module get() = this@EvaluatorModuleDescriptor override val memberScope by lazy { if (fragments.isEmpty()) { MemberScope.Empty } else { val scopes = fragments.map { it.getMemberScope() } + SubpackagesScope(module, fqName) ChainedMemberScope.create("package view scope for $fqName in ${module.name}", scopes) } } override val fragments = listOf(packageFragmentForEvaluator) override fun <R, D> accept(visitor: DeclarationDescriptorVisitor<R, D>, data: D): R { return visitor.visitPackageViewDescriptor(this, data) } } override fun getPackage(fqName: FqName): PackageViewDescriptor = if (fqName != FqName.ROOT) { moduleDescriptor.safeGetPackage(fqName) } else { rootPackageDescriptorWrapper } private fun ModuleDescriptor.safeGetPackage(fqName: FqName): PackageViewDescriptor = try { getPackage(fqName) } catch (e: InvalidModuleException) { throw ProcessCanceledException(e) } } internal val OutputFile.internalClassName: String get() = relativePath.removeSuffix(".class").replace('/', '.')
apache-2.0
923333b59b11c34ed47bad214c0c7f02
44.811728
158
0.718992
5.880745
false
false
false
false
Maccimo/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/bridgeEntities/api/orders.kt
2
7971
// 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.workspaceModel.storage.bridgeEntities.api import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.referrersx import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.annotations.Child import org.jetbrains.deft.Type import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.MutableEntityStorage /** * This entity stores order of facets in iml file. This is needed to ensure that facet tags are saved in the same order to avoid * unnecessary modifications of iml file. */ interface FacetsOrderEntity : WorkspaceEntity { val orderOfFacets: List<String> val moduleEntity: ModuleEntity //region generated code //@formatter:off @GeneratedCodeApiVersion(1) interface Builder: FacetsOrderEntity, ModifiableWorkspaceEntity<FacetsOrderEntity>, ObjBuilder<FacetsOrderEntity> { override var orderOfFacets: List<String> override var entitySource: EntitySource override var moduleEntity: ModuleEntity } companion object: Type<FacetsOrderEntity, Builder>() { operator fun invoke(orderOfFacets: List<String>, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): FacetsOrderEntity { val builder = builder() builder.orderOfFacets = orderOfFacets builder.entitySource = entitySource init?.invoke(builder) return builder } } //@formatter:on //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: FacetsOrderEntity, modification: FacetsOrderEntity.Builder.() -> Unit) = modifyEntity(FacetsOrderEntity.Builder::class.java, entity, modification) //endregion val ModuleEntity.facetOrder: @Child FacetsOrderEntity? get() = referrersx(FacetsOrderEntity::moduleEntity).singleOrNull() /** * This property indicates that external-system-id attribute should be stored in facet configuration to avoid unnecessary modifications */ interface FacetExternalSystemIdEntity : WorkspaceEntity { val externalSystemId: String val facet: FacetEntity //region generated code //@formatter:off @GeneratedCodeApiVersion(1) interface Builder: FacetExternalSystemIdEntity, ModifiableWorkspaceEntity<FacetExternalSystemIdEntity>, ObjBuilder<FacetExternalSystemIdEntity> { override var externalSystemId: String override var entitySource: EntitySource override var facet: FacetEntity } companion object: Type<FacetExternalSystemIdEntity, Builder>() { operator fun invoke(externalSystemId: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): FacetExternalSystemIdEntity { val builder = builder() builder.externalSystemId = externalSystemId builder.entitySource = entitySource init?.invoke(builder) return builder } } //@formatter:on //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: FacetExternalSystemIdEntity, modification: FacetExternalSystemIdEntity.Builder.() -> Unit) = modifyEntity(FacetExternalSystemIdEntity.Builder::class.java, entity, modification) //endregion val FacetEntity.facetExternalSystemIdEntity: @Child FacetExternalSystemIdEntity? get() = referrersx(FacetExternalSystemIdEntity::facet).singleOrNull() /** * This property indicates that external-system-id attribute should be stored in artifact configuration file to avoid unnecessary modifications */ interface ArtifactExternalSystemIdEntity : WorkspaceEntity { val externalSystemId: String val artifactEntity: ArtifactEntity //region generated code //@formatter:off @GeneratedCodeApiVersion(1) interface Builder: ArtifactExternalSystemIdEntity, ModifiableWorkspaceEntity<ArtifactExternalSystemIdEntity>, ObjBuilder<ArtifactExternalSystemIdEntity> { override var externalSystemId: String override var entitySource: EntitySource override var artifactEntity: ArtifactEntity } companion object: Type<ArtifactExternalSystemIdEntity, Builder>() { operator fun invoke(externalSystemId: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ArtifactExternalSystemIdEntity { val builder = builder() builder.externalSystemId = externalSystemId builder.entitySource = entitySource init?.invoke(builder) return builder } } //@formatter:on //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ArtifactExternalSystemIdEntity, modification: ArtifactExternalSystemIdEntity.Builder.() -> Unit) = modifyEntity(ArtifactExternalSystemIdEntity.Builder::class.java, entity, modification) //endregion val ArtifactEntity.artifactExternalSystemIdEntity: @Child ArtifactExternalSystemIdEntity? get() = referrersx(ArtifactExternalSystemIdEntity::artifactEntity).singleOrNull() /** * This property indicates that external-system-id attribute should be stored in library configuration file to avoid unnecessary modifications */ interface LibraryExternalSystemIdEntity: WorkspaceEntity { val externalSystemId: String val library: LibraryEntity //region generated code //@formatter:off @GeneratedCodeApiVersion(1) interface Builder: LibraryExternalSystemIdEntity, ModifiableWorkspaceEntity<LibraryExternalSystemIdEntity>, ObjBuilder<LibraryExternalSystemIdEntity> { override var externalSystemId: String override var entitySource: EntitySource override var library: LibraryEntity } companion object: Type<LibraryExternalSystemIdEntity, Builder>() { operator fun invoke(externalSystemId: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): LibraryExternalSystemIdEntity { val builder = builder() builder.externalSystemId = externalSystemId builder.entitySource = entitySource init?.invoke(builder) return builder } } //@formatter:on //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: LibraryExternalSystemIdEntity, modification: LibraryExternalSystemIdEntity.Builder.() -> Unit) = modifyEntity(LibraryExternalSystemIdEntity.Builder::class.java, entity, modification) //endregion val LibraryEntity.externalSystemId: @Child LibraryExternalSystemIdEntity? get() = referrersx(LibraryExternalSystemIdEntity::library).singleOrNull() /** * This entity stores order of artifacts in ipr file. This is needed to ensure that artifact tags are saved in the same order to avoid * unnecessary modifications of ipr file. */ interface ArtifactsOrderEntity : WorkspaceEntity { val orderOfArtifacts: List<String> //region generated code //@formatter:off @GeneratedCodeApiVersion(1) interface Builder: ArtifactsOrderEntity, ModifiableWorkspaceEntity<ArtifactsOrderEntity>, ObjBuilder<ArtifactsOrderEntity> { override var orderOfArtifacts: List<String> override var entitySource: EntitySource } companion object: Type<ArtifactsOrderEntity, Builder>() { operator fun invoke(orderOfArtifacts: List<String>, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ArtifactsOrderEntity { val builder = builder() builder.orderOfArtifacts = orderOfArtifacts builder.entitySource = entitySource init?.invoke(builder) return builder } } //@formatter:on //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ArtifactsOrderEntity, modification: ArtifactsOrderEntity.Builder.() -> Unit) = modifyEntity(ArtifactsOrderEntity.Builder::class.java, entity, modification) //endregion
apache-2.0
10186ad9c98c751995068856138d2bed
41.174603
231
0.7723
5.621298
false
false
false
false
PolymerLabs/arcs
java/arcs/sdk/HandleHolderBase.kt
1
2761
/* * 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 import kotlinx.coroutines.CoroutineDispatcher /** * Base class used by `schema2kotlin` code-generator tool to generate a class containing all * declared handles. */ open class HandleHolderBase( private val particleName: String, private val entitySpecs: Map<String, Set<EntitySpec<out Entity>>> ) : HandleHolder { val handles = mutableMapOf<String, Handle>().withDefault { handleName -> checkHandleIsValid(handleName) throw NoSuchElementException( "Handle $handleName has not been initialized in $particleName yet." ) } override val dispatcher: CoroutineDispatcher get() { val handle = checkNotNull(handles.values.firstOrNull()) { "No dispatcher available for a HandleHolder with no handles." } return handle.dispatcher } override fun getEntitySpecs(handleName: String): Set<EntitySpec<out Entity>> { checkHandleIsValid(handleName) return entitySpecs.getValue(handleName) } override fun getHandle(handleName: String): Handle { checkHandleIsValid(handleName) return handles.getValue(handleName) } override fun setHandle(handleName: String, handle: Handle) { checkHandleIsValid(handleName) require(!handles.containsKey(handleName)) { "$particleName.$handleName has already been initialized." } handles[handleName] = handle } override fun detach() { handles.forEach { (_, handle) -> handle.unregisterForStorageEvents() } } override fun reset() { // In our current use case, we call `detach` and then reset. But in case someone using // the handle holder doesn't need the split detach/reset behavior, we'll call detach // here as well to make sure resources are cleaned up. detach() handles.forEach { (_, handle) -> handle.close() } handles.clear() } override fun isEmpty() = handles.isEmpty() private fun checkHandleIsValid(handleName: String) { // entitySpecs is passed in the constructor with the full set of specs, so it can be // considered an authoritative list of which handles are valid and which aren't. if (!entitySpecs.containsKey(handleName)) { throw NoSuchElementException( "Particle $particleName does not have a handle with name $handleName." ) } } override suspend fun <T : Entity> createForeignReference(spec: EntitySpec<T>, id: String) = checkNotNull(handles.values.firstOrNull()).createForeignReference(spec, id) }
bsd-3-clause
f5db0b0951c13edb9658c1c6711dd300
32.26506
96
0.715321
4.341195
false
false
false
false
hpost/kommon
app/src/main/java/cc/femto/kommon/ui/transitions/StartAnimatable.kt
1
2496
package cc.femto.kommon.ui.transitions import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.ValueAnimator import android.content.Context import android.graphics.drawable.Animatable import android.graphics.drawable.Drawable import android.transition.Transition import android.transition.TransitionValues import android.util.AttributeSet import android.view.ViewGroup import android.widget.ImageView import cc.femto.kommon.R /** * A transition which sets a specified [Animatable] `drawable` on a target * [ImageView] and [starts][Animatable.start] it when the transition begins. * See https://github.com/nickbutcher/plaid/blob/master/app/src/main/java/io/plaidapp/ui/transitions/StartAnimatable.java */ class StartAnimatable : Transition { private val animatable: Animatable? constructor(animatable: Animatable) : super() { if (animatable !is Drawable) { throw IllegalArgumentException("Non-Drawable resource provided.") } this.animatable = animatable } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { val a = context.obtainStyledAttributes(attrs, R.styleable.StartAnimatable) val drawable = a.getDrawable(R.styleable.StartAnimatable_android_src) a.recycle() if (drawable is Animatable) { animatable = drawable } else { throw IllegalArgumentException("Non-Animatable resource provided.") } } override fun captureStartValues(transitionValues: TransitionValues) { // no-op } override fun captureEndValues(transitionValues: TransitionValues) { // no-op } override fun createAnimator(sceneRoot: ViewGroup, startValues: TransitionValues, endValues: TransitionValues?): Animator? { if (animatable == null || endValues == null || endValues.view !is ImageView) return null val iv = endValues.view as ImageView iv.setImageDrawable(animatable as Drawable?) // need to return a non-null Animator even though we just want to listen for the start val transition = ValueAnimator.ofInt(0, 1) transition.addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator) { animatable.start() } }) return transition } }
apache-2.0
bd2023473484b1ca7173e273cd7b27ec
34.657143
121
0.684696
4.827853
false
false
false
false
mdaniel/intellij-community
platform/platform-impl/src/com/intellij/notification/impl/NotificationsToolWindow.kt
1
52584
// 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.notification.impl import com.intellij.UtilBundle import com.intellij.icons.AllIcons import com.intellij.ide.DataManager import com.intellij.ide.IdeBundle import com.intellij.ide.ui.LafManagerListener import com.intellij.idea.ActionsBundle import com.intellij.notification.ActionCenter import com.intellij.notification.EventLog import com.intellij.notification.LogModel import com.intellij.notification.Notification import com.intellij.notification.impl.ui.NotificationsUtil import com.intellij.notification.impl.widget.IdeNotificationArea import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.options.ShowSettingsUtil import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Divider import com.intellij.openapi.ui.NullableComponent import com.intellij.openapi.ui.OnePixelDivider import com.intellij.openapi.ui.popup.JBPopup import com.intellij.openapi.ui.popup.JBPopupListener import com.intellij.openapi.ui.popup.LightweightWindowEvent import com.intellij.openapi.util.Clock import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowFactory import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.WindowManager import com.intellij.openapi.wm.ex.ToolWindowEx import com.intellij.openapi.wm.ex.ToolWindowManagerListener import com.intellij.ui.* import com.intellij.ui.components.JBLabel import com.intellij.ui.components.JBOptionButton import com.intellij.ui.components.JBPanelWithEmptyText import com.intellij.ui.components.JBScrollPane import com.intellij.ui.components.labels.LinkLabel import com.intellij.ui.components.labels.LinkListener import com.intellij.ui.components.panels.HorizontalLayout import com.intellij.ui.components.panels.VerticalLayout import com.intellij.ui.content.ContentFactory import com.intellij.ui.scale.JBUIScale import com.intellij.util.Alarm import com.intellij.util.text.DateFormatUtil import com.intellij.util.ui.* import org.jetbrains.annotations.Nls import java.awt.* import java.awt.event.* import java.util.* import java.util.function.Consumer import javax.accessibility.AccessibleContext import javax.swing.* import javax.swing.event.DocumentEvent import javax.swing.event.HyperlinkEvent import javax.swing.event.PopupMenuEvent import javax.swing.text.JTextComponent import kotlin.streams.toList internal class NotificationsToolWindowFactory : ToolWindowFactory, DumbAware { companion object { const val ID = "Notifications" internal const val CLEAR_ACTION_ID = "ClearAllNotifications" internal val myModel = ApplicationNotificationModel() fun addNotification(project: Project?, notification: Notification) { if (ActionCenter.isEnabled() && notification.canShowFor(project)) { myModel.addNotification(project, notification) } } fun expire(notification: Notification) { myModel.expire(notification) } fun expireAll() { myModel.expireAll() } fun clearAll(project: Project?) { myModel.clearAll(project) } fun getStateNotifications(project: Project) = myModel.getStateNotifications(project) fun getNotifications(project: Project?) = myModel.getNotifications(project) } override fun isApplicable(project: Project) = ActionCenter.isEnabled() override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) { NotificationContent(project, toolWindow) } } internal class NotificationContent(val project: Project, private val toolWindow: ToolWindow) : Disposable, ToolWindowManagerListener { private val myMainPanel = JBPanelWithEmptyText(BorderLayout()) private val myNotifications = ArrayList<Notification>() private val myIconNotifications = ArrayList<Notification>() private val suggestions: NotificationGroupComponent private val timeline: NotificationGroupComponent private val searchController: SearchController private val singleSelectionHandler = SingleTextSelectionHandler() private var myVisible = true private val mySearchUpdateAlarm = Alarm() init { myMainPanel.background = NotificationComponent.BG_COLOR setEmptyState() handleFocus() suggestions = NotificationGroupComponent(this, true, project) timeline = NotificationGroupComponent(this, false, project) searchController = SearchController(this, suggestions, timeline) myMainPanel.add(createSearchComponent(toolWindow), BorderLayout.NORTH) createGearActions() val splitter = MySplitter() splitter.firstComponent = suggestions splitter.secondComponent = timeline myMainPanel.add(splitter) suggestions.setRemoveCallback(Consumer(::remove)) timeline.setClearCallback(::clear) Disposer.register(toolWindow.disposable, this) val content = ContentFactory.getInstance().createContent(myMainPanel, "", false) content.preferredFocusableComponent = myMainPanel val contentManager = toolWindow.contentManager contentManager.addContent(content) contentManager.setSelectedContent(content) project.messageBus.connect(toolWindow.disposable).subscribe(ToolWindowManagerListener.TOPIC, this) ApplicationManager.getApplication().messageBus.connect(toolWindow.disposable).subscribe(LafManagerListener.TOPIC, LafManagerListener { suggestions.updateLaf() timeline.updateLaf() }) val newNotifications = ArrayList<Notification>() NotificationsToolWindowFactory.myModel.registerAndGetInitNotifications(this, newNotifications) for (notification in newNotifications) { add(notification) } } private fun createSearchComponent(toolWindow: ToolWindow): SearchTextField { val searchField = object : SearchTextField() { override fun updateUI() { super.updateUI() textEditor?.border = null } override fun preprocessEventForTextField(event: KeyEvent): Boolean { if (event.keyCode == KeyEvent.VK_ESCAPE && event.id == KeyEvent.KEY_PRESSED) { isVisible = false searchController.cancelSearch() return true } return super.preprocessEventForTextField(event) } } searchField.textEditor.border = null searchField.border = JBUI.Borders.customLineBottom(JBColor.border()) searchField.isVisible = false if (ExperimentalUI.isNewUI()) { searchController.background = JBUI.CurrentTheme.ToolWindow.background() searchField.textEditor.background = searchController.background } else { searchController.background = UIUtil.getTextFieldBackground() } searchController.searchField = searchField searchField.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { mySearchUpdateAlarm.cancelAllRequests() mySearchUpdateAlarm.addRequest(searchController::doSearch, 100, ModalityState.stateForComponent(searchField)) } }) return searchField } private fun createGearActions() { val gearAction = object : DumbAwareAction() { override fun actionPerformed(e: AnActionEvent) { searchController.startSearch() } } val actionManager = ActionManager.getInstance() val findAction = actionManager.getAction(IdeActions.ACTION_FIND) if (findAction == null) { gearAction.templatePresentation.text = ActionsBundle.actionText(IdeActions.ACTION_FIND) } else { gearAction.copyFrom(findAction) gearAction.registerCustomShortcutSet(findAction.shortcutSet, myMainPanel) } val group = DefaultActionGroup() group.add(gearAction) group.addSeparator() val clearAction = actionManager.getAction(NotificationsToolWindowFactory.CLEAR_ACTION_ID) if (clearAction != null) { group.add(clearAction) } val markAction = actionManager.getAction("MarkNotificationsAsRead") if (markAction != null) { group.add(markAction) } (toolWindow as ToolWindowEx).setAdditionalGearActions(group) } fun setEmptyState() { myMainPanel.emptyText.appendLine(IdeBundle.message("notifications.toolwindow.empty.text.first.line")) @Suppress("DialogTitleCapitalization") myMainPanel.emptyText.appendLine(IdeBundle.message("notifications.toolwindow.empty.text.second.line")) } fun clearEmptyState() { myMainPanel.emptyText.clear() } private fun handleFocus() { val listener = AWTEventListener { if (it is MouseEvent && it.id == MouseEvent.MOUSE_PRESSED && !toolWindow.isActive && UIUtil.isAncestor(myMainPanel, it.component)) { it.component.requestFocus() } } Toolkit.getDefaultToolkit().addAWTEventListener(listener, AWTEvent.MOUSE_EVENT_MASK) Disposer.register(toolWindow.disposable, Disposable { Toolkit.getDefaultToolkit().removeAWTEventListener(listener) }) } fun add(notification: Notification) { if (!NotificationsConfigurationImpl.getSettings(notification.groupId).isShouldLog) { return } if (notification.isSuggestionType) { suggestions.add(notification, singleSelectionHandler) } else { timeline.add(notification, singleSelectionHandler) } myNotifications.add(notification) myIconNotifications.add(notification) searchController.update() setStatusMessage(notification) updateIcon() } fun getStateNotifications() = ArrayList(myIconNotifications) fun getNotifications() = ArrayList(myNotifications) fun isEmpty() = suggestions.isEmpty() && timeline.isEmpty() fun expire(notification: Notification?) { if (notification == null) { val notifications = ArrayList(myNotifications) myNotifications.clear() myIconNotifications.clear() suggestions.expireAll() timeline.expireAll() searchController.update() setStatusMessage(null) updateIcon() for (n in notifications) { n.expire() } } else { remove(notification) } } private fun remove(notification: Notification) { if (notification.isSuggestionType) { suggestions.remove(notification) } else { timeline.remove(notification) } myNotifications.remove(notification) myIconNotifications.remove(notification) searchController.update() setStatusMessage() updateIcon() } private fun clear(notifications: List<Notification>) { myNotifications.removeAll(notifications) myIconNotifications.removeAll(notifications) searchController.update() setStatusMessage() updateIcon() } fun clearAll() { project.closeAllBalloons() myNotifications.clear() myIconNotifications.clear() suggestions.clear() timeline.clear() searchController.update() setStatusMessage(null) updateIcon() } override fun stateChanged(toolWindowManager: ToolWindowManager) { val visible = toolWindow.isVisible if (myVisible != visible) { myVisible = visible if (visible) { project.closeAllBalloons() suggestions.updateComponents() timeline.updateComponents() } else { suggestions.clearNewState() timeline.clearNewState() myIconNotifications.clear() updateIcon() } } } private fun updateIcon() { toolWindow.setIcon(IdeNotificationArea.getActionCenterNotificationIcon(myIconNotifications)) LogModel.fireModelChanged() } private fun setStatusMessage() { setStatusMessage(myNotifications.findLast { it.isImportant || it.isImportantSuggestion }) } private fun setStatusMessage(notification: Notification?) { EventLog.getLogModel(project).setStatusMessage(notification) } override fun dispose() { NotificationsToolWindowFactory.myModel.unregister(this) Disposer.dispose(mySearchUpdateAlarm) } fun fullRepaint() { myMainPanel.doLayout() myMainPanel.revalidate() myMainPanel.repaint() } } private class MySplitter : OnePixelSplitter(true, .5f) { override fun createDivider(): Divider { return object : OnePixelDivider(true, this) { override fun setVisible(aFlag: Boolean) { super.setVisible(aFlag) setResizeEnabled(aFlag) if (!aFlag) { setBounds(0, 0, 0, 0) } } override fun setBackground(bg: Color?) { super.setBackground(JBColor.border()) } } } } private fun JComponent.mediumFontFunction() { font = JBFont.medium() val f: (JComponent) -> Unit = { it.font = JBFont.medium() } putClientProperty(NotificationGroupComponent.FONT_KEY, f) } private fun JComponent.smallFontFunction() { font = JBFont.small() val f: (JComponent) -> Unit = { it.font = JBFont.small() } putClientProperty(NotificationGroupComponent.FONT_KEY, f) } private class SearchController(private val mainContent: NotificationContent, private val suggestions: NotificationGroupComponent, private val timeline: NotificationGroupComponent) { lateinit var searchField: SearchTextField lateinit var background: Color fun startSearch() { searchField.isVisible = true searchField.selectText() searchField.requestFocus() mainContent.clearEmptyState() if (searchField.text.isNotEmpty()) { doSearch() } } fun doSearch() { val query = searchField.text if (query.isEmpty()) { searchField.textEditor.background = background clearSearch() return } var result = false val function: (NotificationComponent) -> Unit = { if (it.applySearchQuery(query)) { result = true } } suggestions.iterateComponents(function) timeline.iterateComponents(function) searchField.textEditor.background = if (result) background else LightColors.RED mainContent.fullRepaint() } fun update() { if (searchField.isVisible && searchField.text.isNotEmpty()) { doSearch() } } fun cancelSearch() { mainContent.setEmptyState() clearSearch() } private fun clearSearch() { val function: (NotificationComponent) -> Unit = { it.applySearchQuery(null) } suggestions.iterateComponents(function) timeline.iterateComponents(function) mainContent.fullRepaint() } } private class NotificationGroupComponent(private val myMainContent: NotificationContent, private val mySuggestionType: Boolean, private val myProject: Project) : JPanel(BorderLayout()), NullableComponent { companion object { const val FONT_KEY = "FontFunction" } private val myTitle = JBLabel( IdeBundle.message(if (mySuggestionType) "notifications.toolwindow.suggestions" else "notifications.toolwindow.timeline")) private val myList = JPanel(VerticalLayout(JBUI.scale(10))) private val myScrollPane = object : JBScrollPane(myList, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) { override fun setupCorners() { super.setupCorners() border = null } override fun updateUI() { super.updateUI() border = null } } private var myScrollValue = 0 private val myEventHandler = ComponentEventHandler() private val myTimeComponents = ArrayList<JLabel>() private val myTimeAlarm = Alarm(myProject) private lateinit var myClearCallback: (List<Notification>) -> Unit private lateinit var myRemoveCallback: Consumer<Notification> init { background = NotificationComponent.BG_COLOR val mainPanel = JPanel(BorderLayout(0, JBUI.scale(8))) mainPanel.isOpaque = false mainPanel.border = JBUI.Borders.empty(8, 8, 0, 0) add(mainPanel) myTitle.mediumFontFunction() myTitle.foreground = NotificationComponent.INFO_COLOR if (mySuggestionType) { myTitle.border = JBUI.Borders.emptyLeft(10) mainPanel.add(myTitle, BorderLayout.NORTH) } else { val panel = JPanel(BorderLayout()) panel.isOpaque = false panel.border = JBUI.Borders.emptyLeft(10) panel.add(myTitle, BorderLayout.WEST) val clearAll = LinkLabel(IdeBundle.message("notifications.toolwindow.timeline.clear.all"), null) { _: LinkLabel<Unit>, _: Unit? -> clearAll() } clearAll.mediumFontFunction() clearAll.border = JBUI.Borders.emptyRight(20) panel.add(clearAll, BorderLayout.EAST) mainPanel.add(panel, BorderLayout.NORTH) } myList.isOpaque = true myList.background = NotificationComponent.BG_COLOR myList.border = JBUI.Borders.emptyRight(10) myScrollPane.border = null mainPanel.add(myScrollPane) myScrollPane.verticalScrollBar.addAdjustmentListener { val value = it.value if (myScrollValue == 0 && value > 0 || myScrollValue > 0 && value == 0) { myScrollValue = value repaint() } else { myScrollValue = value } } myEventHandler.add(this) } fun updateLaf() { updateComponents() iterateComponents { it.updateLaf() } } override fun paintComponent(g: Graphics) { super.paintComponent(g) if (myScrollValue > 0) { g.color = JBColor.border() val y = myScrollPane.y - 1 g.drawLine(0, y, width, y) } } fun add(notification: Notification, singleSelectionHandler: SingleTextSelectionHandler) { val component = NotificationComponent(myProject, notification, myTimeComponents, singleSelectionHandler) component.setNew(true) myList.add(component, 0) updateLayout() myEventHandler.add(component) updateContent() if (mySuggestionType) { component.setDoNotAskHandler { forProject -> component.myNotificationWrapper.notification!! .setDoNotAskFor(if (forProject) myProject else null) .also { myRemoveCallback.accept(it) } .hideBalloon() } component.setRemoveCallback(myRemoveCallback) } } private fun updateLayout() { val layout = myList.layout iterateComponents { component -> layout.removeLayoutComponent(component) layout.addLayoutComponent(null, component) } } fun isEmpty(): Boolean { val count = myList.componentCount for (i in 0 until count) { if (myList.getComponent(i) is NotificationComponent) { return false } } return true } fun setRemoveCallback(callback: Consumer<Notification>) { myRemoveCallback = callback } fun remove(notification: Notification) { val count = myList.componentCount for (i in 0 until count) { val component = myList.getComponent(i) as NotificationComponent if (component.myNotificationWrapper.notification === notification) { if (notification.isSuggestionType) { component.removeFromParent() myList.remove(i) } else { component.expire() } break } } updateContent() } fun setClearCallback(callback: (List<Notification>) -> Unit) { myClearCallback = callback } private fun clearAll() { myProject.closeAllBalloons() val notifications = ArrayList<Notification>() iterateComponents { val notification = it.myNotificationWrapper.notification if (notification != null) { notifications.add(notification) } } clear() myClearCallback.invoke(notifications) } fun expireAll() { if (mySuggestionType) { clear() } else { iterateComponents { if (it.myNotificationWrapper.notification != null) { it.expire() } } updateContent() } } fun clear() { iterateComponents { it.removeFromParent() } myList.removeAll() updateContent() } fun clearNewState() { iterateComponents { it.setNew(false) } } fun updateComponents() { UIUtil.uiTraverser(this).filter(JComponent::class.java).forEach { val value = it.getClientProperty(FONT_KEY) if (value != null) { (value as (JComponent) -> Unit).invoke(it) } } myMainContent.fullRepaint() } inline fun iterateComponents(f: (NotificationComponent) -> Unit) { val count = myList.componentCount for (i in 0 until count) { f.invoke(myList.getComponent(i) as NotificationComponent) } } private fun updateContent() { if (!mySuggestionType && !myTimeAlarm.isDisposed) { myTimeAlarm.cancelAllRequests() object : Runnable { override fun run() { for (timeComponent in myTimeComponents) { timeComponent.text = formatPrettyDateTime(timeComponent.getClientProperty(NotificationComponent.TIME_KEY) as Long) } if (myTimeComponents.isNotEmpty() && !myTimeAlarm.isDisposed) { myTimeAlarm.addRequest(this, 30000) } } }.run() } myMainContent.fullRepaint() } private fun formatPrettyDateTime(time: Long): @NlsSafe String { val c = Calendar.getInstance() c.timeInMillis = Clock.getTime() val currentYear = c[Calendar.YEAR] val currentDayOfYear = c[Calendar.DAY_OF_YEAR] c.timeInMillis = time val year = c[Calendar.YEAR] val dayOfYear = c[Calendar.DAY_OF_YEAR] if (currentYear == year && currentDayOfYear == dayOfYear) { return DateFormatUtil.formatTime(time) } val isYesterdayOnPreviousYear = currentYear == year + 1 && currentDayOfYear == 1 && dayOfYear == c.getActualMaximum( Calendar.DAY_OF_YEAR) val isYesterday = isYesterdayOnPreviousYear || currentYear == year && currentDayOfYear == dayOfYear + 1 if (isYesterday) { return UtilBundle.message("date.format.yesterday") } return DateFormatUtil.formatDate(time) } override fun isVisible(): Boolean { if (super.isVisible()) { val count = myList.componentCount for (i in 0 until count) { if (myList.getComponent(i).isVisible) { return true } } } return false } override fun isNull(): Boolean = !isVisible } private class NotificationComponent(val project: Project, notification: Notification, timeComponents: ArrayList<JLabel>, val singleSelectionHandler: SingleTextSelectionHandler) : JPanel() { companion object { val BG_COLOR: Color get() { if (ExperimentalUI.isNewUI()) { return JBUI.CurrentTheme.ToolWindow.background() } return UIUtil.getListBackground() } val INFO_COLOR = JBColor.namedColor("Label.infoForeground", JBColor(Gray.x80, Gray.x8C)) internal const val NEW_COLOR_NAME = "NotificationsToolwindow.newNotification.background" internal val NEW_DEFAULT_COLOR = JBColor(0xE6EEF7, 0x45494A) val NEW_COLOR = JBColor.namedColor(NEW_COLOR_NAME, NEW_DEFAULT_COLOR) val NEW_HOVER_COLOR = JBColor.namedColor("NotificationsToolwindow.newNotification.hoverBackground", JBColor(0xE6EEF7, 0x45494A)) val HOVER_COLOR = JBColor.namedColor("NotificationsToolwindow.Notification.hoverBackground", BG_COLOR) const val TIME_KEY = "TimestampKey" } val myNotificationWrapper = NotificationWrapper(notification) private var myIsNew = false private var myHoverState = false private val myMoreButton: Component? private var myMorePopupVisible = false private var myRoundColor = BG_COLOR private lateinit var myDoNotAskHandler: (Boolean) -> Unit private lateinit var myRemoveCallback: Consumer<Notification> private var myMorePopup: JBPopup? = null var myMoreAwtPopup: JPopupMenu? = null var myDropDownPopup: JPopupMenu? = null private var myLafUpdater: Runnable? = null init { isOpaque = true background = BG_COLOR border = JBUI.Borders.empty(10, 10, 10, 0) layout = object : BorderLayout(JBUI.scale(7), 0) { private var myEastComponent: Component? = null override fun addLayoutComponent(name: String?, comp: Component) { if (EAST == name) { myEastComponent = comp } else { super.addLayoutComponent(name, comp) } } override fun layoutContainer(target: Container) { super.layoutContainer(target) if (myEastComponent != null && myEastComponent!!.isVisible) { val insets = target.insets val height = target.height - insets.bottom - insets.top val component = myEastComponent!! component.setSize(component.width, height) val d = component.preferredSize component.setBounds(target.width - insets.right - d.width, insets.top, d.width, height) } } } val iconPanel = JPanel(BorderLayout()) iconPanel.isOpaque = false iconPanel.add(JBLabel(NotificationsUtil.getIcon(notification)), BorderLayout.NORTH) add(iconPanel, BorderLayout.WEST) val centerPanel = JPanel(VerticalLayout(JBUI.scale(8))) centerPanel.isOpaque = false centerPanel.border = JBUI.Borders.emptyRight(10) var titlePanel: JPanel? = null if (notification.hasTitle()) { val titleContent = NotificationsUtil.buildHtml(notification, null, false, null, null) val title = object : JBLabel(titleContent) { override fun updateUI() { val oldEditor = UIUtil.findComponentOfType(this, JEditorPane::class.java) if (oldEditor != null) { singleSelectionHandler.remove(oldEditor) } super.updateUI() val newEditor = UIUtil.findComponentOfType(this, JEditorPane::class.java) if (newEditor != null) { singleSelectionHandler.add(newEditor, true) } } } try { title.setCopyable(true) } catch (_: Exception) { } NotificationsManagerImpl.setTextAccessibleName(title, titleContent) val editor = UIUtil.findComponentOfType(title, JEditorPane::class.java) if (editor != null) { singleSelectionHandler.add(editor, true) } if (notification.isSuggestionType) { centerPanel.add(title) } else { titlePanel = JPanel(BorderLayout()) titlePanel.isOpaque = false titlePanel.add(title) centerPanel.add(titlePanel) } } if (notification.hasContent()) { val textContent = NotificationsUtil.buildFullContent(notification) val textComponent = createTextComponent(textContent) NotificationsManagerImpl.setTextAccessibleName(textComponent, textContent) singleSelectionHandler.add(textComponent, true) if (!notification.hasTitle() && !notification.isSuggestionType) { titlePanel = JPanel(BorderLayout()) titlePanel.isOpaque = false titlePanel.add(textComponent) centerPanel.add(titlePanel) } else { centerPanel.add(textComponent) } } val actions = notification.actions val actionsSize = actions.size val helpAction = notification.contextHelpAction if (actionsSize > 0 || helpAction != null) { val layout = HorizontalLayout(JBUIScale.scale(16)) val actionPanel = JPanel(if (!notification.isSuggestionType && actions.size > 1) DropDownActionLayout(layout) else layout) actionPanel.isOpaque = false if (notification.isSuggestionType) { if (actionsSize > 0) { val button = JButton(actions[0].templateText) button.isOpaque = false button.addActionListener { runAction(actions[0], it.source) } actionPanel.add(button) if (actionsSize == 2) { actionPanel.add(createAction(actions[1])) } else if (actionsSize > 2) { actionPanel.add(MoreAction(this, actions)) } } } else { if (actionsSize > 1 && notification.collapseDirection == Notification.CollapseActionsDirection.KEEP_RIGHTMOST) { actionPanel.add(MyDropDownAction(this)) } for (action in actions) { actionPanel.add(createAction(action)) } if (actionsSize > 1 && notification.collapseDirection == Notification.CollapseActionsDirection.KEEP_LEFTMOST) { actionPanel.add(MyDropDownAction(this)) } } if (helpAction != null) { val presentation = helpAction.templatePresentation val helpLabel = ContextHelpLabel.create(StringUtil.defaultIfEmpty(presentation.text, ""), presentation.description) helpLabel.foreground = UIUtil.getLabelDisabledForeground() actionPanel.add(helpLabel) } if (!notification.hasTitle() && !notification.hasContent() && !notification.isSuggestionType) { titlePanel = JPanel(BorderLayout()) titlePanel.isOpaque = false actionPanel.add(titlePanel, HorizontalLayout.RIGHT) } centerPanel.add(actionPanel) } add(centerPanel) if (notification.isSuggestionType) { val group = DefaultActionGroup() group.isPopup = true if (NotificationsConfigurationImpl.getInstanceImpl().isRegistered(notification.groupId)) { group.add(object : DumbAwareAction(IdeBundle.message("action.text.settings")) { override fun actionPerformed(e: AnActionEvent) { doShowSettings() } }) group.addSeparator() } val remindAction = RemindLaterManager.createAction(notification, DateFormatUtil.DAY) if (remindAction != null) { @Suppress("DialogTitleCapitalization") group.add(object : DumbAwareAction(IdeBundle.message("notifications.toolwindow.remind.tomorrow")) { override fun actionPerformed(e: AnActionEvent) { remindAction.run() myRemoveCallback.accept(myNotificationWrapper.notification!!) myNotificationWrapper.notification!!.hideBalloon() } }) } @Suppress("DialogTitleCapitalization") group.add(object : DumbAwareAction(IdeBundle.message("notifications.toolwindow.dont.show.again.for.this.project")) { override fun actionPerformed(e: AnActionEvent) { myDoNotAskHandler.invoke(true) } }) @Suppress("DialogTitleCapitalization") group.add(object : DumbAwareAction(IdeBundle.message("notifications.toolwindow.dont.show.again")) { override fun actionPerformed(e: AnActionEvent) { myDoNotAskHandler.invoke(false) } }) val presentation = Presentation() presentation.icon = AllIcons.Actions.More presentation.putClientProperty(ActionButton.HIDE_DROPDOWN_ICON, java.lang.Boolean.TRUE) val button = object : ActionButton(group, presentation, ActionPlaces.UNKNOWN, ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE) { override fun createAndShowActionGroupPopup(actionGroup: ActionGroup, event: AnActionEvent): JBPopup { myMorePopupVisible = true val popup = super.createAndShowActionGroupPopup(actionGroup, event) myMorePopup = popup popup.addListener(object : JBPopupListener { override fun onClosed(event: LightweightWindowEvent) { myMorePopup = null ApplicationManager.getApplication().invokeLater { myMorePopupVisible = false isVisible = myHoverState } } }) return popup } } button.border = JBUI.Borders.emptyRight(5) button.isVisible = false myMoreButton = button val eastPanel = JPanel(BorderLayout()) eastPanel.isOpaque = false eastPanel.add(button, BorderLayout.NORTH) add(eastPanel, BorderLayout.EAST) setComponentZOrder(eastPanel, 0) } else { val timeComponent = JBLabel(DateFormatUtil.formatPrettyDateTime(notification.timestamp)) timeComponent.putClientProperty(TIME_KEY, notification.timestamp) timeComponent.verticalAlignment = SwingConstants.TOP timeComponent.verticalTextPosition = SwingConstants.TOP timeComponent.toolTipText = DateFormatUtil.formatDateTime(notification.timestamp) timeComponent.border = JBUI.Borders.emptyRight(10) timeComponent.smallFontFunction() timeComponent.foreground = INFO_COLOR timeComponents.add(timeComponent) if (NotificationsConfigurationImpl.getInstanceImpl().isRegistered(notification.groupId)) { val button = object: InplaceButton(IdeBundle.message("tooltip.turn.notification.off"), AllIcons.Ide.Notification.Gear, ActionListener { doShowSettings() }) { override fun setBounds(x: Int, y: Int, width: Int, height: Int) { super.setBounds(x, y - 1, width, height) } } button.setIcons(AllIcons.Ide.Notification.Gear, null, AllIcons.Ide.Notification.GearHover) myMoreButton = button val buttonWrapper = JPanel(BorderLayout()) buttonWrapper.isOpaque = false buttonWrapper.border = JBUI.Borders.emptyRight(10) buttonWrapper.add(button, BorderLayout.NORTH) buttonWrapper.preferredSize = buttonWrapper.preferredSize button.isVisible = false val eastPanel = JPanel(BorderLayout()) eastPanel.isOpaque = false eastPanel.add(buttonWrapper, BorderLayout.WEST) eastPanel.add(timeComponent, BorderLayout.EAST) titlePanel!!.add(eastPanel, BorderLayout.EAST) } else { titlePanel!!.add(timeComponent, BorderLayout.EAST) myMoreButton = null } } } private fun createAction(action: AnAction): JComponent { return object : LinkLabel<AnAction>(action.templateText, action.templatePresentation.icon, { link, _action -> runAction(_action, link) }, action) { override fun getTextColor() = JBUI.CurrentTheme.Link.Foreground.ENABLED } } private fun doShowSettings() { NotificationCollector.getInstance().logNotificationSettingsClicked(myNotificationWrapper.id, myNotificationWrapper.displayId, myNotificationWrapper.groupId) val configurable = NotificationsConfigurable() ShowSettingsUtil.getInstance().editConfigurable(project, configurable, Runnable { val runnable = configurable.enableSearch(myNotificationWrapper.groupId) runnable?.run() }) } private fun runAction(action: AnAction, component: Any) { setNew(false) NotificationCollector.getInstance().logNotificationActionInvoked(null, myNotificationWrapper.notification!!, action, NotificationCollector.NotificationPlace.ACTION_CENTER) Notification.fire(myNotificationWrapper.notification!!, action, DataManager.getInstance().getDataContext(component as Component)) } fun expire() { closePopups() myNotificationWrapper.notification = null setNew(false) for (component in UIUtil.findComponentsOfType(this, LinkLabel::class.java)) { component.isEnabled = false } val dropDownAction = UIUtil.findComponentOfType(this, MyDropDownAction::class.java) if (dropDownAction != null) { DataManager.removeDataProvider(dropDownAction) } } fun removeFromParent() { closePopups() for (component in UIUtil.findComponentsOfType(this, JTextComponent::class.java)) { singleSelectionHandler.remove(component) } } private fun closePopups() { myMorePopup?.cancel() myMoreAwtPopup?.isVisible = false myDropDownPopup?.isVisible = false } private fun createTextComponent(text: @Nls String): JEditorPane { val component = JEditorPane() component.isEditable = false component.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, java.lang.Boolean.TRUE) component.contentType = "text/html" component.isOpaque = false component.border = null NotificationsUtil.configureHtmlEditorKit(component, false) if (myNotificationWrapper.notification!!.listener != null) { component.addHyperlinkListener { e -> val notification = myNotificationWrapper.notification if (notification != null && e.eventType == HyperlinkEvent.EventType.ACTIVATED) { val listener = notification.listener if (listener != null) { NotificationCollector.getInstance().logHyperlinkClicked(notification) listener.hyperlinkUpdate(notification, e) } } } } component.putClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY, StringUtil.unescapeXmlEntities(StringUtil.stripHtml(text, " "))) component.text = text component.isEditable = false if (component.caret != null) { component.caretPosition = 0 } myLafUpdater = Runnable { NotificationsUtil.configureHtmlEditorKit(component, false) component.text = text component.revalidate() component.repaint() } return component } fun updateLaf() { myLafUpdater?.run() updateColor() } fun setDoNotAskHandler(handler: (Boolean) -> Unit) { myDoNotAskHandler = handler } fun setRemoveCallback(callback: Consumer<Notification>) { myRemoveCallback = callback } fun isHover(): Boolean = myHoverState fun setNew(state: Boolean) { if (myIsNew != state) { myIsNew = state updateColor() } } fun setHover(state: Boolean) { myHoverState = state if (myMoreButton != null) { if (!myMorePopupVisible) { myMoreButton.isVisible = state } } updateColor() } private fun updateColor() { if (myHoverState) { if (myIsNew) { setColor(NEW_HOVER_COLOR) } else { setColor(HOVER_COLOR) } } else if (myIsNew) { if (UIManager.getColor(NEW_COLOR_NAME) != null) { setColor(NEW_COLOR) } else { setColor(NEW_DEFAULT_COLOR) } } else { setColor(BG_COLOR) } } private fun setColor(color: Color) { myRoundColor = color repaint() } override fun paintComponent(g: Graphics) { super.paintComponent(g) if (myRoundColor !== BG_COLOR) { g.color = myRoundColor val config = GraphicsUtil.setupAAPainting(g) val cornerRadius = NotificationBalloonRoundShadowBorderProvider.CORNER_RADIUS.get() g.fillRoundRect(0, 0, width, height, cornerRadius, cornerRadius) config.restore() } } fun applySearchQuery(query: String?): Boolean { if (query == null) { isVisible = true return true } val result = matchQuery(query) isVisible = result return result } private fun matchQuery(query: @NlsSafe String): Boolean { if (myNotificationWrapper.title.contains(query, true)) { return true } val subtitle = myNotificationWrapper.subtitle if (subtitle != null && subtitle.contains(query, true)) { return true } if (myNotificationWrapper.content.contains(query, true)) { return true } for (action in myNotificationWrapper.actions) { if (action != null && action.contains(query, true)) { return true } } return false } } private class MoreAction(val notificationComponent: NotificationComponent, actions: List<AnAction>) : NotificationsManagerImpl.DropDownAction(null, null) { val group = DefaultActionGroup() init { val size = actions.size for (i in 1..size - 1) { group.add(actions[i]) } setListener(LinkListener { link, _ -> val popup = NotificationsManagerImpl.showPopup(link, group) notificationComponent.myMoreAwtPopup = popup popup?.addPopupMenuListener(object: PopupMenuListenerAdapter() { override fun popupMenuWillBecomeInvisible(e: PopupMenuEvent?) { notificationComponent.myMoreAwtPopup = null } }) }, null) text = IdeBundle.message("notifications.action.more") Notification.setDataProvider(notificationComponent.myNotificationWrapper.notification!!, this) } override fun getTextColor() = JBUI.CurrentTheme.Link.Foreground.ENABLED } private class MyDropDownAction(val notificationComponent: NotificationComponent) : NotificationsManagerImpl.DropDownAction(null, null) { var collapseActionsDirection: Notification.CollapseActionsDirection = notificationComponent.myNotificationWrapper.notification!!.collapseDirection init { setListener(LinkListener { link, _ -> val group = DefaultActionGroup() val layout = link.parent.layout as DropDownActionLayout for (action in layout.actions) { if (!action.isVisible) { group.add(action.linkData) } } val popup = NotificationsManagerImpl.showPopup(link, group) notificationComponent.myDropDownPopup = popup popup?.addPopupMenuListener(object: PopupMenuListenerAdapter() { override fun popupMenuWillBecomeInvisible(e: PopupMenuEvent?) { notificationComponent.myDropDownPopup = null } }) }, null) text = notificationComponent.myNotificationWrapper.notification!!.dropDownText isVisible = false Notification.setDataProvider(notificationComponent.myNotificationWrapper.notification!!, this) } override fun getTextColor() = JBUI.CurrentTheme.Link.Foreground.ENABLED } private class NotificationWrapper(notification: Notification) { val title = notification.title val subtitle = notification.subtitle val content = notification.content val id = notification.id val displayId = notification.displayId val groupId = notification.groupId val actions: List<String?> = notification.actions.stream().map { it.templateText }.toList() var notification: Notification? = notification } private class DropDownActionLayout(layout: LayoutManager2) : FinalLayoutWrapper(layout) { val actions = ArrayList<LinkLabel<AnAction>>() private lateinit var myDropDownAction: MyDropDownAction override fun addLayoutComponent(comp: Component, constraints: Any?) { super.addLayoutComponent(comp, constraints) add(comp) } override fun addLayoutComponent(name: String?, comp: Component) { super.addLayoutComponent(name, comp) add(comp) } private fun add(component: Component) { if (component is MyDropDownAction) { myDropDownAction = component } else if (component is LinkLabel<*>) { @Suppress("UNCHECKED_CAST") actions.add(component as LinkLabel<AnAction>) } } override fun layoutContainer(parent: Container) { val width = parent.width myDropDownAction.isVisible = false for (action in actions) { action.isVisible = true } layout.layoutContainer(parent) val keepRightmost = myDropDownAction.collapseActionsDirection == Notification.CollapseActionsDirection.KEEP_RIGHTMOST val collapseStart = if (keepRightmost) 0 else actions.size - 1 val collapseDelta = if (keepRightmost) 1 else -1 var collapseIndex = collapseStart if (parent.preferredSize.width > width) { myDropDownAction.isVisible = true actions[collapseIndex].isVisible = false collapseIndex += collapseDelta actions[collapseIndex].isVisible = false collapseIndex += collapseDelta layout.layoutContainer(parent) while (parent.preferredSize.width > width && collapseIndex >= 0 && collapseIndex < actions.size) { actions[collapseIndex].isVisible = false collapseIndex += collapseDelta layout.layoutContainer(parent) } } } } private class ComponentEventHandler { private var myHoverComponent: NotificationComponent? = null private val myMouseHandler = object : MouseAdapter() { override fun mouseMoved(e: MouseEvent) { if (myHoverComponent == null) { val component = ComponentUtil.getParentOfType(NotificationComponent::class.java, e.component) if (component != null) { if (!component.isHover()) { component.setHover(true) } myHoverComponent = component } } } override fun mouseExited(e: MouseEvent) { if (myHoverComponent != null) { val component = myHoverComponent!! if (component.isHover()) { component.setHover(false) } myHoverComponent = null } } } fun add(component: Component) { addAll(component) { c -> c.addMouseListener(myMouseHandler) c.addMouseMotionListener(myMouseHandler) } } private fun addAll(component: Component, listener: (Component) -> Unit) { listener.invoke(component) if (component is JBOptionButton) { component.addContainerListener(object : ContainerAdapter() { override fun componentAdded(e: ContainerEvent) { addAll(e.child, listener) } }) } for (child in UIUtil.uiChildren(component)) { addAll(child, listener) } } } internal class ApplicationNotificationModel { private val myNotifications = ArrayList<Notification>() private val myProjectToModel = HashMap<Project, ProjectNotificationModel>() private val myLock = Object() internal fun registerAndGetInitNotifications(content: NotificationContent, notifications: MutableList<Notification>) { synchronized(myLock) { notifications.addAll(myNotifications) myNotifications.clear() val model = myProjectToModel.getOrPut(content.project) { ProjectNotificationModel() } model.registerAndGetInitNotifications(content, notifications) } } internal fun unregister(content: NotificationContent) { synchronized(myLock) { myProjectToModel.remove(content.project) } } fun addNotification(project: Project?, notification: Notification) { val runnables = ArrayList<Runnable>() synchronized(myLock) { if (project == null) { if (myProjectToModel.isEmpty()) { myNotifications.add(notification) } else { for ((_project, model) in myProjectToModel.entries) { model.addNotification(_project, notification, myNotifications, runnables) } } } else { val model = myProjectToModel.getOrPut(project) { Disposer.register(project) { synchronized(myLock) { myProjectToModel.remove(project) } } ProjectNotificationModel() } model.addNotification(project, notification, myNotifications, runnables) } } for (runnable in runnables) { runnable.run() } } fun getStateNotifications(project: Project): List<Notification> { synchronized(myLock) { val model = myProjectToModel[project] if (model != null) { return model.getStateNotifications() } } return emptyList() } fun getNotifications(project: Project?): List<Notification> { synchronized(myLock) { if (project == null) { return ArrayList(myNotifications) } val model = myProjectToModel[project] if (model == null) { return ArrayList(myNotifications) } return model.getNotifications(myNotifications) } } fun isEmptyContent(project: Project): Boolean { val model = myProjectToModel[project] return model == null || model.isEmptyContent() } fun expire(notification: Notification) { val runnables = ArrayList<Runnable>() synchronized(myLock) { myNotifications.remove(notification) for (model in myProjectToModel.values) { model.expire(notification, runnables) } } for (runnable in runnables) { runnable.run() } } fun expireAll() { val notifications = ArrayList<Notification>() val runnables = ArrayList<Runnable>() synchronized(myLock) { notifications.addAll(myNotifications) myNotifications.clear() for (model in myProjectToModel.values) { model.expireAll(notifications, runnables) } } for (runnable in runnables) { runnable.run() } for (notification in notifications) { notification.expire() } } fun clearAll(project: Project?) { synchronized(myLock) { myNotifications.clear() if (project != null) { myProjectToModel[project]?.clearAll(project) } } } } private class ProjectNotificationModel { private val myNotifications = ArrayList<Notification>() private var myContent: NotificationContent? = null fun registerAndGetInitNotifications(content: NotificationContent, notifications: MutableList<Notification>) { notifications.addAll(myNotifications) myNotifications.clear() myContent = content } fun addNotification(project: Project, notification: Notification, appNotifications: List<Notification>, runnables: MutableList<Runnable>) { if (myContent == null) { myNotifications.add(notification) val notifications = ArrayList(appNotifications) notifications.addAll(myNotifications) runnables.add(Runnable { EventLog.getLogModel(project).setStatusMessage(notification) val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(NotificationsToolWindowFactory.ID) if (toolWindow != null) { UIUtil.invokeLaterIfNeeded { toolWindow.setIcon(IdeNotificationArea.getActionCenterNotificationIcon(notifications)) } } }) } else { runnables.add(Runnable { UIUtil.invokeLaterIfNeeded { myContent!!.add(notification) } }) } } fun getStateNotifications(): List<Notification> { if (myContent == null) { return emptyList() } return myContent!!.getStateNotifications() } fun isEmptyContent(): Boolean { return myContent == null || myContent!!.isEmpty() } fun getNotifications(appNotifications: List<Notification>): List<Notification> { if (myContent == null) { val notifications = ArrayList(appNotifications) notifications.addAll(myNotifications) return notifications } return myContent!!.getNotifications() } fun expire(notification: Notification, runnables: MutableList<Runnable>) { myNotifications.remove(notification) if (myContent != null) { runnables.add(Runnable { UIUtil.invokeLaterIfNeeded { myContent!!.expire(notification) } }) } } fun expireAll(notifications: MutableList<Notification>, runnables: MutableList<Runnable>) { notifications.addAll(myNotifications) myNotifications.clear() if (myContent != null) { runnables.add(Runnable { UIUtil.invokeLaterIfNeeded { myContent!!.expire(null) } }) } } fun clearAll(project: Project) { myNotifications.clear() if (myContent == null) { UIUtil.invokeLaterIfNeeded { EventLog.getLogModel(project).setStatusMessage(null) project.closeAllBalloons() val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(NotificationsToolWindowFactory.ID) toolWindow?.setIcon(IdeNotificationArea.getActionCenterNotificationIcon(emptyList())) } } else { UIUtil.invokeLaterIfNeeded { myContent!!.clearAll() } } } } fun Project.closeAllBalloons() { val ideFrame = WindowManager.getInstance().getIdeFrame(this) val balloonLayout = ideFrame!!.balloonLayout as BalloonLayoutImpl balloonLayout.closeAll() } class ClearAllNotificationsAction : DumbAwareAction(IdeBundle.message("clear.all.notifications"), null, AllIcons.Actions.GC) { override fun update(e: AnActionEvent) { val project = e.project e.presentation.isEnabled = NotificationsToolWindowFactory.getNotifications(project).isNotEmpty() || (project != null && !NotificationsToolWindowFactory.myModel.isEmptyContent(project)) } override fun getActionUpdateThread() = ActionUpdateThread.EDT override fun actionPerformed(e: AnActionEvent) { NotificationsToolWindowFactory.clearAll(e.project) } }
apache-2.0
b2f91595eed6a28bba23db24902fd5eb
30.450359
148
0.688765
4.970132
false
false
false
false
mdaniel/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/XChildEntityImpl.kt
1
12752
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren import com.intellij.workspaceModel.storage.impl.extractOneToManyParent import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class XChildEntityImpl: XChildEntity, WorkspaceEntityBase() { companion object { internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(XParentEntity::class.java, XChildEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) internal val CHILDCHILD_CONNECTION_ID: ConnectionId = ConnectionId.create(XChildEntity::class.java, XChildChildEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) val connections = listOf<ConnectionId>( PARENTENTITY_CONNECTION_ID, CHILDCHILD_CONNECTION_ID, ) } @JvmField var _childProperty: String? = null override val childProperty: String get() = _childProperty!! @JvmField var _dataClass: DataClassX? = null override val dataClass: DataClassX? get() = _dataClass override val parentEntity: XParentEntity get() = snapshot.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this)!! override val childChild: List<XChildChildEntity> get() = snapshot.extractOneToManyChildren<XChildChildEntity>(CHILDCHILD_CONNECTION_ID, this)!!.toList() override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: XChildEntityData?): ModifiableWorkspaceEntityBase<XChildEntity>(), XChildEntity.Builder { constructor(): this(XChildEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity XChildEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isChildPropertyInitialized()) { error("Field XChildEntity#childProperty should be initialized") } if (!getEntityData().isEntitySourceInitialized()) { error("Field XChildEntity#entitySource should be initialized") } if (_diff != null) { if (_diff.extractOneToManyParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) { error("Field XChildEntity#parentEntity should be initialized") } } else { if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) { error("Field XChildEntity#parentEntity should be initialized") } } // Check initialization for collection with ref type if (_diff != null) { if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDCHILD_CONNECTION_ID, this) == null) { error("Field XChildEntity#childChild should be initialized") } } else { if (this.entityLinks[EntityLink(true, CHILDCHILD_CONNECTION_ID)] == null) { error("Field XChildEntity#childChild should be initialized") } } } override fun connectionIdList(): List<ConnectionId> { return connections } override var childProperty: String get() = getEntityData().childProperty set(value) { checkModificationAllowed() getEntityData().childProperty = value changedProperty.add("childProperty") } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var dataClass: DataClassX? get() = getEntityData().dataClass set(value) { checkModificationAllowed() getEntityData().dataClass = value changedProperty.add("dataClass") } override var parentEntity: XParentEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as XParentEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as XParentEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value } changedProperty.add("parentEntity") } // List of non-abstract referenced types var _childChild: List<XChildChildEntity>? = emptyList() override var childChild: List<XChildChildEntity> get() { // Getter of the list of non-abstract referenced types val _diff = diff return if (_diff != null) { _diff.extractOneToManyChildren<XChildChildEntity>(CHILDCHILD_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, CHILDCHILD_CONNECTION_ID)] as? List<XChildChildEntity> ?: emptyList()) } else { this.entityLinks[EntityLink(true, CHILDCHILD_CONNECTION_ID)] as? List<XChildChildEntity> ?: emptyList() } } set(value) { // Setter of the list of non-abstract referenced types checkModificationAllowed() val _diff = diff if (_diff != null) { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) { _diff.addEntity(item_value) } } _diff.updateOneToManyChildrenOfParent(CHILDCHILD_CONNECTION_ID, this, value) } else { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*>) { item_value.entityLinks[EntityLink(false, CHILDCHILD_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable } this.entityLinks[EntityLink(true, CHILDCHILD_CONNECTION_ID)] = value } changedProperty.add("childChild") } override fun getEntityData(): XChildEntityData = result ?: super.getEntityData() as XChildEntityData override fun getEntityClass(): Class<XChildEntity> = XChildEntity::class.java } } class XChildEntityData : WorkspaceEntityData<XChildEntity>() { lateinit var childProperty: String var dataClass: DataClassX? = null fun isChildPropertyInitialized(): Boolean = ::childProperty.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<XChildEntity> { val modifiable = XChildEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): XChildEntity { val entity = XChildEntityImpl() entity._childProperty = childProperty entity._dataClass = dataClass entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return XChildEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as XChildEntityData if (this.childProperty != other.childProperty) return false if (this.entitySource != other.entitySource) return false if (this.dataClass != other.dataClass) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as XChildEntityData if (this.childProperty != other.childProperty) return false if (this.dataClass != other.dataClass) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + childProperty.hashCode() result = 31 * result + dataClass.hashCode() return result } }
apache-2.0
50e0d67492416c38ff55c49cfeb18cbc
42.975862
220
0.605082
6.020774
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/hsl/HSLLookup.kt
1
6264
/* * HSLLookup.kt * * Copyright 2019 Google * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.transit.hsl import au.id.micolous.metrodroid.multi.Localizer import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.time.MetroTimeZone import au.id.micolous.metrodroid.transit.TransitCurrency import au.id.micolous.metrodroid.transit.en1545.En1545LookupUnknown import au.id.micolous.metrodroid.transit.en1545.En1545Parsed import au.id.micolous.metrodroid.util.StationTableReader object HSLLookup : En1545LookupUnknown() { override fun parseCurrency(price: Int) = TransitCurrency.EUR(price) override val timeZone: MetroTimeZone get() = MetroTimeZone.HELSINKI fun contractWalttiZoneName(prefix: String) = "${prefix}WalttiZone" fun contractWalttiRegionName(prefix: String) = "${prefix}WalttiRegion" fun contractAreaTypeName(prefix: String) = "${prefix}AreaType" fun contractAreaName(prefix: String) = "${prefix}Area" fun languageCode(input: Int?) = when (input) { 0 -> Localizer.localizeString(R.string.hsl_finnish) 1 -> Localizer.localizeString(R.string.hsl_swedish) 2 -> Localizer.localizeString(R.string.hsl_english) else -> Localizer.localizeString(R.string.unknown_format, input.toString()) } private val areaMap = mapOf( Pair(0, 1) to R.string.hsl_region_helsinki, Pair(0, 2) to R.string.hsl_region_espoo, Pair(0, 4) to R.string.hsl_region_vantaa, Pair(0, 5) to R.string.hsl_region_seutu, Pair(0, 6) to R.string.hsl_region_kirkkonummi_siuntio, Pair(0, 7) to R.string.hsl_region_vihti, Pair(0, 8) to R.string.hsl_region_nurmijarvi, Pair(0, 9) to R.string.hsl_region_kerava_sipoo_tuusula, Pair(0, 10) to R.string.hsl_region_sipoo, Pair(0, 14) to R.string.hsl_region_lahiseutu_2, Pair(0, 15) to R.string.hsl_region_lahiseutu_3, Pair(1, 1) to R.string.hsl_transport_bussi, Pair(1, 2) to R.string.hsl_transport_bussi_2, Pair(1, 3) to R.string.hsl_transport_bussi_3, Pair(1, 4) to R.string.hsl_transport_bussi_4, Pair(1, 5) to R.string.hsl_transport_raitiovaunu, Pair(1, 6) to R.string.hsl_transport_metro, Pair(1, 7) to R.string.hsl_transport_juna, Pair(1, 8) to R.string.hsl_transport_lautta, Pair(1, 9) to R.string.hsl_transport_u_linja ) val walttiValiditySplit = listOf(Pair(0, 0)) + (1..10).map { Pair(it, it) } + (1..10).flatMap { start -> ((start+1)..10).map { Pair(start, it) } } const val WALTTI_OULU = 229 const val WALTTI_LAHTI = 223 const val CITY_UL_TAMPERE = 1 private val lahtiZones = listOf( "A", "B", "C", "D", "E", "F1", "F2", "G", "H", "I" ) private val ouluZones = listOf( "City A", "A", "B", "C", "D", "E", "F", "G", "H", "I" ) private fun mapWalttiZone(region: Int, id: Int): String = when (region) { WALTTI_OULU -> lahtiZones[id - 1] WALTTI_LAHTI -> ouluZones[id - 1] else -> String(charArrayOf('A' + id - 1)) } private fun walttiNameRegion(id: Int): String? = StationTableReader.getOperatorName("waltti_region", id, true)?.unformatted fun getArea(parsed: En1545Parsed, prefix: String, isValidity: Boolean, walttiRegion: Int? = null, ultralightCity: Int? = null): String? { if (parsed.getInt(contractAreaName(prefix)) == null && parsed.getInt(contractWalttiZoneName(prefix)) != null) { val region = walttiRegion ?: parsed.getIntOrZero(contractWalttiRegionName(prefix)) val regionName = walttiNameRegion(region) ?: region.toString() val zone = parsed.getIntOrZero(contractWalttiZoneName(prefix)) if (zone == 0) { return null } if (!isValidity && zone in 1..10) { return Localizer.localizeString(R.string.waltti_city_zone, regionName, mapWalttiZone(region, zone)) } val (start, end) = walttiValiditySplit[zone] return Localizer.localizeString(R.string.waltti_city_zones, regionName, mapWalttiZone(region, start) + " - " + mapWalttiZone(region, end)) } val type = parsed.getIntOrZero(contractAreaTypeName(prefix)) val value = parsed.getIntOrZero(contractAreaName(prefix)) if (type in 0..1 && value == 0) { return null } if (ultralightCity == CITY_UL_TAMPERE && type == 0) { val from = value % 6 if (isValidity) { val to = value / 6 val num = to - from + 1 val zones = String((from..to).map { 'A' + it }.toCharArray()) return Localizer.localizePlural(R.plurals.hsl_zones, num, zones, num) } else { return Localizer.localizeString(R.string.hsl_zone_station, String(charArrayOf('A' + from))) } } if (type == 2) { val to = value and 7 if (isValidity) { val from = value shr 3 val num = to - from + 1 val zones = String((from..to).map { 'A' + it }.toCharArray()) return Localizer.localizePlural(R.plurals.hsl_zones, num, zones, num) } else { return Localizer.localizeString(R.string.hsl_zone_station, String(charArrayOf('A' + to))) } } return areaMap[Pair(type, value)]?.let { Localizer.localizeString(it) } ?: Localizer.localizeString(R.string.unknown_format, "$type/$value") } }
gpl-3.0
5ebc706053bc058213515312d96bc6bf
43.112676
150
0.625479
3.462687
false
false
false
false
hzsweers/CatchUp
services/github/src/main/kotlin/io/sweers/catchup/service/github/GitHubService.kt
1
7736
/* * Copyright (C) 2019. Zac Sweers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.sweers.catchup.service.github import android.graphics.Color import com.apollographql.apollo3.ApolloClient import com.apollographql.apollo3.api.ApolloRequest import com.apollographql.apollo3.api.Query import com.apollographql.apollo3.cache.http.HttpFetchPolicy.NetworkOnly import com.apollographql.apollo3.cache.http.httpFetchPolicy import com.apollographql.apollo3.exception.ApolloException import com.squareup.anvil.annotations.ContributesMultibinding import com.squareup.anvil.annotations.ContributesTo import dagger.Binds import dagger.Lazy import dagger.Module import dagger.Provides import dagger.Reusable import dagger.multibindings.IntoMap import dev.zacsweers.catchup.appconfig.AppConfig import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.core.Single import io.sweers.catchup.gemoji.EmojiMarkdownConverter import io.sweers.catchup.gemoji.replaceMarkdownEmojisIn import io.sweers.catchup.libraries.retrofitconverters.DecodingConverter import io.sweers.catchup.libraries.retrofitconverters.delegatingCallFactory import io.sweers.catchup.service.api.CatchUpItem import io.sweers.catchup.service.api.DataRequest import io.sweers.catchup.service.api.DataResult import io.sweers.catchup.service.api.Mark import io.sweers.catchup.service.api.Service import io.sweers.catchup.service.api.ServiceIndex import io.sweers.catchup.service.api.ServiceKey import io.sweers.catchup.service.api.ServiceMeta import io.sweers.catchup.service.api.ServiceMetaIndex import io.sweers.catchup.service.api.ServiceMetaKey import io.sweers.catchup.service.api.TextService import io.sweers.catchup.service.github.GitHubApi.Language.All import io.sweers.catchup.service.github.GitHubApi.Since.DAILY import io.sweers.catchup.service.github.model.SearchQuery import io.sweers.catchup.service.github.model.TrendingTimespan import io.sweers.catchup.service.github.type.LanguageOrder import io.sweers.catchup.service.github.type.LanguageOrderField import io.sweers.catchup.service.github.type.OrderDirection import io.sweers.catchup.util.e import io.sweers.catchup.util.nullIfBlank import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.rx3.rxSingle import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory import javax.inject.Inject import javax.inject.Qualifier @Qualifier private annotation class InternalApi private const val SERVICE_KEY = "github" @ServiceKey(SERVICE_KEY) @ContributesMultibinding(ServiceIndex::class, boundType = Service::class) class GitHubService @Inject constructor( @InternalApi private val serviceMeta: ServiceMeta, private val apolloClient: Lazy<ApolloClient>, private val emojiMarkdownConverter: Lazy<EmojiMarkdownConverter>, private val gitHubApi: Lazy<GitHubApi> ) : TextService { override fun meta() = serviceMeta override fun fetchPage(request: DataRequest): Single<DataResult> { return fetchByScraping() .onErrorResumeNext { t: Throwable -> e(t) { "GitHub trending scraping failed." } fetchByQuery(request) } } private fun fetchByScraping(): Single<DataResult> { return gitHubApi .get() .getTrending(language = All, since = DAILY) .flattenAsObservable { it } .map { with(it) { CatchUpItem( id = "$author/$repoName".hashCode().toLong(), title = "$author / $repoName", description = description, timestamp = null, score = "★" to stars, tag = language, itemClickUrl = url, mark = starsToday?.toString()?.let { Mark( text = "+$it", icon = R.drawable.ic_star_black_24dp, iconTintColor = languageColor?.let(Color::parseColor) ) } ) } } .toList() .map { DataResult(it, null) } } private fun fetchByQuery(request: DataRequest): Single<DataResult> { val query = SearchQuery( createdSince = TrendingTimespan.WEEK.createdSince(), minStars = 50 ) .toString() val searchQuery = rxSingle(Dispatchers.IO) { apolloClient.get() .query( GitHubSearchQuery( queryString = query, firstCount = 50, order = LanguageOrder( direction = OrderDirection.DESC, field_ = LanguageOrderField.SIZE ), after = request.pageId.nullIfBlank() ).toApolloRequest() .newBuilder() .httpFetchPolicy(NetworkOnly) .build() ) } return searchQuery .doOnSuccess { if (it.hasErrors()) { throw ApolloException(it.errors.toString()) } } .map { it.data!! } .flatMap { (search) -> Observable.fromIterable(search.nodes?.mapNotNull { it?.onRepository }.orEmpty()) .map { with(it) { val description = description ?.let { " — ${emojiMarkdownConverter.get().replaceMarkdownEmojisIn(it)}" } .orEmpty() CatchUpItem( id = id.hashCode().toLong(), title = "$name$description", score = "★" to stargazers.totalCount, timestamp = createdAt, author = owner.login, tag = languages?.nodes?.firstOrNull()?.name, source = licenseInfo?.name, itemClickUrl = url.toString() ) } } .toList() .map { if (search.pageInfo.hasNextPage) { DataResult(it, search.pageInfo.endCursor) } else { DataResult(it, null) } } } } } @ContributesTo(ServiceMetaIndex::class) @Module abstract class GitHubMetaModule { @IntoMap @ServiceMetaKey(SERVICE_KEY) @Binds internal abstract fun @receiver:InternalApi ServiceMeta.githubServiceMeta(): ServiceMeta companion object { @InternalApi @Provides @Reusable internal fun provideGitHubServiceMeta(): ServiceMeta = ServiceMeta( SERVICE_KEY, R.string.github, R.color.githubAccent, R.drawable.logo_github, firstPageKey = "", enabled = BuildConfig.GITHUB_DEVELOPER_TOKEN.run { !isNullOrEmpty() && !equals("null") } ) } } @ContributesTo(ServiceIndex::class) @Module(includes = [GitHubMetaModule::class]) object GitHubModule { @Provides internal fun provideGitHubService( client: Lazy<OkHttpClient>, rxJavaCallAdapterFactory: RxJava3CallAdapterFactory, appConfig: AppConfig ): GitHubApi { return Retrofit.Builder().baseUrl(GitHubApi.ENDPOINT) .delegatingCallFactory(client) .addCallAdapterFactory(rxJavaCallAdapterFactory) .addConverterFactory(DecodingConverter.newFactory(GitHubTrendingParser::parse)) .validateEagerly(appConfig.isDebug) .build() .create(GitHubApi::class.java) } } private fun <D : Query.Data> Query<D>.toApolloRequest(): ApolloRequest<D> { return ApolloRequest.Builder(this).build() }
apache-2.0
2dc44d9f64d6af2f76fb577a3fc55f78
32.175966
94
0.687322
4.38706
false
false
false
false
Turbo87/intellij-emberjs
src/test/kotlin/com/emberjs/navigation/EmberTestFinderTest.kt
1
3095
package com.emberjs.navigation import com.emberjs.EmberTestFixtures.FIXTURES_PATH import com.emberjs.index.EmberNameIndex import com.emberjs.resolver.EmberName import com.emberjs.utils.use import com.intellij.psi.PsiManager import com.intellij.testFramework.fixtures.BasePlatformTestCase import com.intellij.util.indexing.FileBasedIndex import org.assertj.core.api.Assertions import org.assertj.core.api.SoftAssertions import org.junit.Test class EmberTestFinderTest : BasePlatformTestCase() { val finder = EmberTestFinder() @Test fun testCratesIo() = doTest("crates.io", mapOf( "app/helpers/format-email.js" to listOf("tests/unit/helpers/format-email-test.js"), "app/helpers/format-num.js" to listOf("tests/unit/helpers/format-num-test.js"), "app/mixins/pagination.js" to listOf("tests/unit/mixins/pagination-test.js") )) @Test fun testExample() = doTest("example", mapOf( "app/pet/model.js" to listOf("tests/unit/pet/model-test.js"), "app/pet/serializer.js" to listOf("tests/unit/pet/serializer-test.js"), "app/session/service.js" to listOf("tests/unit/session/service-test.js"), "app/user/adapter.js" to listOf("tests/unit/user/adapter-test.js"), "app/user/model.js" to listOf("tests/unit/user/model-test.js") )) @Test fun testAptible() = doTest("dashboard.aptible.com", mapOf( "app/claim/route.js" to listOf("tests/unit/claim/route-test.js"), "app/components/object-select/component.js" to listOf("tests/integration/components/object-select-test.js"), "app/components/login-box/component.js" to listOf("tests/unit/components/login-box-test.js"), "app/helpers/eq.js" to listOf("tests/integration/helpers/eq-test.js"), "app/index/route.js" to listOf("tests/unit/routes/index-test.js"), "app/databases/index/route.js" to listOf("tests/unit/routes/databases/index-test.js") )) override fun getTestDataPath() = FIXTURES_PATH.toString() private fun doTest(fixtureName: String, tests: Map<String, List<String>>) { // Load fixture files into the project val root = myFixture.copyDirectoryToProject(fixtureName, "/") val project = myFixture.project val psiManager = PsiManager.getInstance(project) SoftAssertions().use { for ((path, relatedTests) in tests) { val file = root.findFileByRelativePath(path)!! val relatedFiles = relatedTests.map { root.findFileByRelativePath(it)!! } assertThat(finder.findTestsForClass(psiManager.findFile(file)!!)) .describedAs(path) .containsOnly(*relatedFiles.map { psiManager.findFile(it)!! }.toTypedArray()) relatedFiles.forEach { assertThat(finder.findClassesForTest(psiManager.findFile(it)!!)) .describedAs(path) .containsOnly(psiManager.findFile(file)!!) } } } } }
apache-2.0
113145d50648072767376ebd8442bb8f
44.514706
120
0.653635
4.051047
false
true
false
false
AsamK/TextSecure
app/src/androidTest/java/org/thoughtcrime/securesms/database/MmsHelper.kt
1
1730
package org.thoughtcrime.securesms.database import org.thoughtcrime.securesms.database.model.StoryType import org.thoughtcrime.securesms.database.model.databaseprotos.GiftBadge import org.thoughtcrime.securesms.mms.IncomingMediaMessage import org.thoughtcrime.securesms.mms.OutgoingMediaMessage import org.thoughtcrime.securesms.recipients.Recipient import java.util.Optional /** * Helper methods for inserting an MMS message into the MMS table. */ object MmsHelper { fun insert( recipient: Recipient = Recipient.UNKNOWN, body: String = "body", sentTimeMillis: Long = System.currentTimeMillis(), subscriptionId: Int = -1, expiresIn: Long = 0, viewOnce: Boolean = false, distributionType: Int = ThreadDatabase.DistributionTypes.DEFAULT, threadId: Long = 1, storyType: StoryType = StoryType.NONE, giftBadge: GiftBadge? = null ): Long { val message = OutgoingMediaMessage( recipient, body, emptyList(), sentTimeMillis, subscriptionId, expiresIn, viewOnce, distributionType, storyType, null, false, null, emptyList(), emptyList(), emptyList(), emptySet(), emptySet(), giftBadge ) return insert( message = message, threadId = threadId ) } fun insert( message: OutgoingMediaMessage, threadId: Long ): Long { return SignalDatabase.mms.insertMessageOutbox(message, threadId, false, GroupReceiptDatabase.STATUS_UNKNOWN, null) } fun insert( message: IncomingMediaMessage, threadId: Long ): Optional<MessageDatabase.InsertResult> { return SignalDatabase.mms.insertSecureDecryptedMessageInbox(message, threadId) } }
gpl-3.0
70f5bf935a3d0bdbef4dc9da7e017fc2
24.820896
118
0.700578
4.493506
false
false
false
false
AsamK/TextSecure
app/src/test/java/org/thoughtcrime/securesms/video/exo/ExoPlayerPoolTest.kt
2
2587
package org.thoughtcrime.securesms.video.exo import com.google.android.exoplayer2.ExoPlayer import org.junit.Assert.assertNotNull import org.junit.Assert.assertTrue import org.junit.Assert.fail import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.mockito.Mockito.mock @RunWith(JUnit4::class) class ExoPlayerPoolTest { @Test fun `Given an empty pool, when I require a player, then I expect a player`() { // GIVEN val testSubject = createTestSubject(1, 1) // WHEN val player = testSubject.require("") // THEN assertNotNull(player) } @Test(expected = IllegalStateException::class) fun `Given a pool without available players, when I require a player, then I expect an exception`() { // GIVEN val testSubject = createTestSubject(1, 0) // WHEN testSubject.require("") // THEN fail("Expected an IllegalStateException") } @Test fun `Given a pool that allows 10 unreserved items, when I ask for 20, then I expect 10 items and 10 nulls`() { // GIVEN val testSubject = createTestSubject(0, 10) // WHEN val players = (1..10).map { testSubject.get("") } val nulls = (1..10).map { testSubject.get("") } // THEN assertTrue(players.all { it != null }) assertTrue(nulls.all { it == null }) } @Test fun `Given a pool that allows 10 items and has all items checked out, when I return then check them all out again, then I expect 10 non null players`() { // GIVEN val testSubject = createTestSubject(0, 10) val players = (1..10).map { testSubject.get("") } // WHEN players.filterNotNull().forEach { testSubject.pool(it) } val morePlayers = (1..10).map { testSubject.get("") } assertTrue(morePlayers.all { it != null }) } @Test(expected = IllegalArgumentException::class) fun `Given an ExoPlayer not in the pool, when I pool it, then I expect an IllegalArgumentException`() { // GIVEN val player = mock(ExoPlayer::class.java) val pool = createTestSubject(1, 10) // WHEN pool.pool(player) // THEN fail("Expected an IllegalArgumentException to be thrown") } private fun createTestSubject( maximumReservedPlayers: Int, maximumSimultaneousPlayback: Int ): ExoPlayerPool<ExoPlayer> { return object : ExoPlayerPool<ExoPlayer>(maximumReservedPlayers) { override fun createPlayer(): ExoPlayer { return mock(ExoPlayer::class.java) } override fun getMaxSimultaneousPlayback(): Int { return maximumSimultaneousPlayback } } } }
gpl-3.0
96126956a5f07df88dde97c0e3209867
26.817204
155
0.679938
4.080442
false
true
false
false
Philip-Trettner/GlmKt
GlmKt/src/glm/vec/Double/MutableDoubleVec4.kt
1
52861
package glm data class MutableDoubleVec4(var x: Double, var y: Double, var z: Double, var w: Double) { // Initializes each element by evaluating init from 0 until 3 constructor(init: (Int) -> Double) : this(init(0), init(1), init(2), init(3)) operator fun get(idx: Int): Double = when (idx) { 0 -> x 1 -> y 2 -> z 3 -> w else -> throw IndexOutOfBoundsException("index $idx is out of bounds") } operator fun set(idx: Int, value: Double) = when (idx) { 0 -> x = value 1 -> y = value 2 -> z = value 3 -> w = value else -> throw IndexOutOfBoundsException("index $idx is out of bounds") } // Operators operator fun inc(): MutableDoubleVec4 = MutableDoubleVec4(x.inc(), y.inc(), z.inc(), w.inc()) operator fun dec(): MutableDoubleVec4 = MutableDoubleVec4(x.dec(), y.dec(), z.dec(), w.dec()) operator fun unaryPlus(): MutableDoubleVec4 = MutableDoubleVec4(+x, +y, +z, +w) operator fun unaryMinus(): MutableDoubleVec4 = MutableDoubleVec4(-x, -y, -z, -w) operator fun plus(rhs: MutableDoubleVec4): MutableDoubleVec4 = MutableDoubleVec4(x + rhs.x, y + rhs.y, z + rhs.z, w + rhs.w) operator fun minus(rhs: MutableDoubleVec4): MutableDoubleVec4 = MutableDoubleVec4(x - rhs.x, y - rhs.y, z - rhs.z, w - rhs.w) operator fun times(rhs: MutableDoubleVec4): MutableDoubleVec4 = MutableDoubleVec4(x * rhs.x, y * rhs.y, z * rhs.z, w * rhs.w) operator fun div(rhs: MutableDoubleVec4): MutableDoubleVec4 = MutableDoubleVec4(x / rhs.x, y / rhs.y, z / rhs.z, w / rhs.w) operator fun rem(rhs: MutableDoubleVec4): MutableDoubleVec4 = MutableDoubleVec4(x % rhs.x, y % rhs.y, z % rhs.z, w % rhs.w) operator fun plus(rhs: Double): MutableDoubleVec4 = MutableDoubleVec4(x + rhs, y + rhs, z + rhs, w + rhs) operator fun minus(rhs: Double): MutableDoubleVec4 = MutableDoubleVec4(x - rhs, y - rhs, z - rhs, w - rhs) operator fun times(rhs: Double): MutableDoubleVec4 = MutableDoubleVec4(x * rhs, y * rhs, z * rhs, w * rhs) operator fun div(rhs: Double): MutableDoubleVec4 = MutableDoubleVec4(x / rhs, y / rhs, z / rhs, w / rhs) operator fun rem(rhs: Double): MutableDoubleVec4 = MutableDoubleVec4(x % rhs, y % rhs, z % rhs, w % rhs) inline fun map(func: (Double) -> Double): MutableDoubleVec4 = MutableDoubleVec4(func(x), func(y), func(z), func(w)) fun toList(): List<Double> = listOf(x, y, z, w) // Predefined vector constants companion object Constants { val zero: MutableDoubleVec4 get() = MutableDoubleVec4(0.0, 0.0, 0.0, 0.0) val ones: MutableDoubleVec4 get() = MutableDoubleVec4(1.0, 1.0, 1.0, 1.0) val unitX: MutableDoubleVec4 get() = MutableDoubleVec4(1.0, 0.0, 0.0, 0.0) val unitY: MutableDoubleVec4 get() = MutableDoubleVec4(0.0, 1.0, 0.0, 0.0) val unitZ: MutableDoubleVec4 get() = MutableDoubleVec4(0.0, 0.0, 1.0, 0.0) val unitW: MutableDoubleVec4 get() = MutableDoubleVec4(0.0, 0.0, 0.0, 1.0) } // Conversions to Float fun toVec(): Vec4 = Vec4(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat()) inline fun toVec(conv: (Double) -> Float): Vec4 = Vec4(conv(x), conv(y), conv(z), conv(w)) fun toVec2(): Vec2 = Vec2(x.toFloat(), y.toFloat()) inline fun toVec2(conv: (Double) -> Float): Vec2 = Vec2(conv(x), conv(y)) fun toVec3(): Vec3 = Vec3(x.toFloat(), y.toFloat(), z.toFloat()) inline fun toVec3(conv: (Double) -> Float): Vec3 = Vec3(conv(x), conv(y), conv(z)) fun toVec4(): Vec4 = Vec4(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat()) inline fun toVec4(conv: (Double) -> Float): Vec4 = Vec4(conv(x), conv(y), conv(z), conv(w)) // Conversions to Float fun toMutableVec(): MutableVec4 = MutableVec4(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat()) inline fun toMutableVec(conv: (Double) -> Float): MutableVec4 = MutableVec4(conv(x), conv(y), conv(z), conv(w)) fun toMutableVec2(): MutableVec2 = MutableVec2(x.toFloat(), y.toFloat()) inline fun toMutableVec2(conv: (Double) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y)) fun toMutableVec3(): MutableVec3 = MutableVec3(x.toFloat(), y.toFloat(), z.toFloat()) inline fun toMutableVec3(conv: (Double) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), conv(z)) fun toMutableVec4(): MutableVec4 = MutableVec4(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat()) inline fun toMutableVec4(conv: (Double) -> Float): MutableVec4 = MutableVec4(conv(x), conv(y), conv(z), conv(w)) // Conversions to Double fun toDoubleVec(): DoubleVec4 = DoubleVec4(x, y, z, w) inline fun toDoubleVec(conv: (Double) -> Double): DoubleVec4 = DoubleVec4(conv(x), conv(y), conv(z), conv(w)) fun toDoubleVec2(): DoubleVec2 = DoubleVec2(x, y) inline fun toDoubleVec2(conv: (Double) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y)) fun toDoubleVec3(): DoubleVec3 = DoubleVec3(x, y, z) inline fun toDoubleVec3(conv: (Double) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), conv(z)) fun toDoubleVec4(): DoubleVec4 = DoubleVec4(x, y, z, w) inline fun toDoubleVec4(conv: (Double) -> Double): DoubleVec4 = DoubleVec4(conv(x), conv(y), conv(z), conv(w)) // Conversions to Double fun toMutableDoubleVec(): MutableDoubleVec4 = MutableDoubleVec4(x, y, z, w) inline fun toMutableDoubleVec(conv: (Double) -> Double): MutableDoubleVec4 = MutableDoubleVec4(conv(x), conv(y), conv(z), conv(w)) fun toMutableDoubleVec2(): MutableDoubleVec2 = MutableDoubleVec2(x, y) inline fun toMutableDoubleVec2(conv: (Double) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y)) fun toMutableDoubleVec3(): MutableDoubleVec3 = MutableDoubleVec3(x, y, z) inline fun toMutableDoubleVec3(conv: (Double) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), conv(z)) fun toMutableDoubleVec4(): MutableDoubleVec4 = MutableDoubleVec4(x, y, z, w) inline fun toMutableDoubleVec4(conv: (Double) -> Double): MutableDoubleVec4 = MutableDoubleVec4(conv(x), conv(y), conv(z), conv(w)) // Conversions to Int fun toIntVec(): IntVec4 = IntVec4(x.toInt(), y.toInt(), z.toInt(), w.toInt()) inline fun toIntVec(conv: (Double) -> Int): IntVec4 = IntVec4(conv(x), conv(y), conv(z), conv(w)) fun toIntVec2(): IntVec2 = IntVec2(x.toInt(), y.toInt()) inline fun toIntVec2(conv: (Double) -> Int): IntVec2 = IntVec2(conv(x), conv(y)) fun toIntVec3(): IntVec3 = IntVec3(x.toInt(), y.toInt(), z.toInt()) inline fun toIntVec3(conv: (Double) -> Int): IntVec3 = IntVec3(conv(x), conv(y), conv(z)) fun toIntVec4(): IntVec4 = IntVec4(x.toInt(), y.toInt(), z.toInt(), w.toInt()) inline fun toIntVec4(conv: (Double) -> Int): IntVec4 = IntVec4(conv(x), conv(y), conv(z), conv(w)) // Conversions to Int fun toMutableIntVec(): MutableIntVec4 = MutableIntVec4(x.toInt(), y.toInt(), z.toInt(), w.toInt()) inline fun toMutableIntVec(conv: (Double) -> Int): MutableIntVec4 = MutableIntVec4(conv(x), conv(y), conv(z), conv(w)) fun toMutableIntVec2(): MutableIntVec2 = MutableIntVec2(x.toInt(), y.toInt()) inline fun toMutableIntVec2(conv: (Double) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y)) fun toMutableIntVec3(): MutableIntVec3 = MutableIntVec3(x.toInt(), y.toInt(), z.toInt()) inline fun toMutableIntVec3(conv: (Double) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), conv(z)) fun toMutableIntVec4(): MutableIntVec4 = MutableIntVec4(x.toInt(), y.toInt(), z.toInt(), w.toInt()) inline fun toMutableIntVec4(conv: (Double) -> Int): MutableIntVec4 = MutableIntVec4(conv(x), conv(y), conv(z), conv(w)) // Conversions to Long fun toLongVec(): LongVec4 = LongVec4(x.toLong(), y.toLong(), z.toLong(), w.toLong()) inline fun toLongVec(conv: (Double) -> Long): LongVec4 = LongVec4(conv(x), conv(y), conv(z), conv(w)) fun toLongVec2(): LongVec2 = LongVec2(x.toLong(), y.toLong()) inline fun toLongVec2(conv: (Double) -> Long): LongVec2 = LongVec2(conv(x), conv(y)) fun toLongVec3(): LongVec3 = LongVec3(x.toLong(), y.toLong(), z.toLong()) inline fun toLongVec3(conv: (Double) -> Long): LongVec3 = LongVec3(conv(x), conv(y), conv(z)) fun toLongVec4(): LongVec4 = LongVec4(x.toLong(), y.toLong(), z.toLong(), w.toLong()) inline fun toLongVec4(conv: (Double) -> Long): LongVec4 = LongVec4(conv(x), conv(y), conv(z), conv(w)) // Conversions to Long fun toMutableLongVec(): MutableLongVec4 = MutableLongVec4(x.toLong(), y.toLong(), z.toLong(), w.toLong()) inline fun toMutableLongVec(conv: (Double) -> Long): MutableLongVec4 = MutableLongVec4(conv(x), conv(y), conv(z), conv(w)) fun toMutableLongVec2(): MutableLongVec2 = MutableLongVec2(x.toLong(), y.toLong()) inline fun toMutableLongVec2(conv: (Double) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y)) fun toMutableLongVec3(): MutableLongVec3 = MutableLongVec3(x.toLong(), y.toLong(), z.toLong()) inline fun toMutableLongVec3(conv: (Double) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), conv(z)) fun toMutableLongVec4(): MutableLongVec4 = MutableLongVec4(x.toLong(), y.toLong(), z.toLong(), w.toLong()) inline fun toMutableLongVec4(conv: (Double) -> Long): MutableLongVec4 = MutableLongVec4(conv(x), conv(y), conv(z), conv(w)) // Conversions to Short fun toShortVec(): ShortVec4 = ShortVec4(x.toShort(), y.toShort(), z.toShort(), w.toShort()) inline fun toShortVec(conv: (Double) -> Short): ShortVec4 = ShortVec4(conv(x), conv(y), conv(z), conv(w)) fun toShortVec2(): ShortVec2 = ShortVec2(x.toShort(), y.toShort()) inline fun toShortVec2(conv: (Double) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y)) fun toShortVec3(): ShortVec3 = ShortVec3(x.toShort(), y.toShort(), z.toShort()) inline fun toShortVec3(conv: (Double) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), conv(z)) fun toShortVec4(): ShortVec4 = ShortVec4(x.toShort(), y.toShort(), z.toShort(), w.toShort()) inline fun toShortVec4(conv: (Double) -> Short): ShortVec4 = ShortVec4(conv(x), conv(y), conv(z), conv(w)) // Conversions to Short fun toMutableShortVec(): MutableShortVec4 = MutableShortVec4(x.toShort(), y.toShort(), z.toShort(), w.toShort()) inline fun toMutableShortVec(conv: (Double) -> Short): MutableShortVec4 = MutableShortVec4(conv(x), conv(y), conv(z), conv(w)) fun toMutableShortVec2(): MutableShortVec2 = MutableShortVec2(x.toShort(), y.toShort()) inline fun toMutableShortVec2(conv: (Double) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y)) fun toMutableShortVec3(): MutableShortVec3 = MutableShortVec3(x.toShort(), y.toShort(), z.toShort()) inline fun toMutableShortVec3(conv: (Double) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), conv(z)) fun toMutableShortVec4(): MutableShortVec4 = MutableShortVec4(x.toShort(), y.toShort(), z.toShort(), w.toShort()) inline fun toMutableShortVec4(conv: (Double) -> Short): MutableShortVec4 = MutableShortVec4(conv(x), conv(y), conv(z), conv(w)) // Conversions to Byte fun toByteVec(): ByteVec4 = ByteVec4(x.toByte(), y.toByte(), z.toByte(), w.toByte()) inline fun toByteVec(conv: (Double) -> Byte): ByteVec4 = ByteVec4(conv(x), conv(y), conv(z), conv(w)) fun toByteVec2(): ByteVec2 = ByteVec2(x.toByte(), y.toByte()) inline fun toByteVec2(conv: (Double) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y)) fun toByteVec3(): ByteVec3 = ByteVec3(x.toByte(), y.toByte(), z.toByte()) inline fun toByteVec3(conv: (Double) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), conv(z)) fun toByteVec4(): ByteVec4 = ByteVec4(x.toByte(), y.toByte(), z.toByte(), w.toByte()) inline fun toByteVec4(conv: (Double) -> Byte): ByteVec4 = ByteVec4(conv(x), conv(y), conv(z), conv(w)) // Conversions to Byte fun toMutableByteVec(): MutableByteVec4 = MutableByteVec4(x.toByte(), y.toByte(), z.toByte(), w.toByte()) inline fun toMutableByteVec(conv: (Double) -> Byte): MutableByteVec4 = MutableByteVec4(conv(x), conv(y), conv(z), conv(w)) fun toMutableByteVec2(): MutableByteVec2 = MutableByteVec2(x.toByte(), y.toByte()) inline fun toMutableByteVec2(conv: (Double) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y)) fun toMutableByteVec3(): MutableByteVec3 = MutableByteVec3(x.toByte(), y.toByte(), z.toByte()) inline fun toMutableByteVec3(conv: (Double) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), conv(z)) fun toMutableByteVec4(): MutableByteVec4 = MutableByteVec4(x.toByte(), y.toByte(), z.toByte(), w.toByte()) inline fun toMutableByteVec4(conv: (Double) -> Byte): MutableByteVec4 = MutableByteVec4(conv(x), conv(y), conv(z), conv(w)) // Conversions to Char fun toCharVec(): CharVec4 = CharVec4(x.toChar(), y.toChar(), z.toChar(), w.toChar()) inline fun toCharVec(conv: (Double) -> Char): CharVec4 = CharVec4(conv(x), conv(y), conv(z), conv(w)) fun toCharVec2(): CharVec2 = CharVec2(x.toChar(), y.toChar()) inline fun toCharVec2(conv: (Double) -> Char): CharVec2 = CharVec2(conv(x), conv(y)) fun toCharVec3(): CharVec3 = CharVec3(x.toChar(), y.toChar(), z.toChar()) inline fun toCharVec3(conv: (Double) -> Char): CharVec3 = CharVec3(conv(x), conv(y), conv(z)) fun toCharVec4(): CharVec4 = CharVec4(x.toChar(), y.toChar(), z.toChar(), w.toChar()) inline fun toCharVec4(conv: (Double) -> Char): CharVec4 = CharVec4(conv(x), conv(y), conv(z), conv(w)) // Conversions to Char fun toMutableCharVec(): MutableCharVec4 = MutableCharVec4(x.toChar(), y.toChar(), z.toChar(), w.toChar()) inline fun toMutableCharVec(conv: (Double) -> Char): MutableCharVec4 = MutableCharVec4(conv(x), conv(y), conv(z), conv(w)) fun toMutableCharVec2(): MutableCharVec2 = MutableCharVec2(x.toChar(), y.toChar()) inline fun toMutableCharVec2(conv: (Double) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y)) fun toMutableCharVec3(): MutableCharVec3 = MutableCharVec3(x.toChar(), y.toChar(), z.toChar()) inline fun toMutableCharVec3(conv: (Double) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), conv(z)) fun toMutableCharVec4(): MutableCharVec4 = MutableCharVec4(x.toChar(), y.toChar(), z.toChar(), w.toChar()) inline fun toMutableCharVec4(conv: (Double) -> Char): MutableCharVec4 = MutableCharVec4(conv(x), conv(y), conv(z), conv(w)) // Conversions to Boolean fun toBoolVec(): BoolVec4 = BoolVec4(x != 0.0, y != 0.0, z != 0.0, w != 0.0) inline fun toBoolVec(conv: (Double) -> Boolean): BoolVec4 = BoolVec4(conv(x), conv(y), conv(z), conv(w)) fun toBoolVec2(): BoolVec2 = BoolVec2(x != 0.0, y != 0.0) inline fun toBoolVec2(conv: (Double) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y)) fun toBoolVec3(): BoolVec3 = BoolVec3(x != 0.0, y != 0.0, z != 0.0) inline fun toBoolVec3(conv: (Double) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), conv(z)) fun toBoolVec4(): BoolVec4 = BoolVec4(x != 0.0, y != 0.0, z != 0.0, w != 0.0) inline fun toBoolVec4(conv: (Double) -> Boolean): BoolVec4 = BoolVec4(conv(x), conv(y), conv(z), conv(w)) // Conversions to Boolean fun toMutableBoolVec(): MutableBoolVec4 = MutableBoolVec4(x != 0.0, y != 0.0, z != 0.0, w != 0.0) inline fun toMutableBoolVec(conv: (Double) -> Boolean): MutableBoolVec4 = MutableBoolVec4(conv(x), conv(y), conv(z), conv(w)) fun toMutableBoolVec2(): MutableBoolVec2 = MutableBoolVec2(x != 0.0, y != 0.0) inline fun toMutableBoolVec2(conv: (Double) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y)) fun toMutableBoolVec3(): MutableBoolVec3 = MutableBoolVec3(x != 0.0, y != 0.0, z != 0.0) inline fun toMutableBoolVec3(conv: (Double) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), conv(z)) fun toMutableBoolVec4(): MutableBoolVec4 = MutableBoolVec4(x != 0.0, y != 0.0, z != 0.0, w != 0.0) inline fun toMutableBoolVec4(conv: (Double) -> Boolean): MutableBoolVec4 = MutableBoolVec4(conv(x), conv(y), conv(z), conv(w)) // Conversions to String fun toStringVec(): StringVec4 = StringVec4(x.toString(), y.toString(), z.toString(), w.toString()) inline fun toStringVec(conv: (Double) -> String): StringVec4 = StringVec4(conv(x), conv(y), conv(z), conv(w)) fun toStringVec2(): StringVec2 = StringVec2(x.toString(), y.toString()) inline fun toStringVec2(conv: (Double) -> String): StringVec2 = StringVec2(conv(x), conv(y)) fun toStringVec3(): StringVec3 = StringVec3(x.toString(), y.toString(), z.toString()) inline fun toStringVec3(conv: (Double) -> String): StringVec3 = StringVec3(conv(x), conv(y), conv(z)) fun toStringVec4(): StringVec4 = StringVec4(x.toString(), y.toString(), z.toString(), w.toString()) inline fun toStringVec4(conv: (Double) -> String): StringVec4 = StringVec4(conv(x), conv(y), conv(z), conv(w)) // Conversions to String fun toMutableStringVec(): MutableStringVec4 = MutableStringVec4(x.toString(), y.toString(), z.toString(), w.toString()) inline fun toMutableStringVec(conv: (Double) -> String): MutableStringVec4 = MutableStringVec4(conv(x), conv(y), conv(z), conv(w)) fun toMutableStringVec2(): MutableStringVec2 = MutableStringVec2(x.toString(), y.toString()) inline fun toMutableStringVec2(conv: (Double) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y)) fun toMutableStringVec3(): MutableStringVec3 = MutableStringVec3(x.toString(), y.toString(), z.toString()) inline fun toMutableStringVec3(conv: (Double) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), conv(z)) fun toMutableStringVec4(): MutableStringVec4 = MutableStringVec4(x.toString(), y.toString(), z.toString(), w.toString()) inline fun toMutableStringVec4(conv: (Double) -> String): MutableStringVec4 = MutableStringVec4(conv(x), conv(y), conv(z), conv(w)) // Conversions to T2 inline fun <T2> toTVec(conv: (Double) -> T2): TVec4<T2> = TVec4<T2>(conv(x), conv(y), conv(z), conv(w)) inline fun <T2> toTVec2(conv: (Double) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y)) inline fun <T2> toTVec3(conv: (Double) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), conv(z)) inline fun <T2> toTVec4(conv: (Double) -> T2): TVec4<T2> = TVec4<T2>(conv(x), conv(y), conv(z), conv(w)) // Conversions to T2 inline fun <T2> toMutableTVec(conv: (Double) -> T2): MutableTVec4<T2> = MutableTVec4<T2>(conv(x), conv(y), conv(z), conv(w)) inline fun <T2> toMutableTVec2(conv: (Double) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y)) inline fun <T2> toMutableTVec3(conv: (Double) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), conv(z)) inline fun <T2> toMutableTVec4(conv: (Double) -> T2): MutableTVec4<T2> = MutableTVec4<T2>(conv(x), conv(y), conv(z), conv(w)) // Allows for swizzling, e.g. v.swizzle.xzx inner class Swizzle { val xx: MutableDoubleVec2 get() = MutableDoubleVec2(x, x) var xy: MutableDoubleVec2 get() = MutableDoubleVec2(x, y) set(value) { x = value.x y = value.y } var xz: MutableDoubleVec2 get() = MutableDoubleVec2(x, z) set(value) { x = value.x z = value.y } var xw: MutableDoubleVec2 get() = MutableDoubleVec2(x, w) set(value) { x = value.x w = value.y } var yx: MutableDoubleVec2 get() = MutableDoubleVec2(y, x) set(value) { y = value.x x = value.y } val yy: MutableDoubleVec2 get() = MutableDoubleVec2(y, y) var yz: MutableDoubleVec2 get() = MutableDoubleVec2(y, z) set(value) { y = value.x z = value.y } var yw: MutableDoubleVec2 get() = MutableDoubleVec2(y, w) set(value) { y = value.x w = value.y } var zx: MutableDoubleVec2 get() = MutableDoubleVec2(z, x) set(value) { z = value.x x = value.y } var zy: MutableDoubleVec2 get() = MutableDoubleVec2(z, y) set(value) { z = value.x y = value.y } val zz: MutableDoubleVec2 get() = MutableDoubleVec2(z, z) var zw: MutableDoubleVec2 get() = MutableDoubleVec2(z, w) set(value) { z = value.x w = value.y } var wx: MutableDoubleVec2 get() = MutableDoubleVec2(w, x) set(value) { w = value.x x = value.y } var wy: MutableDoubleVec2 get() = MutableDoubleVec2(w, y) set(value) { w = value.x y = value.y } var wz: MutableDoubleVec2 get() = MutableDoubleVec2(w, z) set(value) { w = value.x z = value.y } val ww: MutableDoubleVec2 get() = MutableDoubleVec2(w, w) val xxx: MutableDoubleVec3 get() = MutableDoubleVec3(x, x, x) val xxy: MutableDoubleVec3 get() = MutableDoubleVec3(x, x, y) val xxz: MutableDoubleVec3 get() = MutableDoubleVec3(x, x, z) val xxw: MutableDoubleVec3 get() = MutableDoubleVec3(x, x, w) val xyx: MutableDoubleVec3 get() = MutableDoubleVec3(x, y, x) val xyy: MutableDoubleVec3 get() = MutableDoubleVec3(x, y, y) var xyz: MutableDoubleVec3 get() = MutableDoubleVec3(x, y, z) set(value) { x = value.x y = value.y z = value.z } var xyw: MutableDoubleVec3 get() = MutableDoubleVec3(x, y, w) set(value) { x = value.x y = value.y w = value.z } val xzx: MutableDoubleVec3 get() = MutableDoubleVec3(x, z, x) var xzy: MutableDoubleVec3 get() = MutableDoubleVec3(x, z, y) set(value) { x = value.x z = value.y y = value.z } val xzz: MutableDoubleVec3 get() = MutableDoubleVec3(x, z, z) var xzw: MutableDoubleVec3 get() = MutableDoubleVec3(x, z, w) set(value) { x = value.x z = value.y w = value.z } val xwx: MutableDoubleVec3 get() = MutableDoubleVec3(x, w, x) var xwy: MutableDoubleVec3 get() = MutableDoubleVec3(x, w, y) set(value) { x = value.x w = value.y y = value.z } var xwz: MutableDoubleVec3 get() = MutableDoubleVec3(x, w, z) set(value) { x = value.x w = value.y z = value.z } val xww: MutableDoubleVec3 get() = MutableDoubleVec3(x, w, w) val yxx: MutableDoubleVec3 get() = MutableDoubleVec3(y, x, x) val yxy: MutableDoubleVec3 get() = MutableDoubleVec3(y, x, y) var yxz: MutableDoubleVec3 get() = MutableDoubleVec3(y, x, z) set(value) { y = value.x x = value.y z = value.z } var yxw: MutableDoubleVec3 get() = MutableDoubleVec3(y, x, w) set(value) { y = value.x x = value.y w = value.z } val yyx: MutableDoubleVec3 get() = MutableDoubleVec3(y, y, x) val yyy: MutableDoubleVec3 get() = MutableDoubleVec3(y, y, y) val yyz: MutableDoubleVec3 get() = MutableDoubleVec3(y, y, z) val yyw: MutableDoubleVec3 get() = MutableDoubleVec3(y, y, w) var yzx: MutableDoubleVec3 get() = MutableDoubleVec3(y, z, x) set(value) { y = value.x z = value.y x = value.z } val yzy: MutableDoubleVec3 get() = MutableDoubleVec3(y, z, y) val yzz: MutableDoubleVec3 get() = MutableDoubleVec3(y, z, z) var yzw: MutableDoubleVec3 get() = MutableDoubleVec3(y, z, w) set(value) { y = value.x z = value.y w = value.z } var ywx: MutableDoubleVec3 get() = MutableDoubleVec3(y, w, x) set(value) { y = value.x w = value.y x = value.z } val ywy: MutableDoubleVec3 get() = MutableDoubleVec3(y, w, y) var ywz: MutableDoubleVec3 get() = MutableDoubleVec3(y, w, z) set(value) { y = value.x w = value.y z = value.z } val yww: MutableDoubleVec3 get() = MutableDoubleVec3(y, w, w) val zxx: MutableDoubleVec3 get() = MutableDoubleVec3(z, x, x) var zxy: MutableDoubleVec3 get() = MutableDoubleVec3(z, x, y) set(value) { z = value.x x = value.y y = value.z } val zxz: MutableDoubleVec3 get() = MutableDoubleVec3(z, x, z) var zxw: MutableDoubleVec3 get() = MutableDoubleVec3(z, x, w) set(value) { z = value.x x = value.y w = value.z } var zyx: MutableDoubleVec3 get() = MutableDoubleVec3(z, y, x) set(value) { z = value.x y = value.y x = value.z } val zyy: MutableDoubleVec3 get() = MutableDoubleVec3(z, y, y) val zyz: MutableDoubleVec3 get() = MutableDoubleVec3(z, y, z) var zyw: MutableDoubleVec3 get() = MutableDoubleVec3(z, y, w) set(value) { z = value.x y = value.y w = value.z } val zzx: MutableDoubleVec3 get() = MutableDoubleVec3(z, z, x) val zzy: MutableDoubleVec3 get() = MutableDoubleVec3(z, z, y) val zzz: MutableDoubleVec3 get() = MutableDoubleVec3(z, z, z) val zzw: MutableDoubleVec3 get() = MutableDoubleVec3(z, z, w) var zwx: MutableDoubleVec3 get() = MutableDoubleVec3(z, w, x) set(value) { z = value.x w = value.y x = value.z } var zwy: MutableDoubleVec3 get() = MutableDoubleVec3(z, w, y) set(value) { z = value.x w = value.y y = value.z } val zwz: MutableDoubleVec3 get() = MutableDoubleVec3(z, w, z) val zww: MutableDoubleVec3 get() = MutableDoubleVec3(z, w, w) val wxx: MutableDoubleVec3 get() = MutableDoubleVec3(w, x, x) var wxy: MutableDoubleVec3 get() = MutableDoubleVec3(w, x, y) set(value) { w = value.x x = value.y y = value.z } var wxz: MutableDoubleVec3 get() = MutableDoubleVec3(w, x, z) set(value) { w = value.x x = value.y z = value.z } val wxw: MutableDoubleVec3 get() = MutableDoubleVec3(w, x, w) var wyx: MutableDoubleVec3 get() = MutableDoubleVec3(w, y, x) set(value) { w = value.x y = value.y x = value.z } val wyy: MutableDoubleVec3 get() = MutableDoubleVec3(w, y, y) var wyz: MutableDoubleVec3 get() = MutableDoubleVec3(w, y, z) set(value) { w = value.x y = value.y z = value.z } val wyw: MutableDoubleVec3 get() = MutableDoubleVec3(w, y, w) var wzx: MutableDoubleVec3 get() = MutableDoubleVec3(w, z, x) set(value) { w = value.x z = value.y x = value.z } var wzy: MutableDoubleVec3 get() = MutableDoubleVec3(w, z, y) set(value) { w = value.x z = value.y y = value.z } val wzz: MutableDoubleVec3 get() = MutableDoubleVec3(w, z, z) val wzw: MutableDoubleVec3 get() = MutableDoubleVec3(w, z, w) val wwx: MutableDoubleVec3 get() = MutableDoubleVec3(w, w, x) val wwy: MutableDoubleVec3 get() = MutableDoubleVec3(w, w, y) val wwz: MutableDoubleVec3 get() = MutableDoubleVec3(w, w, z) val www: MutableDoubleVec3 get() = MutableDoubleVec3(w, w, w) val xxxx: MutableDoubleVec4 get() = MutableDoubleVec4(x, x, x, x) val xxxy: MutableDoubleVec4 get() = MutableDoubleVec4(x, x, x, y) val xxxz: MutableDoubleVec4 get() = MutableDoubleVec4(x, x, x, z) val xxxw: MutableDoubleVec4 get() = MutableDoubleVec4(x, x, x, w) val xxyx: MutableDoubleVec4 get() = MutableDoubleVec4(x, x, y, x) val xxyy: MutableDoubleVec4 get() = MutableDoubleVec4(x, x, y, y) val xxyz: MutableDoubleVec4 get() = MutableDoubleVec4(x, x, y, z) val xxyw: MutableDoubleVec4 get() = MutableDoubleVec4(x, x, y, w) val xxzx: MutableDoubleVec4 get() = MutableDoubleVec4(x, x, z, x) val xxzy: MutableDoubleVec4 get() = MutableDoubleVec4(x, x, z, y) val xxzz: MutableDoubleVec4 get() = MutableDoubleVec4(x, x, z, z) val xxzw: MutableDoubleVec4 get() = MutableDoubleVec4(x, x, z, w) val xxwx: MutableDoubleVec4 get() = MutableDoubleVec4(x, x, w, x) val xxwy: MutableDoubleVec4 get() = MutableDoubleVec4(x, x, w, y) val xxwz: MutableDoubleVec4 get() = MutableDoubleVec4(x, x, w, z) val xxww: MutableDoubleVec4 get() = MutableDoubleVec4(x, x, w, w) val xyxx: MutableDoubleVec4 get() = MutableDoubleVec4(x, y, x, x) val xyxy: MutableDoubleVec4 get() = MutableDoubleVec4(x, y, x, y) val xyxz: MutableDoubleVec4 get() = MutableDoubleVec4(x, y, x, z) val xyxw: MutableDoubleVec4 get() = MutableDoubleVec4(x, y, x, w) val xyyx: MutableDoubleVec4 get() = MutableDoubleVec4(x, y, y, x) val xyyy: MutableDoubleVec4 get() = MutableDoubleVec4(x, y, y, y) val xyyz: MutableDoubleVec4 get() = MutableDoubleVec4(x, y, y, z) val xyyw: MutableDoubleVec4 get() = MutableDoubleVec4(x, y, y, w) val xyzx: MutableDoubleVec4 get() = MutableDoubleVec4(x, y, z, x) val xyzy: MutableDoubleVec4 get() = MutableDoubleVec4(x, y, z, y) val xyzz: MutableDoubleVec4 get() = MutableDoubleVec4(x, y, z, z) var xyzw: MutableDoubleVec4 get() = MutableDoubleVec4(x, y, z, w) set(value) { x = value.x y = value.y z = value.z w = value.w } val xywx: MutableDoubleVec4 get() = MutableDoubleVec4(x, y, w, x) val xywy: MutableDoubleVec4 get() = MutableDoubleVec4(x, y, w, y) var xywz: MutableDoubleVec4 get() = MutableDoubleVec4(x, y, w, z) set(value) { x = value.x y = value.y w = value.z z = value.w } val xyww: MutableDoubleVec4 get() = MutableDoubleVec4(x, y, w, w) val xzxx: MutableDoubleVec4 get() = MutableDoubleVec4(x, z, x, x) val xzxy: MutableDoubleVec4 get() = MutableDoubleVec4(x, z, x, y) val xzxz: MutableDoubleVec4 get() = MutableDoubleVec4(x, z, x, z) val xzxw: MutableDoubleVec4 get() = MutableDoubleVec4(x, z, x, w) val xzyx: MutableDoubleVec4 get() = MutableDoubleVec4(x, z, y, x) val xzyy: MutableDoubleVec4 get() = MutableDoubleVec4(x, z, y, y) val xzyz: MutableDoubleVec4 get() = MutableDoubleVec4(x, z, y, z) var xzyw: MutableDoubleVec4 get() = MutableDoubleVec4(x, z, y, w) set(value) { x = value.x z = value.y y = value.z w = value.w } val xzzx: MutableDoubleVec4 get() = MutableDoubleVec4(x, z, z, x) val xzzy: MutableDoubleVec4 get() = MutableDoubleVec4(x, z, z, y) val xzzz: MutableDoubleVec4 get() = MutableDoubleVec4(x, z, z, z) val xzzw: MutableDoubleVec4 get() = MutableDoubleVec4(x, z, z, w) val xzwx: MutableDoubleVec4 get() = MutableDoubleVec4(x, z, w, x) var xzwy: MutableDoubleVec4 get() = MutableDoubleVec4(x, z, w, y) set(value) { x = value.x z = value.y w = value.z y = value.w } val xzwz: MutableDoubleVec4 get() = MutableDoubleVec4(x, z, w, z) val xzww: MutableDoubleVec4 get() = MutableDoubleVec4(x, z, w, w) val xwxx: MutableDoubleVec4 get() = MutableDoubleVec4(x, w, x, x) val xwxy: MutableDoubleVec4 get() = MutableDoubleVec4(x, w, x, y) val xwxz: MutableDoubleVec4 get() = MutableDoubleVec4(x, w, x, z) val xwxw: MutableDoubleVec4 get() = MutableDoubleVec4(x, w, x, w) val xwyx: MutableDoubleVec4 get() = MutableDoubleVec4(x, w, y, x) val xwyy: MutableDoubleVec4 get() = MutableDoubleVec4(x, w, y, y) var xwyz: MutableDoubleVec4 get() = MutableDoubleVec4(x, w, y, z) set(value) { x = value.x w = value.y y = value.z z = value.w } val xwyw: MutableDoubleVec4 get() = MutableDoubleVec4(x, w, y, w) val xwzx: MutableDoubleVec4 get() = MutableDoubleVec4(x, w, z, x) var xwzy: MutableDoubleVec4 get() = MutableDoubleVec4(x, w, z, y) set(value) { x = value.x w = value.y z = value.z y = value.w } val xwzz: MutableDoubleVec4 get() = MutableDoubleVec4(x, w, z, z) val xwzw: MutableDoubleVec4 get() = MutableDoubleVec4(x, w, z, w) val xwwx: MutableDoubleVec4 get() = MutableDoubleVec4(x, w, w, x) val xwwy: MutableDoubleVec4 get() = MutableDoubleVec4(x, w, w, y) val xwwz: MutableDoubleVec4 get() = MutableDoubleVec4(x, w, w, z) val xwww: MutableDoubleVec4 get() = MutableDoubleVec4(x, w, w, w) val yxxx: MutableDoubleVec4 get() = MutableDoubleVec4(y, x, x, x) val yxxy: MutableDoubleVec4 get() = MutableDoubleVec4(y, x, x, y) val yxxz: MutableDoubleVec4 get() = MutableDoubleVec4(y, x, x, z) val yxxw: MutableDoubleVec4 get() = MutableDoubleVec4(y, x, x, w) val yxyx: MutableDoubleVec4 get() = MutableDoubleVec4(y, x, y, x) val yxyy: MutableDoubleVec4 get() = MutableDoubleVec4(y, x, y, y) val yxyz: MutableDoubleVec4 get() = MutableDoubleVec4(y, x, y, z) val yxyw: MutableDoubleVec4 get() = MutableDoubleVec4(y, x, y, w) val yxzx: MutableDoubleVec4 get() = MutableDoubleVec4(y, x, z, x) val yxzy: MutableDoubleVec4 get() = MutableDoubleVec4(y, x, z, y) val yxzz: MutableDoubleVec4 get() = MutableDoubleVec4(y, x, z, z) var yxzw: MutableDoubleVec4 get() = MutableDoubleVec4(y, x, z, w) set(value) { y = value.x x = value.y z = value.z w = value.w } val yxwx: MutableDoubleVec4 get() = MutableDoubleVec4(y, x, w, x) val yxwy: MutableDoubleVec4 get() = MutableDoubleVec4(y, x, w, y) var yxwz: MutableDoubleVec4 get() = MutableDoubleVec4(y, x, w, z) set(value) { y = value.x x = value.y w = value.z z = value.w } val yxww: MutableDoubleVec4 get() = MutableDoubleVec4(y, x, w, w) val yyxx: MutableDoubleVec4 get() = MutableDoubleVec4(y, y, x, x) val yyxy: MutableDoubleVec4 get() = MutableDoubleVec4(y, y, x, y) val yyxz: MutableDoubleVec4 get() = MutableDoubleVec4(y, y, x, z) val yyxw: MutableDoubleVec4 get() = MutableDoubleVec4(y, y, x, w) val yyyx: MutableDoubleVec4 get() = MutableDoubleVec4(y, y, y, x) val yyyy: MutableDoubleVec4 get() = MutableDoubleVec4(y, y, y, y) val yyyz: MutableDoubleVec4 get() = MutableDoubleVec4(y, y, y, z) val yyyw: MutableDoubleVec4 get() = MutableDoubleVec4(y, y, y, w) val yyzx: MutableDoubleVec4 get() = MutableDoubleVec4(y, y, z, x) val yyzy: MutableDoubleVec4 get() = MutableDoubleVec4(y, y, z, y) val yyzz: MutableDoubleVec4 get() = MutableDoubleVec4(y, y, z, z) val yyzw: MutableDoubleVec4 get() = MutableDoubleVec4(y, y, z, w) val yywx: MutableDoubleVec4 get() = MutableDoubleVec4(y, y, w, x) val yywy: MutableDoubleVec4 get() = MutableDoubleVec4(y, y, w, y) val yywz: MutableDoubleVec4 get() = MutableDoubleVec4(y, y, w, z) val yyww: MutableDoubleVec4 get() = MutableDoubleVec4(y, y, w, w) val yzxx: MutableDoubleVec4 get() = MutableDoubleVec4(y, z, x, x) val yzxy: MutableDoubleVec4 get() = MutableDoubleVec4(y, z, x, y) val yzxz: MutableDoubleVec4 get() = MutableDoubleVec4(y, z, x, z) var yzxw: MutableDoubleVec4 get() = MutableDoubleVec4(y, z, x, w) set(value) { y = value.x z = value.y x = value.z w = value.w } val yzyx: MutableDoubleVec4 get() = MutableDoubleVec4(y, z, y, x) val yzyy: MutableDoubleVec4 get() = MutableDoubleVec4(y, z, y, y) val yzyz: MutableDoubleVec4 get() = MutableDoubleVec4(y, z, y, z) val yzyw: MutableDoubleVec4 get() = MutableDoubleVec4(y, z, y, w) val yzzx: MutableDoubleVec4 get() = MutableDoubleVec4(y, z, z, x) val yzzy: MutableDoubleVec4 get() = MutableDoubleVec4(y, z, z, y) val yzzz: MutableDoubleVec4 get() = MutableDoubleVec4(y, z, z, z) val yzzw: MutableDoubleVec4 get() = MutableDoubleVec4(y, z, z, w) var yzwx: MutableDoubleVec4 get() = MutableDoubleVec4(y, z, w, x) set(value) { y = value.x z = value.y w = value.z x = value.w } val yzwy: MutableDoubleVec4 get() = MutableDoubleVec4(y, z, w, y) val yzwz: MutableDoubleVec4 get() = MutableDoubleVec4(y, z, w, z) val yzww: MutableDoubleVec4 get() = MutableDoubleVec4(y, z, w, w) val ywxx: MutableDoubleVec4 get() = MutableDoubleVec4(y, w, x, x) val ywxy: MutableDoubleVec4 get() = MutableDoubleVec4(y, w, x, y) var ywxz: MutableDoubleVec4 get() = MutableDoubleVec4(y, w, x, z) set(value) { y = value.x w = value.y x = value.z z = value.w } val ywxw: MutableDoubleVec4 get() = MutableDoubleVec4(y, w, x, w) val ywyx: MutableDoubleVec4 get() = MutableDoubleVec4(y, w, y, x) val ywyy: MutableDoubleVec4 get() = MutableDoubleVec4(y, w, y, y) val ywyz: MutableDoubleVec4 get() = MutableDoubleVec4(y, w, y, z) val ywyw: MutableDoubleVec4 get() = MutableDoubleVec4(y, w, y, w) var ywzx: MutableDoubleVec4 get() = MutableDoubleVec4(y, w, z, x) set(value) { y = value.x w = value.y z = value.z x = value.w } val ywzy: MutableDoubleVec4 get() = MutableDoubleVec4(y, w, z, y) val ywzz: MutableDoubleVec4 get() = MutableDoubleVec4(y, w, z, z) val ywzw: MutableDoubleVec4 get() = MutableDoubleVec4(y, w, z, w) val ywwx: MutableDoubleVec4 get() = MutableDoubleVec4(y, w, w, x) val ywwy: MutableDoubleVec4 get() = MutableDoubleVec4(y, w, w, y) val ywwz: MutableDoubleVec4 get() = MutableDoubleVec4(y, w, w, z) val ywww: MutableDoubleVec4 get() = MutableDoubleVec4(y, w, w, w) val zxxx: MutableDoubleVec4 get() = MutableDoubleVec4(z, x, x, x) val zxxy: MutableDoubleVec4 get() = MutableDoubleVec4(z, x, x, y) val zxxz: MutableDoubleVec4 get() = MutableDoubleVec4(z, x, x, z) val zxxw: MutableDoubleVec4 get() = MutableDoubleVec4(z, x, x, w) val zxyx: MutableDoubleVec4 get() = MutableDoubleVec4(z, x, y, x) val zxyy: MutableDoubleVec4 get() = MutableDoubleVec4(z, x, y, y) val zxyz: MutableDoubleVec4 get() = MutableDoubleVec4(z, x, y, z) var zxyw: MutableDoubleVec4 get() = MutableDoubleVec4(z, x, y, w) set(value) { z = value.x x = value.y y = value.z w = value.w } val zxzx: MutableDoubleVec4 get() = MutableDoubleVec4(z, x, z, x) val zxzy: MutableDoubleVec4 get() = MutableDoubleVec4(z, x, z, y) val zxzz: MutableDoubleVec4 get() = MutableDoubleVec4(z, x, z, z) val zxzw: MutableDoubleVec4 get() = MutableDoubleVec4(z, x, z, w) val zxwx: MutableDoubleVec4 get() = MutableDoubleVec4(z, x, w, x) var zxwy: MutableDoubleVec4 get() = MutableDoubleVec4(z, x, w, y) set(value) { z = value.x x = value.y w = value.z y = value.w } val zxwz: MutableDoubleVec4 get() = MutableDoubleVec4(z, x, w, z) val zxww: MutableDoubleVec4 get() = MutableDoubleVec4(z, x, w, w) val zyxx: MutableDoubleVec4 get() = MutableDoubleVec4(z, y, x, x) val zyxy: MutableDoubleVec4 get() = MutableDoubleVec4(z, y, x, y) val zyxz: MutableDoubleVec4 get() = MutableDoubleVec4(z, y, x, z) var zyxw: MutableDoubleVec4 get() = MutableDoubleVec4(z, y, x, w) set(value) { z = value.x y = value.y x = value.z w = value.w } val zyyx: MutableDoubleVec4 get() = MutableDoubleVec4(z, y, y, x) val zyyy: MutableDoubleVec4 get() = MutableDoubleVec4(z, y, y, y) val zyyz: MutableDoubleVec4 get() = MutableDoubleVec4(z, y, y, z) val zyyw: MutableDoubleVec4 get() = MutableDoubleVec4(z, y, y, w) val zyzx: MutableDoubleVec4 get() = MutableDoubleVec4(z, y, z, x) val zyzy: MutableDoubleVec4 get() = MutableDoubleVec4(z, y, z, y) val zyzz: MutableDoubleVec4 get() = MutableDoubleVec4(z, y, z, z) val zyzw: MutableDoubleVec4 get() = MutableDoubleVec4(z, y, z, w) var zywx: MutableDoubleVec4 get() = MutableDoubleVec4(z, y, w, x) set(value) { z = value.x y = value.y w = value.z x = value.w } val zywy: MutableDoubleVec4 get() = MutableDoubleVec4(z, y, w, y) val zywz: MutableDoubleVec4 get() = MutableDoubleVec4(z, y, w, z) val zyww: MutableDoubleVec4 get() = MutableDoubleVec4(z, y, w, w) val zzxx: MutableDoubleVec4 get() = MutableDoubleVec4(z, z, x, x) val zzxy: MutableDoubleVec4 get() = MutableDoubleVec4(z, z, x, y) val zzxz: MutableDoubleVec4 get() = MutableDoubleVec4(z, z, x, z) val zzxw: MutableDoubleVec4 get() = MutableDoubleVec4(z, z, x, w) val zzyx: MutableDoubleVec4 get() = MutableDoubleVec4(z, z, y, x) val zzyy: MutableDoubleVec4 get() = MutableDoubleVec4(z, z, y, y) val zzyz: MutableDoubleVec4 get() = MutableDoubleVec4(z, z, y, z) val zzyw: MutableDoubleVec4 get() = MutableDoubleVec4(z, z, y, w) val zzzx: MutableDoubleVec4 get() = MutableDoubleVec4(z, z, z, x) val zzzy: MutableDoubleVec4 get() = MutableDoubleVec4(z, z, z, y) val zzzz: MutableDoubleVec4 get() = MutableDoubleVec4(z, z, z, z) val zzzw: MutableDoubleVec4 get() = MutableDoubleVec4(z, z, z, w) val zzwx: MutableDoubleVec4 get() = MutableDoubleVec4(z, z, w, x) val zzwy: MutableDoubleVec4 get() = MutableDoubleVec4(z, z, w, y) val zzwz: MutableDoubleVec4 get() = MutableDoubleVec4(z, z, w, z) val zzww: MutableDoubleVec4 get() = MutableDoubleVec4(z, z, w, w) val zwxx: MutableDoubleVec4 get() = MutableDoubleVec4(z, w, x, x) var zwxy: MutableDoubleVec4 get() = MutableDoubleVec4(z, w, x, y) set(value) { z = value.x w = value.y x = value.z y = value.w } val zwxz: MutableDoubleVec4 get() = MutableDoubleVec4(z, w, x, z) val zwxw: MutableDoubleVec4 get() = MutableDoubleVec4(z, w, x, w) var zwyx: MutableDoubleVec4 get() = MutableDoubleVec4(z, w, y, x) set(value) { z = value.x w = value.y y = value.z x = value.w } val zwyy: MutableDoubleVec4 get() = MutableDoubleVec4(z, w, y, y) val zwyz: MutableDoubleVec4 get() = MutableDoubleVec4(z, w, y, z) val zwyw: MutableDoubleVec4 get() = MutableDoubleVec4(z, w, y, w) val zwzx: MutableDoubleVec4 get() = MutableDoubleVec4(z, w, z, x) val zwzy: MutableDoubleVec4 get() = MutableDoubleVec4(z, w, z, y) val zwzz: MutableDoubleVec4 get() = MutableDoubleVec4(z, w, z, z) val zwzw: MutableDoubleVec4 get() = MutableDoubleVec4(z, w, z, w) val zwwx: MutableDoubleVec4 get() = MutableDoubleVec4(z, w, w, x) val zwwy: MutableDoubleVec4 get() = MutableDoubleVec4(z, w, w, y) val zwwz: MutableDoubleVec4 get() = MutableDoubleVec4(z, w, w, z) val zwww: MutableDoubleVec4 get() = MutableDoubleVec4(z, w, w, w) val wxxx: MutableDoubleVec4 get() = MutableDoubleVec4(w, x, x, x) val wxxy: MutableDoubleVec4 get() = MutableDoubleVec4(w, x, x, y) val wxxz: MutableDoubleVec4 get() = MutableDoubleVec4(w, x, x, z) val wxxw: MutableDoubleVec4 get() = MutableDoubleVec4(w, x, x, w) val wxyx: MutableDoubleVec4 get() = MutableDoubleVec4(w, x, y, x) val wxyy: MutableDoubleVec4 get() = MutableDoubleVec4(w, x, y, y) var wxyz: MutableDoubleVec4 get() = MutableDoubleVec4(w, x, y, z) set(value) { w = value.x x = value.y y = value.z z = value.w } val wxyw: MutableDoubleVec4 get() = MutableDoubleVec4(w, x, y, w) val wxzx: MutableDoubleVec4 get() = MutableDoubleVec4(w, x, z, x) var wxzy: MutableDoubleVec4 get() = MutableDoubleVec4(w, x, z, y) set(value) { w = value.x x = value.y z = value.z y = value.w } val wxzz: MutableDoubleVec4 get() = MutableDoubleVec4(w, x, z, z) val wxzw: MutableDoubleVec4 get() = MutableDoubleVec4(w, x, z, w) val wxwx: MutableDoubleVec4 get() = MutableDoubleVec4(w, x, w, x) val wxwy: MutableDoubleVec4 get() = MutableDoubleVec4(w, x, w, y) val wxwz: MutableDoubleVec4 get() = MutableDoubleVec4(w, x, w, z) val wxww: MutableDoubleVec4 get() = MutableDoubleVec4(w, x, w, w) val wyxx: MutableDoubleVec4 get() = MutableDoubleVec4(w, y, x, x) val wyxy: MutableDoubleVec4 get() = MutableDoubleVec4(w, y, x, y) var wyxz: MutableDoubleVec4 get() = MutableDoubleVec4(w, y, x, z) set(value) { w = value.x y = value.y x = value.z z = value.w } val wyxw: MutableDoubleVec4 get() = MutableDoubleVec4(w, y, x, w) val wyyx: MutableDoubleVec4 get() = MutableDoubleVec4(w, y, y, x) val wyyy: MutableDoubleVec4 get() = MutableDoubleVec4(w, y, y, y) val wyyz: MutableDoubleVec4 get() = MutableDoubleVec4(w, y, y, z) val wyyw: MutableDoubleVec4 get() = MutableDoubleVec4(w, y, y, w) var wyzx: MutableDoubleVec4 get() = MutableDoubleVec4(w, y, z, x) set(value) { w = value.x y = value.y z = value.z x = value.w } val wyzy: MutableDoubleVec4 get() = MutableDoubleVec4(w, y, z, y) val wyzz: MutableDoubleVec4 get() = MutableDoubleVec4(w, y, z, z) val wyzw: MutableDoubleVec4 get() = MutableDoubleVec4(w, y, z, w) val wywx: MutableDoubleVec4 get() = MutableDoubleVec4(w, y, w, x) val wywy: MutableDoubleVec4 get() = MutableDoubleVec4(w, y, w, y) val wywz: MutableDoubleVec4 get() = MutableDoubleVec4(w, y, w, z) val wyww: MutableDoubleVec4 get() = MutableDoubleVec4(w, y, w, w) val wzxx: MutableDoubleVec4 get() = MutableDoubleVec4(w, z, x, x) var wzxy: MutableDoubleVec4 get() = MutableDoubleVec4(w, z, x, y) set(value) { w = value.x z = value.y x = value.z y = value.w } val wzxz: MutableDoubleVec4 get() = MutableDoubleVec4(w, z, x, z) val wzxw: MutableDoubleVec4 get() = MutableDoubleVec4(w, z, x, w) var wzyx: MutableDoubleVec4 get() = MutableDoubleVec4(w, z, y, x) set(value) { w = value.x z = value.y y = value.z x = value.w } val wzyy: MutableDoubleVec4 get() = MutableDoubleVec4(w, z, y, y) val wzyz: MutableDoubleVec4 get() = MutableDoubleVec4(w, z, y, z) val wzyw: MutableDoubleVec4 get() = MutableDoubleVec4(w, z, y, w) val wzzx: MutableDoubleVec4 get() = MutableDoubleVec4(w, z, z, x) val wzzy: MutableDoubleVec4 get() = MutableDoubleVec4(w, z, z, y) val wzzz: MutableDoubleVec4 get() = MutableDoubleVec4(w, z, z, z) val wzzw: MutableDoubleVec4 get() = MutableDoubleVec4(w, z, z, w) val wzwx: MutableDoubleVec4 get() = MutableDoubleVec4(w, z, w, x) val wzwy: MutableDoubleVec4 get() = MutableDoubleVec4(w, z, w, y) val wzwz: MutableDoubleVec4 get() = MutableDoubleVec4(w, z, w, z) val wzww: MutableDoubleVec4 get() = MutableDoubleVec4(w, z, w, w) val wwxx: MutableDoubleVec4 get() = MutableDoubleVec4(w, w, x, x) val wwxy: MutableDoubleVec4 get() = MutableDoubleVec4(w, w, x, y) val wwxz: MutableDoubleVec4 get() = MutableDoubleVec4(w, w, x, z) val wwxw: MutableDoubleVec4 get() = MutableDoubleVec4(w, w, x, w) val wwyx: MutableDoubleVec4 get() = MutableDoubleVec4(w, w, y, x) val wwyy: MutableDoubleVec4 get() = MutableDoubleVec4(w, w, y, y) val wwyz: MutableDoubleVec4 get() = MutableDoubleVec4(w, w, y, z) val wwyw: MutableDoubleVec4 get() = MutableDoubleVec4(w, w, y, w) val wwzx: MutableDoubleVec4 get() = MutableDoubleVec4(w, w, z, x) val wwzy: MutableDoubleVec4 get() = MutableDoubleVec4(w, w, z, y) val wwzz: MutableDoubleVec4 get() = MutableDoubleVec4(w, w, z, z) val wwzw: MutableDoubleVec4 get() = MutableDoubleVec4(w, w, z, w) val wwwx: MutableDoubleVec4 get() = MutableDoubleVec4(w, w, w, x) val wwwy: MutableDoubleVec4 get() = MutableDoubleVec4(w, w, w, y) val wwwz: MutableDoubleVec4 get() = MutableDoubleVec4(w, w, w, z) val wwww: MutableDoubleVec4 get() = MutableDoubleVec4(w, w, w, w) } val swizzle: Swizzle get() = Swizzle() } fun mutableVecOf(x: Double, y: Double, z: Double, w: Double): MutableDoubleVec4 = MutableDoubleVec4(x, y, z, w) operator fun Double.plus(rhs: MutableDoubleVec4): MutableDoubleVec4 = MutableDoubleVec4(this + rhs.x, this + rhs.y, this + rhs.z, this + rhs.w) operator fun Double.minus(rhs: MutableDoubleVec4): MutableDoubleVec4 = MutableDoubleVec4(this - rhs.x, this - rhs.y, this - rhs.z, this - rhs.w) operator fun Double.times(rhs: MutableDoubleVec4): MutableDoubleVec4 = MutableDoubleVec4(this * rhs.x, this * rhs.y, this * rhs.z, this * rhs.w) operator fun Double.div(rhs: MutableDoubleVec4): MutableDoubleVec4 = MutableDoubleVec4(this / rhs.x, this / rhs.y, this / rhs.z, this / rhs.w) operator fun Double.rem(rhs: MutableDoubleVec4): MutableDoubleVec4 = MutableDoubleVec4(this % rhs.x, this % rhs.y, this % rhs.z, this % rhs.w)
mit
2713d9f46bf89dc956314178c65b3c45
53.495876
144
0.588033
3.747412
false
false
false
false
airbnb/lottie-android
snapshot-tests/src/androidTest/java/com/airbnb/lottie/snapshots/tests/ComposeScaleTypesTestCase.kt
1
5696
package com.airbnb.lottie.snapshots.tests import androidx.compose.foundation.layout.size import androidx.compose.ui.Modifier import androidx.compose.ui.draw.scale import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.unit.dp import com.airbnb.lottie.compose.LottieAnimation import com.airbnb.lottie.snapshots.SnapshotTestCase import com.airbnb.lottie.snapshots.SnapshotTestCaseContext import com.airbnb.lottie.snapshots.loadCompositionFromAssetsSync import com.airbnb.lottie.snapshots.snapshotComposable class ComposeScaleTypesTestCase : SnapshotTestCase { override suspend fun SnapshotTestCaseContext.run() { val composition = loadCompositionFromAssetsSync("Lottie Logo 1.json") snapshotComposable("Compose Scale Types", "Wrap Content", renderHardwareAndSoftware = true) { renderMode -> LottieAnimation( composition, { 1f }, renderMode = renderMode, ) } snapshotComposable("Compose Scale Types", "720p", renderHardwareAndSoftware = true) { renderMode -> LottieAnimation( composition, { 1f }, renderMode = renderMode, modifier = Modifier .size(720.dp, 1280.dp) ) } snapshotComposable("Compose Scale Types", "300x300@2x", renderHardwareAndSoftware = true) { renderMode -> LottieAnimation( composition, { 1f }, renderMode = renderMode, modifier = Modifier .size(300.dp, 300.dp) .scale(2f) ) } snapshotComposable("Compose Scale Types", "300x300@4x", renderHardwareAndSoftware = true) { renderMode -> LottieAnimation( composition, { 1f }, renderMode = renderMode, modifier = Modifier .size(300.dp, 300.dp) .scale(4f) ) } snapshotComposable("Compose Scale Types", "300x300 Crop", renderHardwareAndSoftware = true) { renderMode -> LottieAnimation( composition, { 1f }, contentScale = ContentScale.Crop, renderMode = renderMode, modifier = Modifier .size(300.dp, 300.dp) ) } snapshotComposable("Compose Scale Types", "300x300 Inside", renderHardwareAndSoftware = true) { renderMode -> LottieAnimation( composition, { 1f }, contentScale = ContentScale.Inside, renderMode = renderMode, modifier = Modifier .size(300.dp, 300.dp) ) } snapshotComposable("Compose Scale Types", "300x300 FillBounds", renderHardwareAndSoftware = true) { renderMode -> LottieAnimation( composition, { 1f }, contentScale = ContentScale.FillBounds, renderMode = renderMode, modifier = Modifier .size(300.dp, 300.dp) ) } snapshotComposable("Compose Scale Types", "300x300 Fit 2x", renderHardwareAndSoftware = true) { renderMode -> LottieAnimation( composition, { 1f }, contentScale = ContentScale.Fit, renderMode = renderMode, modifier = Modifier .size(300.dp, 300.dp) .scale(2f) ) } snapshotComposable("Compose Scale Types", "300x300 Crop 2x", renderHardwareAndSoftware = true) { renderMode -> LottieAnimation( composition, { 1f }, contentScale = ContentScale.Crop, renderMode = renderMode, modifier = Modifier .size(300.dp, 300.dp) .scale(2f) ) } snapshotComposable("Compose Scale Types", "600x600 Inside", renderHardwareAndSoftware = true) { renderMode -> LottieAnimation( composition, { 1f }, contentScale = ContentScale.Inside, renderMode = renderMode, modifier = Modifier .size(600.dp, 600.dp) ) } snapshotComposable("Compose Scale Types", "600x600 FillBounds", renderHardwareAndSoftware = true) { renderMode -> LottieAnimation( composition, { 1f }, contentScale = ContentScale.FillBounds, renderMode = renderMode, modifier = Modifier .size(600.dp, 600.dp) ) } snapshotComposable("Compose Scale Types", "600x600 Fit", renderHardwareAndSoftware = true) { renderMode -> LottieAnimation( composition, { 1f }, contentScale = ContentScale.Fit, renderMode = renderMode, modifier = Modifier .size(600.dp, 600.dp) ) } snapshotComposable("Compose Scale Types", "300x600 FitBounds", renderHardwareAndSoftware = true) { renderMode -> LottieAnimation( composition, { 1f }, contentScale = ContentScale.FillBounds, renderMode = renderMode, modifier = Modifier .size(300.dp, 600.dp) ) } } }
apache-2.0
2c0678aac5630dafe9de656743e5082e
35.056962
121
0.528265
5.323364
false
false
false
false
AshishKayastha/Movie-Guide
app/src/main/kotlin/com/ashish/movieguide/data/api/MovieApi.kt
1
2217
package com.ashish.movieguide.data.api import com.ashish.movieguide.data.models.Movie import com.ashish.movieguide.data.models.MovieDetail import com.ashish.movieguide.data.models.Rating import com.ashish.movieguide.data.models.Results import com.ashish.movieguide.data.models.Review import com.ashish.movieguide.data.models.Status import com.ashish.movieguide.utils.Constants.INCLUDE_IMAGE_LANGUAGE import io.reactivex.Single import retrofit2.http.Body import retrofit2.http.DELETE import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.Path import retrofit2.http.Query /** * Created by Ashish on Dec 27. */ interface MovieApi { companion object { const val NOW_PLAYING = "now_playing" const val POPULAR = "popular" const val TOP_RATED = "top_rated" const val UPCOMING = "upcoming" } @GET("movie/{movieType}") fun getMovies( @Path("movieType") movieType: String?, @Query("page") page: Int = 1, @Query("region") region: String = "US" ): Single<Results<Movie>> @GET("movie/{movieId}" + INCLUDE_IMAGE_LANGUAGE) fun getMovieDetail( @Path("movieId") movieId: Long, @Query("append_to_response") appendedResponse: String ): Single<MovieDetail> @POST("movie/{movieId}/rating") fun rateMovie(@Path("movieId") movieId: Long, @Body rating: Rating): Single<Status> @DELETE("movie/{movieId}/rating") fun deleteMovieRating(@Path("movieId") movieId: Long): Single<Status> @GET("movie/{movieId}/reviews") fun getMovieReviews( @Path("movieId") movieId: Long, @Query("page") page: Int = 1 ): Single<Results<Review>> @GET("discover/movie") fun discoverMovie( @Query("sort_by") sortBy: String = "popularity.desc", @Query("release_date.gte") minReleaseDate: String? = null, @Query("release_date.lte") maxReleaseDate: String? = null, @Query("with_genres") genreIds: String? = null, @Query("page") page: Int = 1, @Query("region") region: String = "US", @Query("with_release_type") releaseType: String = "2|3" ): Single<Results<Movie>> }
apache-2.0
270a723a84953f5671ce446cbf8e5a3f
33.123077
87
0.656743
3.83564
false
false
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/readinglist/sync/SyncedReadingLists.kt
1
2744
package org.wikipedia.readinglist.sync import com.google.gson.annotations.SerializedName import org.wikipedia.dataclient.page.PageSummary import org.wikipedia.json.annotations.Required import org.wikipedia.util.DateUtil import java.text.Normalizer import java.util.* data class SyncedReadingLists(val lists: List<RemoteReadingList>?, val entries: List<RemoteReadingListEntry>?, @SerializedName("next") val continueStr: String?) { constructor(lists: List<RemoteReadingList>?, entries: List<RemoteReadingListEntry>?) : this(lists, entries, null) data class RemoteReadingList(@Required val id: Long, @SerializedName("default") val isDefault: Boolean, @Required private val name: String, private val description: String?, @Required val created: String, @Required val updated: String, @SerializedName("deleted") val isDeleted: Boolean) { constructor(name: String, description: String?) : this(0, false, name, description, DateUtil.iso8601DateFormat(Date()), DateUtil.iso8601DateFormat(Date()), false) fun name(): String = Normalizer.normalize(name, Normalizer.Form.NFC) fun description(): String? = Normalizer.normalize(description.orEmpty(), Normalizer.Form.NFC) } data class RemoteReadingListEntry(val id: Long, val listId: Long, @Required private val project: String, @Required private val title: String, @Required val created: String, @Required val updated: String, val summary: PageSummary?, @SerializedName("deleted") val isDeleted: Boolean) { constructor(project: String, title: String) : this(0, 0, project, title, DateUtil.iso8601DateFormat(Date()), DateUtil.iso8601DateFormat(Date()), null, false) fun project(): String = Normalizer.normalize(project, Normalizer.Form.NFC) fun title(): String = Normalizer.normalize(title, Normalizer.Form.NFC) } data class RemoteReadingListEntryBatch(val entries: List<RemoteReadingListEntry>) { val batch: Array<RemoteReadingListEntry> = entries.toTypedArray() } inner class RemoteIdResponse { @Required val id: Long = 0 } inner class RemoteIdResponseBatch { @Required val batch: Array<RemoteIdResponse> = arrayOf() } }
apache-2.0
e1a83c1d03dd4dd8f83c3d97b3d3d5fe
46.310345
128
0.594023
5.380392
false
false
false
false
dahlstrom-g/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/editor/tables/actions/column/ColumnBasedTableAction.kt
4
4181
// 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.intellij.plugins.markdown.editor.tables.actions.column import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiFile import org.intellij.plugins.markdown.editor.tables.TableUtils import org.intellij.plugins.markdown.editor.tables.actions.TableActionKeys import org.intellij.plugins.markdown.lang.psi.impl.MarkdownTable /** * Base class for actions operating on a single column. * * Implementations should override performAction and update methods which take current editor, table and column index. * * Could be invoked from two contexts: normally from the editor or from the table inlay toolbar. * In the latter case current column index, and it's parent table are taken from the event's data context (see [TableActionKeys]). * If table and column index are not found in even's data context, then we consider that action was invoked normally * (e.g. from search everywhere) and compute column index and table element based on the position of current caret. * * See [ColumnBasedTableAction.Companion.findTableAndIndex]. */ internal abstract class ColumnBasedTableAction: AnAction() { override fun actionPerformed(event: AnActionEvent) { val editor = event.getRequiredData(CommonDataKeys.EDITOR) val file = event.getRequiredData(CommonDataKeys.PSI_FILE) val (table, columnIndex) = findTableAndIndex(event, file, editor) requireNotNull(table) requireNotNull(columnIndex) performAction(editor, table, columnIndex) } @Suppress("DuplicatedCode") override fun update(event: AnActionEvent) { val project = event.getData(CommonDataKeys.PROJECT) val editor = event.getData(CommonDataKeys.EDITOR) val file = event.getData(CommonDataKeys.PSI_FILE) if (project == null || editor == null || file == null) { event.presentation.isEnabledAndVisible = false return } val (table, columnIndex) = findTableAndIndex(event, file, editor) event.presentation.isEnabledAndVisible = table != null && columnIndex != null update(event, table, columnIndex) } protected abstract fun performAction(editor: Editor, table: MarkdownTable, columnIndex: Int) protected open fun update(event: AnActionEvent, table: MarkdownTable?, columnIndex: Int?) = Unit private fun findTableAndIndex(event: AnActionEvent, file: PsiFile, editor: Editor): Pair<MarkdownTable?, Int?> { return findTableAndIndex(event, file, editor, ::findTable, ::findColumnIndex) } protected open fun findTable(file: PsiFile, editor: Editor): MarkdownTable? { return TableUtils.findTable(file, editor.caretModel.currentCaret.offset) } protected open fun findColumnIndex(file: PsiFile, editor: Editor): Int? { return TableUtils.findCellIndex(file, editor.caretModel.currentCaret.offset) } companion object { fun findTableAndIndex( event: AnActionEvent, file: PsiFile, editor: Editor, tableGetter: (PsiFile, Editor) -> MarkdownTable?, columnIndexGetter: (PsiFile, Editor) -> Int? ): Pair<MarkdownTable?, Int?> { val tableFromEvent = event.getData(TableActionKeys.ELEMENT)?.get() as? MarkdownTable val indexFromEvent = event.getData(TableActionKeys.COLUMN_INDEX) if (tableFromEvent != null && indexFromEvent != null) { return tableFromEvent to indexFromEvent } val table = tableGetter(file, editor)?.takeIf { it.isValid } val index = columnIndexGetter(file, editor) return table to index } fun findTableAndIndex(event: AnActionEvent, file: PsiFile, editor: Editor): Pair<MarkdownTable?, Int?> { return findTableAndIndex( event, file, editor, { file, editor -> TableUtils.findTable(file, editor.caretModel.currentCaret.offset) }, { file, editor -> TableUtils.findCellIndex(file, editor.caretModel.currentCaret.offset) } ) } } }
apache-2.0
5d31375deccaa289cb99831230268308
43.956989
158
0.741928
4.579409
false
false
false
false
dahlstrom-g/intellij-community
plugins/gradle/java/src/service/resolve/GradleProjectReference.kt
12
2764
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.service.resolve import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.model.SingleTargetReference import com.intellij.model.Symbol import com.intellij.model.psi.PsiCompletableReference import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import org.jetbrains.annotations.ApiStatus.Internal import org.jetbrains.plugins.gradle.settings.GradleExtensionsSettings import org.jetbrains.plugins.gradle.settings.GradleExtensionsSettings.GradleProject import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral @Internal class GradleProjectReference( private val myElement: GrLiteral, private val myRange: TextRange, private val myQualifiedName: List<String> ) : SingleTargetReference(), PsiCompletableReference { override fun getElement(): PsiElement = myElement override fun getRangeInElement(): TextRange = myRange override fun resolveSingleTarget(): Symbol? { val gradleProject = GradleExtensionsSettings.getRootProject(myElement) ?: return null val rootProjectPath = GradleExtensionsSettings.getRootProjectPath(myElement) ?: return null if (myQualifiedName.isEmpty()) { return GradleRootProjectSymbol(rootProjectPath) } else if (GradleSubprojectSymbol.qualifiedNameString(myQualifiedName) in gradleProject.extensions) { return GradleSubprojectSymbol(myQualifiedName, rootProjectPath) } return null } /** * This could've been much easier if we could query list of sub-projects by project fqn. */ override fun getCompletionVariants(): Collection<LookupElement> { val gradleProject: GradleProject = GradleExtensionsSettings.getRootProject(myElement) ?: return emptyList() val parentProjectFqn: List<String> = myQualifiedName.dropLast(1) // ["com", "foo", "IntellijIdeaRulezzz "] -> ["com", "foo"] val parentProjectPrefix: String = parentProjectFqn.joinToString(separator = "", postfix = ":") { ":$it" } // ":com:foo:" val result = LinkedHashSet<String>() for (projectFqn in gradleProject.extensions.keys) { // let's say there is ":com:foo:bar:baz" among keys if (!projectFqn.startsWith(parentProjectPrefix)) { continue } val relativeFqn = projectFqn.removePrefix(parentProjectPrefix) // "bar:baz" val childProjectName = relativeFqn.split(':').firstOrNull() // "bar" if (childProjectName.isNullOrEmpty()) { continue } result += childProjectName } return result.map(LookupElementBuilder::create) } }
apache-2.0
910bed916833e30887d01799e2fb749b
45.066667
140
0.76411
4.614357
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantExplicitTypeInspection.kt
1
4277
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.CleanupLocalInspectionTool import com.intellij.codeInspection.IntentionWrapper import com.intellij.codeInspection.ProblemsHolder import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.intentions.RemoveExplicitTypeIntention import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.descriptorUtil.isCompanionObject import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.AbbreviatedType import org.jetbrains.kotlin.types.KotlinType class RedundantExplicitTypeInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = propertyVisitor(fun(property) { val typeReference = property.typeReference ?: return if (hasRedundantType(property)) { holder.registerProblem( typeReference, KotlinBundle.message("explicitly.given.type.is.redundant.here"), IntentionWrapper(RemoveExplicitTypeIntention()) ) } }) companion object { fun hasRedundantType(property: KtProperty): Boolean { if (!property.isLocal) return false val typeReference = property.typeReference ?: return false if (typeReference.annotationEntries.isNotEmpty()) return false val initializer = property.initializer ?: return false val type = property.resolveToDescriptorIfAny()?.type ?: return false if (type is AbbreviatedType) return false when (initializer) { is KtConstantExpression -> { when (initializer.node.elementType) { KtNodeTypes.BOOLEAN_CONSTANT -> { if (!KotlinBuiltIns.isBoolean(type)) return false } KtNodeTypes.INTEGER_CONSTANT -> { if (initializer.text.endsWith("L")) { if (!KotlinBuiltIns.isLong(type)) return false } else { if (!KotlinBuiltIns.isInt(type)) return false } } KtNodeTypes.FLOAT_CONSTANT -> { if (initializer.text.endsWith("f") || initializer.text.endsWith("F")) { if (!KotlinBuiltIns.isFloat(type)) return false } else { if (!KotlinBuiltIns.isDouble(type)) return false } } KtNodeTypes.CHARACTER_CONSTANT -> { if (!KotlinBuiltIns.isChar(type)) return false } else -> return false } } is KtStringTemplateExpression -> { if (!KotlinBuiltIns.isString(type)) return false } is KtNameReferenceExpression -> { if (typeReference.text != initializer.getReferencedName()) return false val initializerType = initializer.getType(property.analyze(BodyResolveMode.PARTIAL)) if (initializerType != type && initializerType.isCompanionObject()) return false } is KtCallExpression -> { if (typeReference.text != initializer.calleeExpression?.text) return false } else -> return false } return true } private fun KotlinType?.isCompanionObject() = this?.constructor?.declarationDescriptor?.isCompanionObject() == true } }
apache-2.0
a8a4b81f42e650d8b4fb6435a30c5302
47.613636
120
0.590367
6.11
false
false
false
false
android/location-samples
LocationUpdatesBackgroundKotlin/app/src/main/java/com/google/android/gms/location/sample/locationupdatesbackgroundkotlin/data/db/MyLocationEntity.kt
2
1501
/* * Copyright (C) 2020 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gms.location.sample.locationupdatesbackgroundkotlin.data.db import androidx.room.Entity import androidx.room.PrimaryKey import java.text.DateFormat import java.util.Date import java.util.UUID /** * Data class for Location related data (only takes what's needed from * {@link android.location.Location} class). */ @Entity(tableName = "my_location_table") data class MyLocationEntity( @PrimaryKey val id: UUID = UUID.randomUUID(), val latitude: Double = 0.0, val longitude: Double = 0.0, val foreground: Boolean = true, val date: Date = Date() ) { override fun toString(): String { val appState = if (foreground) { "in app" } else { "in BG" } return "$latitude, $longitude $appState on " + "${DateFormat.getDateTimeInstance().format(date)}.\n" } }
apache-2.0
3b7d6e1361cddb485bab0dae59a094d3
30.93617
86
0.687542
4.056757
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/notification/NotificationHelper.kt
1
1433
package jp.juggler.subwaytooter.notification import android.annotation.TargetApi import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import jp.juggler.util.LogCategory object NotificationHelper { private val log = LogCategory("NotificationHelper") @TargetApi(26) fun createNotificationChannel( context: Context, channelId: String, // id name: String, // The user-visible name of the channel. description: String?, // The user-visible description of the channel. importance: Int, ): NotificationChannel { val notification_manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager? ?: throw NotImplementedError("missing NotificationManager system service") var channel: NotificationChannel? = null try { channel = notification_manager.getNotificationChannel(channelId) } catch (ex: Throwable) { log.trace(ex) } if (channel == null) { channel = NotificationChannel(channelId, name, importance) } channel.name = name channel.importance = importance if (description != null) channel.description = description notification_manager.createNotificationChannel(channel) return channel } }
apache-2.0
727fe3372d4aea40e74a63b07606c45c
32.95122
90
0.662247
5.532819
false
false
false
false
securityfirst/Umbrella_android
app/src/main/java/org/secfirst/umbrella/feature/search/view/SearchController.kt
1
3066
package org.secfirst.umbrella.feature.search.view import android.app.SearchManager import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import kotlinx.android.synthetic.main.searching_view.* import org.secfirst.advancedsearch.interfaces.AdvancedSearchPresenter import org.secfirst.umbrella.R import org.secfirst.umbrella.UmbrellaApplication import org.secfirst.umbrella.feature.base.view.BaseController import org.secfirst.umbrella.feature.search.DaggerSearchComponent import org.secfirst.umbrella.feature.search.interactor.SearchBaseInteractor import org.secfirst.umbrella.feature.search.presenter.SearchBasePresenter import javax.inject.Inject class SearchController(bundle: Bundle) : BaseController(bundle), SearchView { @Inject internal lateinit var presenter: SearchBasePresenter<SearchView, SearchBaseInteractor> private val query by lazy { args.getString(EXTRA_SEARCH_QUERY) } private lateinit var mainIntentAction: String constructor(query: String = "") : this(Bundle().apply { putString(EXTRA_SEARCH_QUERY, query) }) override fun onInject() { DaggerSearchComponent.builder() .application(UmbrellaApplication.instance) .build() .inject(this) } override fun onAttach(view: View) { super.onAttach(view) setUpToolbar() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle?): View { presenter.onAttach(this) mainActivity.registerSearchProvider(presenter as AdvancedSearchPresenter) mainActivity.intent.action?.let { mainIntentAction = it } presenter.submitSearchQuery(query) mainActivity.hideNavigation() mainActivity.intent.action = Intent.ACTION_SEARCH mainActivity.intent.putExtra(SearchManager.QUERY, query) return inflater.inflate(R.layout.searching_view, container, false) } override fun onDestroyView(view: View) { super.onDestroyView(view) mainActivity.intent.action = mainIntentAction mainActivity.showNavigation() mainActivity.releaseSearchProvider() } override fun handleBack(): Boolean { return super.handleBack() } private fun setUpToolbar() { searchToolbar?.let { it.setTitle(R.string.search_results) it.setNavigationIcon(R.drawable.ic_action_back) it.setNavigationOnClickListener { mainActivity.onBackPressed() } } } companion object { private const val EXTRA_SEARCH_QUERY = "search_query" } }
gpl-3.0
b7d1a9879c3167ffeb1164604bdf4ec2
39.355263
114
0.63666
5.544304
false
false
false
false
BenAlderfer/percent-calculatorv2
app/src/main/java/com/alderferstudios/percentcalculatorv2/fragment/PercentFragment.kt
1
7229
package com.alderferstudios.percentcalculatorv2.fragment import android.content.Intent import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.util.Log import android.view.* import android.widget.EditText import android.widget.SeekBar import com.alderferstudios.percentcalculatorv2.R import com.alderferstudios.percentcalculatorv2.activity.BaseActivity import com.alderferstudios.percentcalculatorv2.util.PrefConstants import com.alderferstudios.percentcalculatorv2.widget.NumPicker import com.alderferstudios.percentcalculatorv2.widget.PercentLimitPopUp /** * Percent screen */ class PercentFragment : BaseFragment(), SeekBar.OnSeekBarChangeListener { private var percentage: EditText? = null private var percent: Int = 15 private var percentStart: Int = 15 private var percentMax: Int = 30 private var numPick: NumPicker? = null private var bar: SeekBar? = null private val needsToRestart: Boolean = false override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_percent, container, false) } override fun onStart() { super.onStart() val base = getBaseActivity() base.buttons.add(activity?.findViewById(R.id.tip)) base.buttons.add(activity?.findViewById(R.id.split)) base.buttons.add(activity?.findViewById(R.id.discount)) bar = activity?.findViewById(R.id.percentBar) bar?.setOnSeekBarChangeListener(this) applyPrefs() percentage = activity?.findViewById(R.id.percentNum) percentage?.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable) { val percentText = percentage?.text.toString() if (percentText != "" && percentText.toInt() <= percentMax && percentText.toInt() >= percentStart) { //only update bar if its within the limits if (percentText == "") { bar?.progress = percentStart } else { bar?.progress = percentage?.text.toString().toInt() - percentStart } percentage?.setSelection(percentage?.text?.length ?: 0) //returns focus to end of text } } override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {} }) } override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { inflater?.inflate(R.menu.menu_percent, menu) super.onCreateOptionsMenu(menu, inflater) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item?.itemId) { R.id.split_options -> startActivity(Intent(activity, PercentLimitPopUp::class.java)) } return true } /** * Applies preference settings */ private fun applyPrefs() { try { percentStart = (activity as BaseActivity).shared?.getString(PrefConstants.PERCENT_START, getString(R.string.default_min_percent))?.toInt() ?: getString(R.string.default_min_percent).toInt() percent = percentStart } catch (e: NullPointerException) { Log.e("failure", "failed to get start percent") e.printStackTrace() } try { percentMax = (activity as BaseActivity).shared?.getString(PrefConstants.PERCENT_MAX, getString(R.string.default_max_percent))?.toInt() ?: getString(R.string.default_max_percent).toInt() } catch (e: NullPointerException) { Log.e("failure", "failed to get max percent") e.printStackTrace() } //set percent bar max if (bar?.max != percentMax) { bar?.max = percentMax - percentStart } if (activity?.findViewById<View>(R.id.numPicker) != null) { //fills in last or default value for split picker if it is there activity?.findViewById<NumPicker>(R.id.numPicker)?.value = 4 } } /** * Restarts the activity if one of the limits was changed * @param sharedPreferences the shared prefs * @param key the name of the pref */ /*@Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals("percentStart") || key.equals("percentMax")) needsToRestart = true; }*/ /** * Checks if the percent input is wrong * Looks to see if it is greater or less than a limit * * @return true if it exceeds a limit; false otherwise */ // private fun percentIsWrong(): Boolean { // var percentText = percentage?.text.toString() // if (percentText == "") { //updates bar if nothing was entered // bar?.progress = percentStart // percentage?.setText(percentStart) // percentText = percentage?.text.toString() // } // // if (percentText.toInt() > percentMax) { // percentage?.setText(percentMax) // MiscUtil.showToast(activity as Context, "The percent cannot be greater than the max percent") // return true // } else if (percentText.toInt() < percentStart) { // percentage?.setText(percentStart) // MiscUtil.showToast(activity as Context, "The percent cannot be less than the start percent") // return true // } // return false // } /** * Updates the percent text as the bar changes */ override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { // if (didJustTypePercent) { // didJustTypePercent = false // } else { // imm?.hideSoftInputFromWindow(splitBox?.windowToken, 0) //hides keyboard if not typing // } percent = progress + percentStart if (percent > percentMax) { percent = percentMax } percentage?.setText(percent.toString()) } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} /** * Checks if the percent input is wrong * Looks to see if it is greater or less than a limit * * @return true if it exceeds a limit; false otherwise */ private fun resetAfterPrefChange() { //TODO: check this var percentText = percentage?.text.toString() if (percentText == "") { //updates bar if nothing was entered bar?.progress = percentStart percentage?.setText(percentStart) percentText = percentage?.text.toString() } if (percentText.toInt() > percentMax) { percentage?.setText(percentMax) } else if (percentText.toInt() < percentStart) { percentage?.setText(percentStart) } } override fun fieldsAreValid(): Boolean { return percent > 0 } }
gpl-3.0
01dfde5c5c126ad5636b56e5989e8163
35.515152
135
0.620556
4.631006
false
false
false
false
aahlenst/spring-boot
spring-boot-project/spring-boot-docs/src/main/kotlin/org/springframework/boot/docs/data/sql/jpaandspringdata/entityclasses/City.kt
10
1405
/* * Copyright 2012-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 org.springframework.boot.docs.data.sql.jpaandspringdata.entityclasses import jakarta.persistence.Column import jakarta.persistence.Entity import jakarta.persistence.GeneratedValue import jakarta.persistence.Id import java.io.Serializable @Entity class City : Serializable { @Id @GeneratedValue private val id: Long? = null @Column(nullable = false) var name: String? = null private set // ... etc @Column(nullable = false) var state: String? = null private set // ... additional members, often include @OneToMany mappings protected constructor() { // no-args constructor required by JPA spec // this one is protected since it should not be used directly } constructor(name: String?, state: String?) { this.name = name this.state = state } }
apache-2.0
7762f3e4381f674bf431b689e22fd491
25.528302
77
0.741637
3.902778
false
false
false
false
dzharkov/intellij-markdown
src/org/intellij/markdown/MarkdownElementTypes.kt
1
2525
package org.intellij.markdown public interface MarkdownElementTypes { companion object { public val MARKDOWN_FILE: IElementType = MarkdownElementType("MARKDOWN_FILE") public val UNORDERED_LIST: IElementType = MarkdownElementType("UNORDERED_LIST") public val ORDERED_LIST: IElementType = MarkdownElementType("ORDERED_LIST") public val LIST_ITEM: IElementType = MarkdownElementType("LIST_ITEM") public val BLOCK_QUOTE: IElementType = MarkdownElementType("BLOCK_QUOTE") public val CODE_FENCE: IElementType = MarkdownElementType("CODE_FENCE") public val CODE_BLOCK: IElementType = MarkdownElementType("CODE_BLOCK", true) public val CODE_SPAN: IElementType = MarkdownElementType("CODE_SPAN") public val HTML_BLOCK: IElementType = MarkdownElementType("HTML_BLOCK") public val PARAGRAPH: IElementType = MarkdownElementType("PARAGRAPH", true) public val EMPH: IElementType = MarkdownElementType("EMPH") public val STRONG: IElementType = MarkdownElementType("STRONG") public val LINK_DEFINITION: IElementType = MarkdownElementType("LINK_DEFINITION") public val LINK_LABEL: IElementType = MarkdownElementType("LINK_LABEL", true) public val LINK_DESTINATION: IElementType = MarkdownElementType("LINK_DESTINATION", true) public val LINK_TITLE: IElementType = MarkdownElementType("LINK_TITLE", true) public val LINK_TEXT: IElementType = MarkdownElementType("LINK_TEXT", true) public val INLINE_LINK: IElementType = MarkdownElementType("INLINE_LINK") public val FULL_REFERENCE_LINK: IElementType = MarkdownElementType("FULL_REFERENCE_LINK") public val SHORT_REFERENCE_LINK: IElementType = MarkdownElementType("SHORT_REFERENCE_LINK") public val IMAGE: IElementType = MarkdownElementType("IMAGE") public val AUTOLINK: IElementType = MarkdownElementType("AUTOLINK") public val SETEXT_1: IElementType = MarkdownElementType("SETEXT_1") public val SETEXT_2: IElementType = MarkdownElementType("SETEXT_2") public val ATX_1: IElementType = MarkdownElementType("ATX_1") public val ATX_2: IElementType = MarkdownElementType("ATX_2") public val ATX_3: IElementType = MarkdownElementType("ATX_3") public val ATX_4: IElementType = MarkdownElementType("ATX_4") public val ATX_5: IElementType = MarkdownElementType("ATX_5") public val ATX_6: IElementType = MarkdownElementType("ATX_6") } }
apache-2.0
7bd1ba8ca96b1086823340d297195e74
48.509804
99
0.72
4.855769
false
false
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/ide/util/TipAndTrickManager.kt
2
1910
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.util import com.intellij.ide.GeneralSettings import com.intellij.openapi.Disposable import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Key import com.intellij.ui.GotItTooltipService import org.jetbrains.annotations.ApiStatus @ApiStatus.Internal @Service class TipAndTrickManager { private var openedDialog: TipDialog? = null fun showTipDialog(project: Project) = showTipDialog(project, TipAndTrickBean.EP_NAME.extensionList) /** * Show the dialog with one tip without "Next tip" and "Previous tip" buttons */ fun showTipDialog(project: Project, tip: TipAndTrickBean) = showTipDialog(project, listOf(tip)) private fun showTipDialog(project: Project, tips: List<TipAndTrickBean>) { closeTipDialog() openedDialog = TipDialog(project, tips).also { dialog -> Disposer.register(dialog.disposable, Disposable { openedDialog = null }) // clear link to not leak the project dialog.show() } } fun closeTipDialog() { openedDialog?.close(DialogWrapper.OK_EXIT_CODE) } fun canShowDialogAutomaticallyNow(project: Project): Boolean { return GeneralSettings.getInstance().isShowTipsOnStartup && !DISABLE_TIPS_FOR_PROJECT.get(project, false) && !GotItTooltipService.getInstance().isFirstRun && openedDialog?.isVisible != true && !TipsUsageManager.getInstance().wereTipsShownToday() } companion object { val DISABLE_TIPS_FOR_PROJECT = Key.create<Boolean>("DISABLE_TIPS_FOR_PROJECT") @JvmStatic fun getInstance(): TipAndTrickManager = service() } }
apache-2.0
ccf19f2f728825f7682bbb0f815cb2f4
35.056604
120
0.750262
4.152174
false
false
false
false