repo_name
stringlengths
7
81
path
stringlengths
4
242
copies
stringclasses
95 values
size
stringlengths
1
6
content
stringlengths
3
991k
license
stringclasses
15 values
jwren/intellij-community
plugins/grazie/src/main/kotlin/com/intellij/grazie/ide/fus/GrazieFUSState.kt
1
4545
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.grazie.ide.fus import com.intellij.grazie.GrazieConfig import com.intellij.grazie.config.CheckingContext import com.intellij.grazie.detector.model.LanguageISO import com.intellij.grazie.ide.ui.grammar.tabs.rules.component.allRules import com.intellij.internal.statistic.beans.MetricEvent import com.intellij.internal.statistic.beans.newMetric import com.intellij.internal.statistic.collectors.fus.LangCustomRuleValidator import com.intellij.internal.statistic.collectors.fus.PluginInfoValidationRule import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.FeatureUsageData import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.eventLog.events.StringEventField import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector import com.intellij.internal.statistic.utils.getPluginInfo internal class GrazieFUSState : ApplicationUsagesCollector() { override fun getGroup(): EventLogGroup { return GROUP } override fun getMetrics(): Set<MetricEvent> { val metrics = HashSet<MetricEvent>() val state = GrazieConfig.get() for (lang in state.enabledLanguages) { metrics.add(ENABLE_LANGUAGE.metric(lang.iso)) } val allRules by lazy { allRules().values.flatten().groupBy { it.globalId } } fun logRule(id: String, enabled: Boolean) { val rule = allRules[id]?.firstOrNull() ?: return metrics.add(RULE.metric(getPluginInfo(rule.javaClass), id, enabled)) } state.userEnabledRules.forEach { logRule(it, enabled = true) } state.userDisabledRules.forEach { logRule(it, enabled = false) } val checkingContext = state.checkingContext for (id in checkingContext.disabledLanguages) { metrics.add(CHECKING_CONTEXT.metric(LANGUAGE_FIELD.with(id), USER_CHANGE_FIELD.with("disabled"))) } for (id in checkingContext.enabledLanguages) { metrics.add(CHECKING_CONTEXT.metric(LANGUAGE_FIELD.with(id), USER_CHANGE_FIELD.with("enabled"))) } val defaults = CheckingContext() fun checkDomain(name: StringEventField, isEnabled: (CheckingContext) -> Boolean) { if (isEnabled(defaults) != isEnabled(checkingContext)) { metrics.add(CHECKING_CONTEXT.metric(name.with(if (isEnabled(checkingContext)) "enabled" else "disabled"))) } } checkDomain(DOCUMENTATION_FIELD) { it.isCheckInDocumentationEnabled } checkDomain(COMMENTS_FIELD) { it.isCheckInCommentsEnabled } checkDomain(LITERALS_FIELD) { it.isCheckInStringLiteralsEnabled } checkDomain(COMMIT_FIELD) { it.isCheckInCommitMessagesEnabled } return metrics } companion object { private val GROUP = EventLogGroup("grazie.state", 6) private val ENABLE_LANGUAGE = GROUP.registerEvent("enabled.language", EventFields.Enum("value", LanguageISO::class.java) { it.name.lowercase() }) private val RULE = GROUP.registerEvent("rule", EventFields.PluginInfo, EventFields.StringValidatedByCustomRule("id", PluginInfoValidationRule::class.java), EventFields.Enabled) private val DOCUMENTATION_FIELD = EventFields.StringValidatedByEnum("documentation", "state") private val COMMENTS_FIELD = EventFields.StringValidatedByEnum("comments", "state") private val LITERALS_FIELD = EventFields.StringValidatedByEnum("literals", "state") private val COMMIT_FIELD = EventFields.StringValidatedByEnum("commit", "state") private val USER_CHANGE_FIELD = EventFields.StringValidatedByEnum("userChange", "state") private val LANGUAGE_FIELD = EventFields.StringValidatedByCustomRule("language", LangCustomRuleValidator::class.java) private val CHECKING_CONTEXT = GROUP.registerVarargEvent("checkingContext", LANGUAGE_FIELD, USER_CHANGE_FIELD, DOCUMENTATION_FIELD, COMMENTS_FIELD, LITERALS_FIELD, COMMIT_FIELD) } }
apache-2.0
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/intentions/convertLambdaToReference/receiverParameterReversed.kt
13
102
// IS_APPLICABLE: false fun Int.foo(x: Int) = this - x val x = { a: Int, b: Int <caret>-> b.foo(a) }
apache-2.0
androidx/androidx
datastore/datastore-core/src/commonMain/kotlin/androidx/datastore/core/DataStore.kt
3
3026
/* * 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.datastore.core import kotlinx.coroutines.flow.Flow /** * DataStore provides a safe and durable way to store small amounts of data, such as preferences * and application state. It does not support partial updates: if any field is modified, the whole * object will be serialized and persisted to disk. If you want partial updates, consider the Room * API (SQLite). * * DataStore provides ACID guarantees. It is thread-safe, and non-blocking. In particular, it * addresses these design shortcomings of the SharedPreferences API: * * 1. Synchronous API encourages StrictMode violations * 2. apply() and commit() have no mechanism of signalling errors * 3. apply() will block the UI thread on fsync() * 4. Not durable โ€“ it can returns state that is not yet persisted * 5. No consistency or transactional semantics * 6. Throws runtime exception on parsing errors * 7. Exposes mutable references to its internal state */ public interface DataStore<T> { /** * Provides efficient, cached (when possible) access to the latest durably persisted state. * The flow will always either emit a value or throw an exception encountered when attempting * to read from disk. If an exception is encountered, collecting again will attempt to read the * data again. * * Do not layer a cache on top of this API: it will be be impossible to guarantee consistency. * Instead, use data.first() to access a single snapshot. * * @return a flow representing the current state of the data * @throws IOException when an exception is encountered when reading data */ public val data: Flow<T> /** * Updates the data transactionally in an atomic read-modify-write operation. All operations * are serialized, and the transform itself is a coroutine so it can perform heavy work * such as RPCs. * * The coroutine completes when the data has been persisted durably to disk (after which * [data] will reflect the update). If the transform or write to disk fails, the * transaction is aborted and an exception is thrown. * * @return the snapshot returned by the transform * @throws IOException when an exception is encountered when writing data to disk * @throws Exception when thrown by the transform function */ public suspend fun updateData(transform: suspend (t: T) -> T): T }
apache-2.0
androidx/androidx
compose/ui/ui-test/src/test/kotlin/androidx/compose/ui/test/inputdispatcher/TouchEventsTest.kt
3
28369
/* * 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.test.inputdispatcher import android.view.MotionEvent.ACTION_CANCEL import android.view.MotionEvent.ACTION_DOWN import android.view.MotionEvent.ACTION_MOVE import android.view.MotionEvent.ACTION_POINTER_DOWN import android.view.MotionEvent.ACTION_POINTER_UP import android.view.MotionEvent.ACTION_UP import androidx.compose.testutils.expectError import androidx.compose.ui.geometry.Offset import androidx.compose.ui.test.AndroidInputDispatcher import androidx.compose.ui.test.InputDispatcher.Companion.eventPeriodMillis import androidx.compose.ui.test.RobolectricMinSdk import androidx.compose.ui.test.util.assertHasValidEventTimes import androidx.compose.ui.test.util.assertNoTouchGestureInProgress import androidx.compose.ui.test.util.verifyTouchEvent import androidx.compose.ui.test.util.verifyTouchPointer import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.robolectric.annotation.Config /** * Tests if [AndroidInputDispatcher.enqueueTouchDown] and friends work. */ @RunWith(AndroidJUnit4::class) @Config(minSdk = RobolectricMinSdk) class TouchEventsTest : InputDispatcherTest() { companion object { // Pointer ids private const val pointer1 = 11 private const val pointer2 = 22 private const val pointer3 = 33 private const val pointer4 = 44 // Positions, mostly used with corresponding pointerId: // pointerX with positionX or positionX_Y private val position1 = Offset(1f, 1f) private val position2 = Offset(2f, 2f) private val position3 = Offset(3f, 3f) private val position4 = Offset(4f, 4f) private val position1_1 = Offset(11f, 11f) private val position2_1 = Offset(21f, 21f) private val position3_1 = Offset(31f, 31f) private val position1_2 = Offset(12f, 12f) private val position2_2 = Offset(22f, 22f) private val position1_3 = Offset(13f, 13f) } @Test fun onePointer_down() { subject.generateTouchDownAndCheck(pointer1, position1) subject.flush() val t = 0L recorder.assertHasValidEventTimes() assertThat(recorder.events).hasSize(1) recorder.events[0].verifyTouchEvent(1, ACTION_DOWN, 0, t) // pointer1 recorder.events[0].verifyTouchPointer(pointer1, position1) } @Test fun onePointer_downUp() { subject.generateTouchDownAndCheck(pointer1, position1) subject.generateTouchUpAndCheck(pointer1) subject.assertNoTouchGestureInProgress() subject.flush() recorder.assertHasValidEventTimes() recorder.events.apply { val t = 0L assertThat(this).hasSize(2) this[0].verifyTouchEvent(1, ACTION_DOWN, 0, t) // pointer1 this[0].verifyTouchPointer(pointer1, position1) this[1].verifyTouchEvent(1, ACTION_UP, 0, t) // pointer1 this[1].verifyTouchPointer(pointer1, position1) } } @Test fun onePointer_downDelayUp() { subject.generateTouchDownAndCheck(pointer1, position1_1) subject.generateTouchUpAndCheck(pointer1, 2 * eventPeriodMillis) subject.assertNoTouchGestureInProgress() subject.flush() recorder.assertHasValidEventTimes() recorder.events.apply { var t = 0L assertThat(this).hasSize(2) this[0].verifyTouchEvent(1, ACTION_DOWN, 0, t) // pointer1 this[0].verifyTouchPointer(pointer1, position1_1) t += 2 * eventPeriodMillis this[1].verifyTouchEvent(1, ACTION_UP, 0, t) // pointer1 this[1].verifyTouchPointer(pointer1, position1_1) } } @Test fun onePointer_downUpdateMove() { subject.generateTouchDownAndCheck(pointer1, position1_1) subject.updateTouchPointerAndCheck(pointer1, position1_2) subject.advanceEventTime() subject.enqueueTouchMove() subject.flush() var t = 0L recorder.assertHasValidEventTimes() assertThat(recorder.events).hasSize(2) recorder.events[0].verifyTouchEvent(1, ACTION_DOWN, 0, t) // pointer1 recorder.events[0].verifyTouchPointer(pointer1, position1_1) t += eventPeriodMillis recorder.events[1].verifyTouchEvent(1, ACTION_MOVE, 0, t) // pointer1 recorder.events[1].verifyTouchPointer(pointer1, position1_2) } @Test fun onePointer_downCancel() { subject.generateTouchDownAndCheck(pointer1, position1_1) subject.advanceEventTime() subject.generateCancelAndCheckPointers() subject.assertNoTouchGestureInProgress() subject.flush() recorder.assertHasValidEventTimes() recorder.events.apply { var t = 0L assertThat(this).hasSize(2) this[0].verifyTouchEvent(1, ACTION_DOWN, 0, t) // pointer1 this[0].verifyTouchPointer(pointer1, position1_1) t += eventPeriodMillis this[1].verifyTouchEvent(1, ACTION_CANCEL, 0, t) this[1].verifyTouchPointer(pointer1, position1_1) } } @Test fun twoPointers_downDownMoveMove() { // 2 fingers, both go down before they move subject.generateTouchDownAndCheck(pointer1, position1_1) subject.generateTouchDownAndCheck(pointer2, position2_1) subject.updateTouchPointerAndCheck(pointer1, position1_2) subject.advanceEventTime() subject.enqueueTouchMove() subject.updateTouchPointerAndCheck(pointer2, position2_2) subject.advanceEventTime() subject.enqueueTouchMove() subject.flush() recorder.assertHasValidEventTimes() recorder.events.apply { var t = 0L assertThat(this).hasSize(4) this[0].verifyTouchEvent(1, ACTION_DOWN, 0, t) // pointer1 this[0].verifyTouchPointer(pointer1, position1_1) this[1].verifyTouchEvent(2, ACTION_POINTER_DOWN, 1, t) // pointer2 this[1].verifyTouchPointer(pointer1, position1_1) this[1].verifyTouchPointer(pointer2, position2_1) t += eventPeriodMillis this[2].verifyTouchEvent(2, ACTION_MOVE, 0, t) this[2].verifyTouchPointer(pointer1, position1_2) this[2].verifyTouchPointer(pointer2, position2_1) t += eventPeriodMillis this[3].verifyTouchEvent(2, ACTION_MOVE, 0, t) this[3].verifyTouchPointer(pointer1, position1_2) this[3].verifyTouchPointer(pointer2, position2_2) } } @Test fun twoPointers_downMoveDownMove() { // 2 fingers, 1st finger moves before 2nd finger goes down and moves subject.generateTouchDownAndCheck(pointer1, position1_1) subject.updateTouchPointerAndCheck(pointer1, position1_2) subject.advanceEventTime() subject.enqueueTouchMove() subject.generateTouchDownAndCheck(pointer2, position2_1) subject.updateTouchPointerAndCheck(pointer2, position2_2) subject.advanceEventTime() subject.enqueueTouchMove() subject.flush() recorder.assertHasValidEventTimes() recorder.events.apply { var t = 0L assertThat(this).hasSize(4) this[0].verifyTouchEvent(1, ACTION_DOWN, 0, t) // pointer1 this[0].verifyTouchPointer(pointer1, position1_1) t += eventPeriodMillis this[1].verifyTouchEvent(1, ACTION_MOVE, 0, t) this[1].verifyTouchPointer(pointer1, position1_2) this[2].verifyTouchEvent(2, ACTION_POINTER_DOWN, 1, t) // pointer2 this[2].verifyTouchPointer(pointer1, position1_2) this[2].verifyTouchPointer(pointer2, position2_1) t += eventPeriodMillis this[3].verifyTouchEvent(2, ACTION_MOVE, 0, t) this[3].verifyTouchPointer(pointer1, position1_2) this[3].verifyTouchPointer(pointer2, position2_2) } } @Test fun twoPointers_moveSimultaneously() { // 2 fingers, use [updateTouchPointer] and [enqueueTouchMove] subject.generateTouchDownAndCheck(pointer1, position1_1) subject.generateTouchDownAndCheck(pointer2, position2_1) subject.updateTouchPointerAndCheck(pointer1, position1_2) subject.updateTouchPointerAndCheck(pointer2, position2_2) subject.advanceEventTime() subject.enqueueTouchMove() subject.flush() recorder.assertHasValidEventTimes() recorder.events.apply { var t = 0L assertThat(this).hasSize(3) this[0].verifyTouchEvent(1, ACTION_DOWN, 0, t) // pointer1 this[0].verifyTouchPointer(pointer1, position1_1) this[1].verifyTouchEvent(2, ACTION_POINTER_DOWN, 1, t) // pointer2 this[1].verifyTouchPointer(pointer1, position1_1) this[1].verifyTouchPointer(pointer2, position2_1) t += eventPeriodMillis this[2].verifyTouchEvent(2, ACTION_MOVE, 0, t) this[2].verifyTouchPointer(pointer1, position1_2) this[2].verifyTouchPointer(pointer2, position2_2) } } @Test fun twoPointers_downUp_sameOrder() { subject.generateTouchDownAndCheck(pointer1, position1_1) subject.generateTouchDownAndCheck(pointer2, position2_1) subject.generateTouchUpAndCheck(pointer2) subject.generateTouchUpAndCheck(pointer1) subject.assertNoTouchGestureInProgress() subject.flush() recorder.assertHasValidEventTimes() recorder.events.apply { val t = 0L assertThat(this).hasSize(4) this[0].verifyTouchEvent(1, ACTION_DOWN, 0, t) // pointer1 this[0].verifyTouchPointer(pointer1, position1_1) this[1].verifyTouchEvent(2, ACTION_POINTER_DOWN, 1, t) // pointer2 this[1].verifyTouchPointer(pointer1, position1_1) this[1].verifyTouchPointer(pointer2, position2_1) this[2].verifyTouchEvent(2, ACTION_POINTER_UP, 1, t) // pointer2 this[2].verifyTouchPointer(pointer1, position1_1) this[2].verifyTouchPointer(pointer2, position2_1) this[3].verifyTouchEvent(1, ACTION_UP, 0, t) // pointer1 this[3].verifyTouchPointer(pointer1, position1_1) } } @Test fun twoPointers_downUp_inverseOrder() { subject.generateTouchDownAndCheck(pointer1, position1_1) subject.generateTouchDownAndCheck(pointer2, position2_1) subject.generateTouchUpAndCheck(pointer1) subject.generateTouchUpAndCheck(pointer2) subject.assertNoTouchGestureInProgress() subject.flush() recorder.assertHasValidEventTimes() recorder.events.apply { val t = 0L assertThat(this).hasSize(4) this[0].verifyTouchEvent(1, ACTION_DOWN, 0, t) // pointer1 this[0].verifyTouchPointer(pointer1, position1_1) this[1].verifyTouchEvent(2, ACTION_POINTER_DOWN, 1, t) // pointer2 this[1].verifyTouchPointer(pointer1, position1_1) this[1].verifyTouchPointer(pointer2, position2_1) this[2].verifyTouchEvent(2, ACTION_POINTER_UP, 0, t) // pointer1 this[2].verifyTouchPointer(pointer1, position1_1) this[2].verifyTouchPointer(pointer2, position2_1) this[3].verifyTouchEvent(1, ACTION_UP, 0, t) // pointer2 this[3].verifyTouchPointer(pointer2, position2_1) } } @Test fun twoPointers_downDownCancel() { subject.generateTouchDownAndCheck(pointer1, position1_1) subject.generateTouchDownAndCheck(pointer2, position2_1) subject.advanceEventTime() subject.generateCancelAndCheckPointers() subject.assertNoTouchGestureInProgress() subject.flush() recorder.assertHasValidEventTimes() recorder.events.apply { var t = 0L assertThat(this).hasSize(3) this[0].verifyTouchEvent(1, ACTION_DOWN, 0, t) // pointer1 this[0].verifyTouchPointer(pointer1, position1_1) this[1].verifyTouchEvent(2, ACTION_POINTER_DOWN, 1, t) // pointer2 this[1].verifyTouchPointer(pointer1, position1_1) this[1].verifyTouchPointer(pointer2, position2_1) t += eventPeriodMillis this[2].verifyTouchEvent(2, ACTION_CANCEL, 0, t) this[2].verifyTouchPointer(pointer1, position1_1) this[2].verifyTouchPointer(pointer2, position2_1) } } @Test fun threePointers_notSimultaneously() { // 3 fingers, where the 1st finger goes up before the 3rd finger goes down (no overlap) subject.generateTouchDownAndCheck(pointer1, position1) subject.generateTouchDownAndCheck(pointer2, position2) subject.advanceEventTime() subject.enqueueTouchMove() subject.generateTouchUpAndCheck(pointer1) subject.advanceEventTime() subject.enqueueTouchMove() subject.generateTouchDownAndCheck(pointer3, position3) subject.flush() recorder.assertHasValidEventTimes() recorder.events.apply { var t = 0L assertThat(this).hasSize(6) this[0].verifyTouchEvent(1, ACTION_DOWN, 0, t) // pointer1 this[0].verifyTouchPointer(pointer1, position1) this[1].verifyTouchEvent(2, ACTION_POINTER_DOWN, 1, t) // pointer2 this[1].verifyTouchPointer(pointer1, position1) this[1].verifyTouchPointer(pointer2, position2) t += eventPeriodMillis this[2].verifyTouchEvent(2, ACTION_MOVE, 0, t) this[2].verifyTouchPointer(pointer1, position1) this[2].verifyTouchPointer(pointer2, position2) this[3].verifyTouchEvent(2, ACTION_POINTER_UP, 0, t) // pointer1 this[3].verifyTouchPointer(pointer1, position1) this[3].verifyTouchPointer(pointer2, position2) t += eventPeriodMillis this[4].verifyTouchEvent(1, ACTION_MOVE, 0, t) this[4].verifyTouchPointer(pointer2, position2) this[5].verifyTouchEvent(2, ACTION_POINTER_DOWN, 1, t) // pointer3 this[5].verifyTouchPointer(pointer2, position2) this[5].verifyTouchPointer(pointer3, position3) } } @Test fun threePointers_pointerIdReuse() { // 3 fingers, where the 1st finger goes up before the 3rd finger goes down, and the 3rd // fingers reuses the pointerId of finger 1 subject.generateTouchDownAndCheck(pointer1, position1) subject.generateTouchDownAndCheck(pointer2, position2) subject.advanceEventTime() subject.enqueueTouchMove() subject.generateTouchUpAndCheck(pointer1) subject.advanceEventTime() subject.enqueueTouchMove() subject.generateTouchDownAndCheck(pointer1, position1_2) subject.flush() recorder.assertHasValidEventTimes() recorder.events.apply { var t = 0L assertThat(this).hasSize(6) this[0].verifyTouchEvent(1, ACTION_DOWN, 0, t) // pointer1 this[0].verifyTouchPointer(pointer1, position1) this[1].verifyTouchEvent(2, ACTION_POINTER_DOWN, 1, t) // pointer2 this[1].verifyTouchPointer(pointer1, position1) this[1].verifyTouchPointer(pointer2, position2) t += eventPeriodMillis this[2].verifyTouchEvent(2, ACTION_MOVE, 0, t) this[2].verifyTouchPointer(pointer1, position1) this[2].verifyTouchPointer(pointer2, position2) this[3].verifyTouchEvent(2, ACTION_POINTER_UP, 0, t) // pointer1 this[3].verifyTouchPointer(pointer1, position1) this[3].verifyTouchPointer(pointer2, position2) t += eventPeriodMillis this[4].verifyTouchEvent(1, ACTION_MOVE, 0, t) this[4].verifyTouchPointer(pointer2, position2) this[5].verifyTouchEvent(2, ACTION_POINTER_DOWN, 0, t) // pointer1 this[5].verifyTouchPointer(pointer1, position1_2) this[5].verifyTouchPointer(pointer2, position2) } } @Test fun fourPointers_downOnly() { subject.generateTouchDownAndCheck(pointer3, position3) subject.generateTouchDownAndCheck(pointer1, position1) subject.generateTouchDownAndCheck(pointer4, position4) subject.generateTouchDownAndCheck(pointer2, position2) subject.flush() recorder.assertHasValidEventTimes() recorder.events.apply { val t = 0L assertThat(this).hasSize(4) this[0].verifyTouchEvent(1, ACTION_DOWN, 0, t) // pointer3 this[0].verifyTouchPointer(pointer3, position3) this[1].verifyTouchEvent(2, ACTION_POINTER_DOWN, 0, t) // pointer1 this[1].verifyTouchPointer(pointer1, position1) this[1].verifyTouchPointer(pointer3, position3) this[2].verifyTouchEvent(3, ACTION_POINTER_DOWN, 2, t) // pointer4 this[2].verifyTouchPointer(pointer1, position1) this[2].verifyTouchPointer(pointer3, position3) this[2].verifyTouchPointer(pointer4, position4) this[3].verifyTouchEvent(4, ACTION_POINTER_DOWN, 1, t) // pointer2 this[3].verifyTouchPointer(pointer1, position1) this[3].verifyTouchPointer(pointer2, position2) this[3].verifyTouchPointer(pointer3, position3) this[3].verifyTouchPointer(pointer4, position4) } } @Test fun fourPointers_downWithMove() { // 4 fingers, going down at different times subject.generateTouchDownAndCheck(pointer3, position3) subject.advanceEventTime() subject.enqueueTouchMove() subject.generateTouchDownAndCheck(pointer1, position1) subject.generateTouchDownAndCheck(pointer2, position2) subject.advanceEventTime() subject.enqueueTouchMove() subject.advanceEventTime() subject.enqueueTouchMove() subject.advanceEventTime() subject.enqueueTouchMove() subject.generateTouchDownAndCheck(pointer4, position4) subject.flush() recorder.assertHasValidEventTimes() recorder.events.apply { var t = 0L assertThat(this).hasSize(8) this[0].verifyTouchEvent(1, ACTION_DOWN, 0, t) // pointer3 this[0].verifyTouchPointer(pointer3, position3) t += eventPeriodMillis this[1].verifyTouchEvent(1, ACTION_MOVE, 0, t) this[1].verifyTouchPointer(pointer3, position3) this[2].verifyTouchEvent(2, ACTION_POINTER_DOWN, 0, t) // pointer1 this[2].verifyTouchPointer(pointer1, position1) this[2].verifyTouchPointer(pointer3, position3) this[3].verifyTouchEvent(3, ACTION_POINTER_DOWN, 1, t) // pointer2 this[3].verifyTouchPointer(pointer1, position1) this[3].verifyTouchPointer(pointer2, position2) this[3].verifyTouchPointer(pointer3, position3) for (i in 4..6) { t += eventPeriodMillis this[i].verifyTouchEvent(3, ACTION_MOVE, 0, t) this[i].verifyTouchPointer(pointer1, position1) this[i].verifyTouchPointer(pointer2, position2) this[i].verifyTouchPointer(pointer3, position3) } this[7].verifyTouchEvent(4, ACTION_POINTER_DOWN, 3, t) // pointer4 this[7].verifyTouchPointer(pointer1, position1) this[7].verifyTouchPointer(pointer2, position2) this[7].verifyTouchPointer(pointer3, position3) this[7].verifyTouchPointer(pointer4, position4) } } @Test fun enqueueTouchDown_flushesPointerMovement() { // Movement from [updateTouchPointer] that hasn't been sent will be sent when sending DOWN subject.generateTouchDownAndCheck(pointer1, position1_1) subject.generateTouchDownAndCheck(pointer2, position2_1) subject.updateTouchPointerAndCheck(pointer1, position1_2) subject.updateTouchPointerAndCheck(pointer1, position1_3) subject.advanceEventTime() subject.generateTouchDownAndCheck(pointer3, position3_1) subject.flush() recorder.assertHasValidEventTimes() recorder.events.apply { var t = 0L assertThat(this).hasSize(4) this[0].verifyTouchEvent(1, ACTION_DOWN, 0, t) // pointer1 this[0].verifyTouchPointer(pointer1, position1_1) this[1].verifyTouchEvent(2, ACTION_POINTER_DOWN, 1, t) // pointer2 this[1].verifyTouchPointer(pointer1, position1_1) this[1].verifyTouchPointer(pointer2, position2_1) t += eventPeriodMillis this[2].verifyTouchEvent(2, ACTION_MOVE, 0, t) this[2].verifyTouchPointer(pointer1, position1_3) this[2].verifyTouchPointer(pointer2, position2_1) this[3].verifyTouchEvent(3, ACTION_POINTER_DOWN, 2, t) // pointer2 this[3].verifyTouchPointer(pointer1, position1_3) this[3].verifyTouchPointer(pointer2, position2_1) this[3].verifyTouchPointer(pointer3, position3_1) } } @Test fun enqueueTouchUp_flushesPointerMovement() { // Movement from [updateTouchPointer] that hasn't been sent will be sent when sending UP subject.generateTouchDownAndCheck(pointer1, position1_1) subject.generateTouchDownAndCheck(pointer2, position2_1) subject.updateTouchPointerAndCheck(pointer1, position1_2) subject.updateTouchPointerAndCheck(pointer1, position1_3) subject.advanceEventTime() subject.generateTouchUpAndCheck(pointer1) subject.flush() recorder.assertHasValidEventTimes() recorder.events.apply { var t = 0L assertThat(this).hasSize(3) this[0].verifyTouchEvent(1, ACTION_DOWN, 0, t) // pointer1 this[0].verifyTouchPointer(pointer1, position1_1) this[1].verifyTouchEvent(2, ACTION_POINTER_DOWN, 1, t) // pointer2 this[1].verifyTouchPointer(pointer1, position1_1) this[1].verifyTouchPointer(pointer2, position2_1) t += eventPeriodMillis this[2].verifyTouchEvent(2, ACTION_POINTER_UP, 0, t) // pointer1 this[2].verifyTouchPointer(pointer1, position1_3) this[2].verifyTouchPointer(pointer2, position2_1) } } @Test fun enqueueTouchCancel_doesNotFlushPointerMovement() { // 2 fingers, both with pending movement. // CANCEL doesn't force a MOVE, but _does_ reflect the latest positions subject.generateTouchDownAndCheck(pointer1, position1_1) subject.generateTouchDownAndCheck(pointer2, position2_1) subject.updateTouchPointerAndCheck(pointer1, position1_2) subject.updateTouchPointerAndCheck(pointer2, position2_2) subject.advanceEventTime() subject.generateCancelAndCheckPointers() subject.flush() recorder.assertHasValidEventTimes() recorder.events.apply { var t = 0L assertThat(this).hasSize(3) this[0].verifyTouchEvent(1, ACTION_DOWN, 0, t) // pointer1 this[0].verifyTouchPointer(pointer1, position1_1) this[1].verifyTouchEvent(2, ACTION_POINTER_DOWN, 1, t) // pointer2 this[1].verifyTouchPointer(pointer1, position1_1) this[1].verifyTouchPointer(pointer2, position2_1) t += eventPeriodMillis this[2].verifyTouchEvent(2, ACTION_CANCEL, 0, t) this[2].verifyTouchPointer(pointer1, position1_2) this[2].verifyTouchPointer(pointer2, position2_2) } } private fun AndroidInputDispatcher.generateCancelAndCheckPointers() { generateTouchCancelAndCheck() assertThat(getCurrentTouchPosition(pointer1)).isNull() assertThat(getCurrentTouchPosition(pointer2)).isNull() assertThat(getCurrentTouchPosition(pointer3)).isNull() } @Test fun enqueueTouchDown_afterDown() { subject.enqueueTouchDown(pointer1, position1) expectError<IllegalArgumentException> { subject.enqueueTouchDown(pointer1, position2) } } @Test fun updateTouchPointer_withoutDown() { expectError<IllegalStateException> { subject.updateTouchPointer(pointer1, position1_1) } } @Test fun updateTouchPointer_wrongPointerId() { subject.enqueueTouchDown(pointer1, position1_1) expectError<IllegalArgumentException> { subject.updateTouchPointer(pointer2, position1_2) } } @Test fun updateTouchPointer_afterUp() { subject.enqueueTouchDown(pointer1, position1_1) subject.enqueueTouchUp(pointer1) expectError<IllegalStateException> { subject.updateTouchPointer(pointer1, position1_2) } } @Test fun updateTouchPointer_afterCancel() { subject.enqueueTouchDown(pointer1, position1_1) subject.enqueueTouchCancel() expectError<IllegalStateException> { subject.updateTouchPointer(pointer1, position1_2) } } @Test fun enqueueTouchMove_withoutDown() { expectError<IllegalStateException> { subject.enqueueTouchMove() } } @Test fun enqueueTouchMove_afterUp() { subject.enqueueTouchDown(pointer1, position1_1) subject.enqueueTouchUp(pointer1) expectError<IllegalStateException> { subject.enqueueTouchMove() } } @Test fun enqueueTouchMove_afterCancel() { subject.enqueueTouchDown(pointer1, position1_1) subject.enqueueTouchCancel() expectError<IllegalStateException> { subject.enqueueTouchMove() } } @Test fun enqueueTouchUp_withoutDown() { expectError<IllegalStateException> { subject.enqueueTouchUp(pointer1) } } @Test fun enqueueTouchUp_wrongPointerId() { subject.enqueueTouchDown(pointer1, position1_1) expectError<IllegalArgumentException> { subject.enqueueTouchUp(pointer2) } } @Test fun enqueueTouchUp_afterUp() { subject.enqueueTouchDown(pointer1, position1_1) subject.enqueueTouchUp(pointer1) expectError<IllegalStateException> { subject.enqueueTouchUp(pointer1) } } @Test fun enqueueTouchUp_afterCancel() { subject.enqueueTouchDown(pointer1, position1_1) subject.enqueueTouchCancel() expectError<IllegalStateException> { subject.enqueueTouchUp(pointer1) } } @Test fun enqueueTouchCancel_withoutDown() { expectError<IllegalStateException> { subject.enqueueTouchCancel() } } @Test fun enqueueTouchCancel_afterUp() { subject.enqueueTouchDown(pointer1, position1_1) subject.enqueueTouchUp(pointer1) expectError<IllegalStateException> { subject.enqueueTouchCancel() } } @Test fun enqueueTouchCancel_afterCancel() { subject.enqueueTouchDown(pointer1, position1_1) subject.enqueueTouchCancel() expectError<IllegalStateException> { subject.enqueueTouchCancel() } } }
apache-2.0
androidx/androidx
health/health-services-client/src/main/java/androidx/health/services/client/impl/event/PassiveListenerEvent.kt
3
2954
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.health.services.client.impl.event import android.os.Parcelable import androidx.annotation.RestrictTo import androidx.health.services.client.PassiveListenerCallback import androidx.health.services.client.PassiveListenerService import androidx.health.services.client.data.ProtoParcelable import androidx.health.services.client.impl.response.HealthEventResponse import androidx.health.services.client.impl.response.PassiveMonitoringGoalResponse import androidx.health.services.client.impl.response.PassiveMonitoringUpdateResponse import androidx.health.services.client.proto.EventsProto.PassiveListenerEvent as EventProto import androidx.health.services.client.proto.ResponsesProto.PermissionLostResponse /** * An event representing a [PassiveListenerCallback] or [PassiveListenerService] invocation. * * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY) internal class PassiveListenerEvent(public override val proto: EventProto) : ProtoParcelable<EventProto>() { public companion object { @JvmField public val CREATOR: Parcelable.Creator<PassiveListenerEvent> = newCreator { PassiveListenerEvent(EventProto.parseFrom(it)) } @JvmStatic public fun createPermissionLostResponse(): PassiveListenerEvent = PassiveListenerEvent( EventProto.newBuilder() .setPermissionLostResponse(PermissionLostResponse.newBuilder().build()) .build() ) @JvmStatic public fun createPassiveUpdateResponse( response: PassiveMonitoringUpdateResponse ): PassiveListenerEvent = PassiveListenerEvent( EventProto.newBuilder().setPassiveUpdateResponse(response.proto).build() ) @JvmStatic public fun createPassiveGoalResponse( response: PassiveMonitoringGoalResponse ): PassiveListenerEvent = PassiveListenerEvent( EventProto.newBuilder().setPassiveGoalResponse(response.proto).build() ) @JvmStatic public fun createHealthEventResponse(response: HealthEventResponse): PassiveListenerEvent = PassiveListenerEvent( EventProto.newBuilder().setHealthEventResponse(response.proto).build() ) } }
apache-2.0
androidx/androidx
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/interaction/InteractionSource.kt
3
6156
/* * 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.foundation.interaction import androidx.compose.runtime.Stable import androidx.compose.runtime.State import androidx.compose.runtime.remember import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow /** * InteractionSource represents a stream of [Interaction]s corresponding to events emitted by a * component. These [Interaction]s can be used to change how components appear in different * states, such as when a component is pressed or dragged. * * A common use case is [androidx.compose.foundation.indication], where * [androidx.compose.foundation.Indication] implementations can subscribe to an [InteractionSource] * to draw indication for different [Interaction]s, such as a ripple effect for * [PressInteraction.Press] and a state overlay for [DragInteraction.Start]. * * For simple cases where you are interested in the binary state of an [Interaction], such as * whether a component is pressed or not, you can use [InteractionSource.collectIsPressedAsState] and other * extension functions that subscribe and return a [Boolean] [State] representing whether the * component is in this state or not. * * @sample androidx.compose.foundation.samples.SimpleInteractionSourceSample * * For more complex cases, such as when building an [androidx.compose.foundation.Indication], the * order of the events can change how a component / indication should be drawn. For example, if a * component is being dragged and then becomes focused, the most recent [Interaction] is * [FocusInteraction.Focus], so the component should appear in a focused state to signal this * event to the user. * * InteractionSource exposes [interactions] to support these use cases - a * [Flow] representing the stream of all emitted [Interaction]s. This also provides more * information, such as the press position of [PressInteraction.Press], so you can show an effect * at the specific point the component was pressed, and whether the press was * [PressInteraction.Release] or [PressInteraction.Cancel], for cases when a component * should behave differently if the press was released normally or interrupted by another gesture. * * You can collect from [interactions] as you would with any other [Flow]: * * @sample androidx.compose.foundation.samples.InteractionSourceFlowSample * * To emit [Interaction]s so that consumers can react to them, see [MutableInteractionSource]. * * @see MutableInteractionSource * @see Interaction */ @Stable interface InteractionSource { /** * [Flow] representing the stream of all [Interaction]s emitted through this * [InteractionSource]. This can be used to see [Interaction]s emitted in order, and with * additional metadata, such as the press position for [PressInteraction.Press]. * * @sample androidx.compose.foundation.samples.InteractionSourceFlowSample */ val interactions: Flow<Interaction> } /** * MutableInteractionSource represents a stream of [Interaction]s corresponding to events emitted * by a component. These [Interaction]s can be used to change how components appear * in different states, such as when a component is pressed or dragged. * * Lower level interaction APIs such as [androidx.compose.foundation.clickable] and * [androidx.compose.foundation.gestures.draggable] have an [MutableInteractionSource] parameter, * which allows you to hoist an [MutableInteractionSource] and combine multiple interactions into * one event stream. * * MutableInteractionSource exposes [emit] and [tryEmit] functions. These emit the provided * [Interaction] to the underlying [interactions] [Flow], allowing consumers to react to these * new [Interaction]s. * * An instance of MutableInteractionSource can be created by using the * [MutableInteractionSource] factory function. This instance should be [remember]ed before it is * passed to other components that consume it. * * @see InteractionSource * @see Interaction */ @Stable interface MutableInteractionSource : InteractionSource { /** * Emits [interaction] into [interactions]. * This method is not thread-safe and should not be invoked concurrently. * * @see tryEmit */ suspend fun emit(interaction: Interaction) /** * Tries to emit [interaction] into [interactions] without suspending. It returns `true` if the * value was emitted successfully. * * @see emit */ fun tryEmit(interaction: Interaction): Boolean } /** * Return a new [MutableInteractionSource] that can be hoisted and provided to components, * allowing listening to [Interaction] changes inside those components. * * This should be [remember]ed before it is provided to components, so it can maintain its state * across compositions. * * @see InteractionSource * @see MutableInteractionSource */ fun MutableInteractionSource(): MutableInteractionSource = MutableInteractionSourceImpl() @Stable private class MutableInteractionSourceImpl : MutableInteractionSource { // TODO: consider replay for new indication instances during events? override val interactions = MutableSharedFlow<Interaction>( extraBufferCapacity = 16, onBufferOverflow = BufferOverflow.DROP_OLDEST, ) override suspend fun emit(interaction: Interaction) { interactions.emit(interaction) } override fun tryEmit(interaction: Interaction): Boolean { return interactions.tryEmit(interaction) } }
apache-2.0
GunoH/intellij-community
plugins/git4idea/src/git4idea/remote/GitDefineRemoteDialog.kt
1
5282
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.remote import com.intellij.openapi.application.AppUIExecutor import com.intellij.openapi.application.impl.coroutineDispatchingContext import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.runUnderIndicator import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.vfs.VfsUtilCore.virtualToIoFile import com.intellij.openapi.wm.IdeFocusManager import com.intellij.ui.AnimatedIcon import com.intellij.ui.DocumentAdapter import com.intellij.ui.components.JBTextField import com.intellij.ui.components.fields.ExtendableTextComponent import com.intellij.ui.components.fields.ExtendableTextField import com.intellij.ui.dsl.builder.AlignX import com.intellij.ui.dsl.builder.panel import git4idea.GitUtil.mention import git4idea.commands.Git import git4idea.commands.GitCommandResult import git4idea.i18n.GitBundle.message import git4idea.repo.GitRepository import git4idea.validators.GitRefNameValidator import kotlinx.coroutines.* import javax.swing.JComponent import javax.swing.event.DocumentEvent private val LOG = logger<GitDefineRemoteDialog>() class GitDefineRemoteDialog( private val repository: GitRepository, private val git: Git, @NlsSafe private val initialName: String, @NlsSafe initialUrl: String ) : DialogWrapper(repository.project) { private val uiDispatcher get() = AppUIExecutor.onUiThread().coroutineDispatchingContext() private val scope = CoroutineScope(SupervisorJob()).also { Disposer.register(disposable) { it.cancel() } } private val nameField = JBTextField(initialName, 30) private val urlField = ExtendableTextField(initialUrl, 30) private val loadingExtension = ExtendableTextComponent.Extension { AnimatedIcon.Default.INSTANCE } private var urlAccessError: ValidationInfo? = null init { title = message("remotes.define.remote") + mention(repository) init() } val remoteName: String get() = nameField.text.orEmpty().trim() val remoteUrl: String get() = urlField.text.orEmpty().trim() override fun getPreferredFocusedComponent(): JComponent = if (nameField.text.isNullOrEmpty()) nameField else urlField override fun createCenterPanel(): JComponent = panel { row(message("remotes.define.remote.name")) { cell(nameField) .align(AlignX.FILL) .validationOnApply { nameNotBlank() ?: nameWellFormed() ?: nameUnique() } } row(message("remotes.define.remote.url")) { cell(urlField) .align(AlignX.FILL) .validationOnApply { urlNotBlank() ?: urlAccessError } .applyToComponent { clearUrlAccessErrorOnTextChanged() } } } override fun doOKAction() { scope.launch(uiDispatcher + CoroutineName("Define Remote - checking url")) { setLoading(true) try { urlAccessError = checkUrlAccess() } finally { setLoading(false) } if (urlAccessError == null) { super.doOKAction() } else { IdeFocusManager.getGlobalInstance().requestFocus(urlField, true) startTrackingValidation() } } } private fun setLoading(isLoading: Boolean) { nameField.isEnabled = !isLoading urlField.apply { if (isLoading) addExtension(loadingExtension) else removeExtension(loadingExtension) } urlField.isEnabled = !isLoading isOKActionEnabled = !isLoading } private fun nameNotBlank(): ValidationInfo? = if (remoteName.isNotEmpty()) null else ValidationInfo(message("remotes.define.empty.remote.name.validation.message"), nameField) private fun nameWellFormed(): ValidationInfo? = if (GitRefNameValidator.getInstance().checkInput(remoteName)) null else ValidationInfo(message("remotes.define.invalid.remote.name.validation.message"), nameField) private fun nameUnique(): ValidationInfo? { val name = remoteName return if (name == initialName || repository.remotes.none { it.name == name }) null else ValidationInfo(message("remotes.define.duplicate.remote.name.validation.message", name), nameField) } private fun urlNotBlank(): ValidationInfo? = if (remoteUrl.isNotEmpty()) null else ValidationInfo(message("remotes.define.empty.remote.url.validation.message"), urlField) private fun JBTextField.clearUrlAccessErrorOnTextChanged() = document.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { urlAccessError = null } }) private suspend fun checkUrlAccess(): ValidationInfo? { val url = remoteUrl val result = lsRemote(url) if (result.success()) return null LOG.warn("Invalid remote. Name: $remoteName, URL: $url, error: ${result.errorOutputAsJoinedString}") return ValidationInfo(result.errorOutputAsHtmlString, urlField).withOKEnabled() } private suspend fun lsRemote(url: String): GitCommandResult = withContext(Dispatchers.IO) { runUnderIndicator { git.lsRemote(repository.project, virtualToIoFile(repository.root), url) } } }
apache-2.0
GunoH/intellij-community
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/expressions/KotlinUSuperExpression.kt
4
1030
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.kotlin import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.psi.KtSuperExpression import org.jetbrains.uast.UElement import org.jetbrains.uast.UIdentifier import org.jetbrains.uast.USuperExpression import org.jetbrains.uast.kotlin.internal.DelegatedMultiResolve @ApiStatus.Internal class KotlinUSuperExpression( override val sourcePsi: KtSuperExpression, givenParent: UElement? ) : KotlinAbstractUExpression(givenParent), USuperExpression, DelegatedMultiResolve, KotlinUElementWithType, KotlinEvaluatableUElement { override val label: String? get() = sourcePsi.getLabelName() override val labelIdentifier: UIdentifier? get() = sourcePsi.getTargetLabel()?.let { KotlinUIdentifier(it, this) } override fun resolve() = baseResolveProviderService.resolveToDeclaration(sourcePsi) }
apache-2.0
GunoH/intellij-community
plugins/toml/core/src/test/kotlin/org/toml/ide/annotator/TomlAnnotationTestBase.kt
7
1919
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.toml.ide.annotator import org.intellij.lang.annotations.Language import org.toml.TomlTestBase abstract class TomlAnnotationTestBase : TomlTestBase() { private lateinit var annotationFixture: TomlAnnotationTestFixture override fun setUp() { super.setUp() annotationFixture = createAnnotationFixture() annotationFixture.setUp() } override fun tearDown() { try { annotationFixture.tearDown() } catch (e: Throwable) { addSuppressedException(e) } finally { super.tearDown() } } protected abstract fun createAnnotationFixture(): TomlAnnotationTestFixture protected fun checkHighlighting(@Language("TOML") text: String, ignoreExtraHighlighting: Boolean = true) = annotationFixture.checkHighlighting(text, ignoreExtraHighlighting) protected fun checkByText( @Language("TOML") text: String, checkWarn: Boolean = true, checkInfo: Boolean = false, checkWeakWarn: Boolean = false, ignoreExtraHighlighting: Boolean = false ) = annotationFixture.checkByText(text, checkWarn, checkInfo, checkWeakWarn, ignoreExtraHighlighting) protected fun checkFixByText( fixName: String, @Language("TOML") before: String, @Language("TOML") after: String, checkWarn: Boolean = true, checkInfo: Boolean = false, checkWeakWarn: Boolean = false ) = annotationFixture.checkFixByText(fixName, before, after, checkWarn, checkInfo, checkWeakWarn) protected fun checkFixByTextWithoutHighlighting( fixName: String, @Language("TOML") before: String, @Language("TOML") after: String, ) = annotationFixture.checkFixByTextWithoutHighlighting(fixName, before, after) }
apache-2.0
zhiayang/pew
core/src/main/kotlin/Items/BasicItem.kt
1
207
// Copyright (c) 2014 Orion Industries, [email protected] // Licensed under the Apache License version 2.0 package Items public class BasicItem(name: String, maxSS: Int = 64) : InventoryItem(name, maxSS)
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/hierarchy/calls/callHierarchyUtils.kt
4
2733
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.hierarchy.calls import com.intellij.ide.hierarchy.HierarchyNodeDescriptor import com.intellij.ide.hierarchy.call.CallHierarchyNodeDescriptor import com.intellij.ide.util.treeView.NodeDescriptor import com.intellij.psi.PsiElement import com.intellij.psi.PsiMember import com.intellij.psi.PsiReference import org.jetbrains.kotlin.asJava.toLightElements import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf fun isCallHierarchyElement(e: PsiElement): Boolean { return (e is KtNamedFunction && e.name != null) || e is KtSecondaryConstructor || (e is KtProperty && !e.isLocal) || e is KtObjectDeclaration || (e is KtClass && !e.isInterface()) || e is KtFile } fun getCallHierarchyElement(element: PsiElement) = element.parentsWithSelf.firstOrNull(::isCallHierarchyElement) as? KtElement private fun NodeDescriptor<*>.incrementUsageCount() { when (this) { is KotlinCallHierarchyNodeDescriptor -> incrementUsageCount() is CallHierarchyNodeDescriptor -> incrementUsageCount() } } private fun NodeDescriptor<*>.addReference(reference: PsiReference) { when (this) { is KotlinCallHierarchyNodeDescriptor -> addReference(reference) is CallHierarchyNodeDescriptor -> addReference(reference) } } internal fun getOrCreateNodeDescriptor( parent: HierarchyNodeDescriptor, originalElement: PsiElement, reference: PsiReference?, navigateToReference: Boolean, elementToDescriptorMap: MutableMap<PsiElement, NodeDescriptor<*>>, isJavaMap: Boolean ): HierarchyNodeDescriptor? { val element = (if (isJavaMap && originalElement is KtElement) originalElement.toLightElements().firstOrNull() else originalElement) ?: return null val existingDescriptor = elementToDescriptorMap[element] as? HierarchyNodeDescriptor val result = if (existingDescriptor != null) { existingDescriptor.incrementUsageCount() existingDescriptor } else { val newDescriptor: HierarchyNodeDescriptor = when (element) { is KtElement -> KotlinCallHierarchyNodeDescriptor(parent, element, false, navigateToReference) is PsiMember -> CallHierarchyNodeDescriptor(element.project, parent, element, false, navigateToReference) else -> return null } elementToDescriptorMap[element] = newDescriptor newDescriptor } if (reference != null) { result.addReference(reference) } return result }
apache-2.0
GunoH/intellij-community
plugins/git4idea/src/git4idea/remote/hosting/gitAsyncExtensions.kt
2
3124
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package git4idea.remote.hosting import com.intellij.collaboration.api.ServerPath import com.intellij.dvcs.repo.VcsRepositoryManager import com.intellij.dvcs.repo.VcsRepositoryMappingListener import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import git4idea.remote.GitRemoteUrlCoordinates import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryChangeListener import git4idea.repo.GitRepositoryManager import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.* fun gitRemotesFlow(project: Project): Flow<Set<GitRemoteUrlCoordinates>> = callbackFlow { val disposable = Disposer.newDisposable() project.messageBus.connect(disposable).subscribe(VcsRepositoryManager.VCS_REPOSITORY_MAPPING_UPDATED, VcsRepositoryMappingListener { trySend(GitRepositoryManager.getInstance(project).collectRemotes()) }) project.messageBus.connect(disposable).subscribe(GitRepository.GIT_REPO_CHANGE, GitRepositoryChangeListener { trySend(GitRepositoryManager.getInstance(project).collectRemotes()) }) send(GitRepositoryManager.getInstance(project).collectRemotes()) awaitClose { Disposer.dispose(disposable) } } private fun GitRepositoryManager.collectRemotes(): Set<GitRemoteUrlCoordinates> { if (repositories.isEmpty()) { return emptySet() } return repositories.flatMap { repo -> repo.remotes.flatMap { remote -> remote.urls.mapNotNull { url -> GitRemoteUrlCoordinates(url, remote, repo) } } }.toSet() } private typealias GitRemotesFlow = Flow<Collection<GitRemoteUrlCoordinates>> fun <S : ServerPath, M : HostedGitRepositoryMapping> GitRemotesFlow.mapToServers(serversState: Flow<Set<S>>, mapper: (S, GitRemoteUrlCoordinates) -> M?) : Flow<Set<M>> = combine(serversState) { remotes, servers -> remotes.asSequence().mapNotNull { remote -> servers.find { GitHostingUrlUtil.match(it.toURI(), remote.url) }?.let { mapper(it, remote) } }.toSet() } fun <S : ServerPath> GitRemotesFlow.discoverServers(knownServersFlow: Flow<Set<S>>, parallelism: Int = 10, checkForDedicatedServer: suspend (GitRemoteUrlCoordinates) -> S?) : Flow<S> { val remotesFlow = this return channelFlow { remotesFlow.combine(knownServersFlow) { remotes, servers -> remotes.filter { remote -> servers.none { GitHostingUrlUtil.match(it.toURI(), remote.url) } } } .conflate() .collect { remotes -> remotes.chunked(parallelism).forEach { remotesChunk -> remotesChunk.map { remote -> async { val server = checkForDedicatedServer(remote) if (server != null) send(server) } }.awaitAll() } } } }
apache-2.0
GunoH/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/hint/types/GroovyParameterTypeHintsCollector.kt
2
4391
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.groovy.codeInsight.hint.types import com.intellij.codeInsight.hints.FactoryInlayHintsCollector import com.intellij.codeInsight.hints.InlayHintsSink import com.intellij.codeInsight.hints.presentation.InlayPresentation import com.intellij.codeInsight.hints.settings.CASE_KEY import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.DumbService import com.intellij.psi.CommonClassNames import com.intellij.psi.PsiElement import com.intellij.psi.PsiType import com.intellij.psi.util.PsiUtilCore import com.intellij.psi.util.parentOfType import com.intellij.refactoring.suggested.endOffset import com.intellij.util.asSafely import org.jetbrains.plugins.groovy.intentions.style.inference.MethodParameterAugmenter import org.jetbrains.plugins.groovy.lang.psi.GrControlFlowOwner import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier.DEF import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod import org.jetbrains.plugins.groovy.lang.psi.dataFlow.types.TypeAugmenter import org.jetbrains.plugins.groovy.lang.psi.dataFlow.types.TypeInferenceHelper import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.ClosureSyntheticParameter import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.GrVariableEnhancer class GroovyParameterTypeHintsCollector(editor: Editor, private val settings: GroovyParameterTypeHintsInlayProvider.Settings) : FactoryInlayHintsCollector(editor) { override fun collect(element: PsiElement, editor: Editor, sink: InlayHintsSink): Boolean { if (DumbService.isDumb(element.project) || element.project.isDefault) { return false } if (!settings.showInferredParameterTypes && CASE_KEY.get(editor) == null) { return false } PsiUtilCore.ensureValid(element) if (element is GrParameter && element.typeElement == null && !element.isVarArgs) { val type: PsiType = getRepresentableType(element) ?: return true val typeRepresentation = with(factory) { roundWithBackground(seq(buildRepresentation(type), smallText(" "))) } sink.addInlineElement(element.textOffset, false, typeRepresentation, false) } if (element is GrClosableBlock && element.parameterList.isEmpty) { val itParameter = element.allParameters.singleOrNull()?.asSafely<ClosureSyntheticParameter>() ?: return true if (!itParameter.isStillValid) return true val type: PsiType = getRepresentableType(itParameter) ?: return true val textRepresentation: InlayPresentation = with(factory) { roundWithBackground(seq(buildRepresentation(type), smallText(" it -> "))) } sink.addInlineElement(element.lBrace.endOffset, true, textRepresentation, false) } if (settings.showTypeParameterList && element is GrMethod && !element.hasTypeParameters() && element.parameters.any { it.typeElement == null }) { val (virtualMethod, _) = MethodParameterAugmenter.createInferenceResult(element) ?: return true val typeParameterList = virtualMethod?.typeParameterList?.takeIf { it.typeParameters.isNotEmpty() } ?: return true val representation = factory.buildRepresentation(typeParameterList) if (element.modifierList.hasModifierProperty(DEF)) { sink.addInlineElement(element.modifierList.getModifier(DEF)!!.textRange.endOffset, true, representation, false) } else { sink.addInlineElement(element.textRange.startOffset, true, representation, false) } } return true } private fun getRepresentableType(variable: GrParameter): PsiType? { var inferredType: PsiType? = GrVariableEnhancer.getEnhancedType(variable) if (inferredType == null) { val ownerFlow = variable.parentOfType<GrControlFlowOwner>()?.controlFlow ?: return null if (TypeInferenceHelper.isSimpleEnoughForAugmenting(ownerFlow)) { inferredType = TypeAugmenter.inferAugmentedType(variable) } } return inferredType?.takeIf { !it.equalsToText(CommonClassNames.JAVA_LANG_OBJECT) } } }
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/optIn/typeInTopLevelProperty.kt
8
322
// "Propagate 'TopMarker' opt-in requirement to 'topUserVal'" "true" // COMPILER_ARGUMENTS: -opt-in=kotlin.RequiresOptIn // WITH_STDLIB @RequiresOptIn annotation class TopMarker @TopMarker class TopClass @Target(AnnotationTarget.TYPE) @TopMarker annotation class TopAnn val topUserVal: @TopAnn <caret>TopClass? = null
apache-2.0
GunoH/intellij-community
plugins/kotlin/jvm-debugger/test/testData/selectExpression/disallowMethodCalls/infixCallArgument.kt
7
112
fun foo() { val a = 1 <caret>a foo 1 } fun Int.foo(i: Int) = 1 // DISALLOW_METHOD_CALLS // EXPECTED: a
apache-2.0
GunoH/intellij-community
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/util/DescriptorUtils.kt
4
4941
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.util import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.load.java.descriptors.JavaCallableMemberDescriptor import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor import org.jetbrains.kotlin.name.FqNameUnsafe import org.jetbrains.kotlin.resolve.OverridingUtil import org.jetbrains.kotlin.resolve.OverridingUtil.OverrideCompatibilityInfo.Result.CONFLICT import org.jetbrains.kotlin.resolve.OverridingUtil.OverrideCompatibilityInfo.Result.OVERRIDABLE import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe import org.jetbrains.kotlin.resolve.descriptorUtil.overriddenTreeUniqueAsSequence import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeConstructor import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.types.checker.KotlinTypeCheckerImpl import org.jetbrains.kotlin.types.typeUtil.equalTypesOrNulls fun descriptorsEqualWithSubstitution( descriptor1: DeclarationDescriptor?, descriptor2: DeclarationDescriptor?, checkOriginals: Boolean = true ): Boolean { if (descriptor1 == descriptor2) return true if (descriptor1 == null || descriptor2 == null) return false if (checkOriginals && descriptor1.original != descriptor2.original) return false if (descriptor1 !is CallableDescriptor) return true descriptor2 as CallableDescriptor val typeChecker = KotlinTypeCheckerImpl.withAxioms(object : KotlinTypeChecker.TypeConstructorEquality { override fun equals(a: TypeConstructor, b: TypeConstructor): Boolean { val typeParam1 = a.declarationDescriptor as? TypeParameterDescriptor val typeParam2 = b.declarationDescriptor as? TypeParameterDescriptor if (typeParam1 != null && typeParam2 != null && typeParam1.containingDeclaration == descriptor1 && typeParam2.containingDeclaration == descriptor2 ) { return typeParam1.index == typeParam2.index } return a == b } }) if (!typeChecker.equalTypesOrNulls(descriptor1.returnType, descriptor2.returnType)) return false val parameters1 = descriptor1.valueParameters val parameters2 = descriptor2.valueParameters if (parameters1.size != parameters2.size) return false for ((param1, param2) in parameters1.zip(parameters2)) { if (!typeChecker.equalTypes(param1.type, param2.type)) return false } return true } fun ClassDescriptor.findCallableMemberBySignature( signature: CallableMemberDescriptor, allowOverridabilityConflicts: Boolean = false ): CallableMemberDescriptor? { val descriptorKind = if (signature is FunctionDescriptor) DescriptorKindFilter.FUNCTIONS else DescriptorKindFilter.VARIABLES return defaultType.memberScope .getContributedDescriptors(descriptorKind) .filterIsInstance<CallableMemberDescriptor>() .firstOrNull { if (it.containingDeclaration != this) return@firstOrNull false val overridability = OverridingUtil.DEFAULT.isOverridableBy(it as CallableDescriptor, signature, null).result overridability == OVERRIDABLE || (allowOverridabilityConflicts && overridability == CONFLICT) } } fun TypeConstructor.supertypesWithAny(): Collection<KotlinType> { val supertypes = supertypes val noSuperClass = supertypes.map { it.constructor.declarationDescriptor as? ClassDescriptor }.all { it == null || it.kind == ClassKind.INTERFACE } return if (noSuperClass) supertypes + builtIns.anyType else supertypes } val ClassifierDescriptorWithTypeParameters.constructors: Collection<ConstructorDescriptor> get() = when (this) { is TypeAliasDescriptor -> this.constructors is ClassDescriptor -> this.constructors else -> emptyList() } val ClassifierDescriptorWithTypeParameters.kind: ClassKind? get() = when (this) { is TypeAliasDescriptor -> classDescriptor?.kind is ClassDescriptor -> kind else -> null } val DeclarationDescriptor.isJavaDescriptor get() = this is JavaClassDescriptor || this is JavaCallableMemberDescriptor fun FunctionDescriptor.shouldNotConvertToProperty(notProperties: Set<FqNameUnsafe>): Boolean { if (fqNameUnsafe in notProperties) return true return this.overriddenTreeUniqueAsSequence(false).any { fqNameUnsafe in notProperties } } fun SyntheticJavaPropertyDescriptor.suppressedByNotPropertyList(set: Set<FqNameUnsafe>) = getMethod.shouldNotConvertToProperty(set) || setMethod?.shouldNotConvertToProperty(set) ?: false
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/autoImports/callablesDeclaredInClasses/companionObjectExtensionFunctionTwoCandidatesB.kt
3
305
// "Import extension function 'Companion.foo'" "true" package p class A { companion object } class B { companion object } open class P { fun A.Companion.foo() {} } open class Q { fun B.Companion.foo() {} } object PObject : P() object QObject : Q() fun usage() { B.<caret>foo() }
apache-2.0
siosio/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/simplifiableCallChain/primitiveArray/mapJoinToString.kt
4
130
// WITH_RUNTIME fun test() { val array: IntArray = intArrayOf(0, 1, 2, 3) array.<caret>map { "$it-$it" }.joinToString() }
apache-2.0
siosio/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/uselessCallOnNotNull/NullOrBlankSafe.kt
4
107
// WITH_RUNTIME // FIX: Change call to 'isBlank' val s: String? = "" val blank = s<caret>?.isNullOrBlank()
apache-2.0
siosio/intellij-community
plugins/kotlin/idea/tests/testData/intentions/specifyExplicitLambdaSignature/multipleParam.kt
4
224
class TestingUse { fun test4(printNum: (a: Int, b: String) -> Unit, c: Int): Int { printNum(c, "This number is") return c } } fun main() { val num = TestingUse().test4({ <caret>x, str -> }, 5) }
apache-2.0
siosio/intellij-community
plugins/completion-ml-ranking/src/com/intellij/completion/ml/util/RelevanceUtil.kt
1
4600
package com.intellij.completion.ml.util import com.intellij.codeInsight.completion.ml.MLWeigherUtil import com.intellij.completion.ml.features.MLCompletionWeigher import com.intellij.completion.ml.sorting.FeatureUtils import com.intellij.internal.statistic.utils.PluginType import com.intellij.internal.statistic.utils.getPluginInfo import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.Pair import com.intellij.openapi.util.text.StringUtil object RelevanceUtil { private val LOG = logger<RelevanceUtil>() private const val NULL_TEXT = "null" private val IGNORED_FACTORS = setOf("kotlin.byNameAlphabetical", "scalaMethodCompletionWeigher", "unresolvedOnTop", "alphabetic", "TabNineLookupElementWeigher", "AixLookupElementWeigher", "CodotaCompletionWeigher", "CodotaCompletionWeigher_Kotlin", "EmcSuggestionsWeigher", "codotaPriorityWeigher", "com.zlabs.code.completion.ScaCompletionWeigher", "com.aliyun.odps.studio.intellij.compiler.codecompletion.OdpsqlCompletionWeigher") private val weighersClassesCache = mutableMapOf<String, PluginType>() /* * First map contains only features affecting default elements ordering * */ fun asRelevanceMaps(relevanceObjects: List<Pair<String, Any?>>): kotlin.Pair<MutableMap<String, Any>, MutableMap<String, Any>> { val relevanceMap = mutableMapOf<String, Any>() val additionalMap = mutableMapOf<String, Any>() for (pair in relevanceObjects) { val name = pair.first.normalized() val value = pair.second if (name in IGNORED_FACTORS || value == null) continue when (name) { "proximity" -> relevanceMap.addProximityValues("prox", value) "kotlin.proximity" -> relevanceMap.addProximityValues("kt_prox", value) "swiftSymbolProximity" -> { relevanceMap[name] = value // while this feature is used in actual models relevanceMap.addProximityValues("swift_prox", value) } "kotlin.callableWeight" -> relevanceMap.addDataClassValues("kotlin.callableWeight", value.toString()) "ml_weigh" -> additionalMap.addMlFeatures("ml", value) else -> if (acceptValue(value) || name == FeatureUtils.ML_RANK) relevanceMap[name] = value } } return kotlin.Pair(relevanceMap, additionalMap) } private fun acceptValue(value: Any): Boolean { return value is Number || value is Boolean || value.javaClass.isEnum || isJetBrainsClass(value.javaClass) } private fun isJetBrainsClass(cl: Class<*>): Boolean { val pluginType = weighersClassesCache.getOrPut(cl.name) { getPluginInfo(cl).type } return pluginType.isDevelopedByJetBrains() } private fun String.normalized(): String { return substringBefore('@') } private fun MutableMap<String, Any>.addMlFeatures(prefix: String, comparable: Any) { if (comparable !is MLCompletionWeigher.DummyComparable) { LOG.error("Unexpected value type of `$prefix`: ${comparable.javaClass.simpleName}") return } for ((name, value) in comparable.mlFeatures) { this["${prefix}_$name"] = value } } private fun MutableMap<String, Any>.addProximityValues(prefix: String, proximity: Any) { val weights = MLWeigherUtil.extractWeightsOrNull(proximity) if (weights == null) { LOG.error("Unexpected comparable type for `$prefix` weigher: ${proximity.javaClass.simpleName}") return } for ((name, weight) in weights) { this["${prefix}_$name"] = weight } } private fun MutableMap<String, Any>.addDataClassValues(featureName: String, dataClassString: String) { if (StringUtil.countChars(dataClassString, '(') != 1) { this[featureName] = dataClassString } else { this.addProperties(featureName, dataClassString.substringAfter('(').substringBeforeLast(')').split(',')) } } private fun MutableMap<String, Any>.addProperties(prefix: String, properties: List<String>) { properties.forEach { if (it.isNotBlank()) { val key = "${prefix}_${it.substringBefore('=').trim()}" val value = it.substringAfter('=').trim() if (value == NULL_TEXT) return@forEach this[key] = value } } } }
apache-2.0
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/NamingConventionInspections.kt
1
17836
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.analysis.AnalysisScope import com.intellij.codeInspection.* import com.intellij.codeInspection.reference.RefEntity import com.intellij.codeInspection.reference.RefFile import com.intellij.codeInspection.reference.RefPackage import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.ui.LabeledComponent import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiNameIdentifierOwner import com.intellij.ui.EditorTextField import com.siyeh.ig.BaseGlobalInspection import com.siyeh.ig.psiutils.TestUtils import org.intellij.lang.annotations.Language import org.intellij.lang.regexp.RegExpFileType import org.jdom.Element import org.jetbrains.annotations.NonNls import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.packageMatchesDirectoryOrImplicit import org.jetbrains.kotlin.idea.quickfix.RenameIdentifierFix import org.jetbrains.kotlin.idea.refactoring.fqName.fqName import org.jetbrains.kotlin.idea.refactoring.isInjectedFragment import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.visibilityModifierType import java.awt.BorderLayout import java.util.regex.PatternSyntaxException import javax.swing.JPanel data class NamingRule(val message: String, val matcher: (String) -> Boolean) private fun findRuleMessage(checkString: String, rules: Array<out NamingRule>): String? { for (rule in rules) { if (rule.matcher(checkString)) { return rule.message } } return null } private val START_UPPER = NamingRule(KotlinBundle.message("should.start.with.an.uppercase.letter")) { it.getOrNull(0)?.isUpperCase() == false } private val START_LOWER = NamingRule(KotlinBundle.message("should.start.with.a.lowercase.letter")) { it.getOrNull(0)?.isLowerCase() == false } private val NO_UNDERSCORES = NamingRule(KotlinBundle.message("should.not.contain.underscores")) { '_' in it } private val NO_START_UPPER = NamingRule(KotlinBundle.message("should.not.start.with.an.uppercase.letter")) { it.getOrNull(0)?.isUpperCase() == true } private val NO_START_UNDERSCORE = NamingRule(KotlinBundle.message("should.not.start.with.an.underscore")) { it.startsWith('_') } private val NO_MIDDLE_UNDERSCORES = NamingRule(KotlinBundle.message("should.not.contain.underscores.in.the.middle.or.the.end")) { '_' in it.substring(1) } private val NO_BAD_CHARACTERS = NamingRule(KotlinBundle.message("may.contain.only.letters.and.digits")) { it.any { c -> c !in 'a'..'z' && c !in 'A'..'Z' && c !in '0'..'9' } } private val NO_BAD_CHARACTERS_OR_UNDERSCORE = NamingRule(KotlinBundle.message("may.contain.only.letters.digits.or.underscores")) { it.any { c -> c !in 'a'..'z' && c !in 'A'..'Z' && c !in '0'..'9' && c != '_' } } class NamingConventionInspectionSettings( private val entityName: String, @Language("RegExp") val defaultNamePattern: String, private val setNamePatternCallback: ((value: String) -> Unit), private vararg val rules: NamingRule ) { var nameRegex: Regex? = defaultNamePattern.toRegex() var namePattern: String = defaultNamePattern set(value) { field = value setNamePatternCallback.invoke(value) nameRegex = try { value.toRegex() } catch (e: PatternSyntaxException) { null } } fun verifyName(element: PsiNameIdentifierOwner, holder: ProblemsHolder, additionalCheck: () -> Boolean) { val name = element.name val nameIdentifier = element.nameIdentifier if (name != null && nameIdentifier != null && nameRegex?.matches(name) == false && additionalCheck()) { val message = getNameMismatchMessage(name) holder.registerProblem( element.nameIdentifier!!, "$entityName ${KotlinBundle.message("text.name")} <code>#ref</code> $message #loc", RenameIdentifierFix() ) } } fun getNameMismatchMessage(name: String): String { if (namePattern != defaultNamePattern) { return getDefaultErrorMessage() } return findRuleMessage(name, rules) ?: getDefaultErrorMessage() } fun getDefaultErrorMessage() = KotlinBundle.message("doesn.t.match.regex.0", namePattern) fun createOptionsPanel(): JPanel = NamingConventionOptionsPanel(this) private class NamingConventionOptionsPanel(settings: NamingConventionInspectionSettings) : JPanel() { init { layout = BorderLayout() val regexField = EditorTextField(settings.namePattern, null, RegExpFileType.INSTANCE).apply { setOneLineMode(true) } regexField.document.addDocumentListener(object : DocumentListener { override fun documentChanged(e: DocumentEvent) { settings.namePattern = regexField.text } }) val labeledComponent = LabeledComponent.create(regexField, KotlinBundle.message("text.pattern"), BorderLayout.WEST) add(labeledComponent, BorderLayout.NORTH) } } } sealed class NamingConventionInspection( entityName: String, @Language("RegExp") defaultNamePattern: String, vararg rules: NamingRule ) : AbstractKotlinInspection() { // Serialized inspection state @Suppress("MemberVisibilityCanBePrivate") var namePattern: String = defaultNamePattern private val namingSettings = NamingConventionInspectionSettings( entityName, defaultNamePattern, setNamePatternCallback = { value -> namePattern = value }, rules = *rules ) protected fun verifyName(element: PsiNameIdentifierOwner, holder: ProblemsHolder, additionalCheck: () -> Boolean = { true }) { namingSettings.verifyName(element, holder, additionalCheck) } protected fun getNameMismatchMessage(name: String): String { return namingSettings.getNameMismatchMessage(name) } override fun createOptionsPanel(): JPanel = namingSettings.createOptionsPanel() override fun readSettings(node: Element) { super.readSettings(node) namingSettings.namePattern = namePattern } } class ClassNameInspection : NamingConventionInspection( KotlinBundle.message("class"), "[A-Z][A-Za-z\\d]*", START_UPPER, NO_UNDERSCORES, NO_BAD_CHARACTERS ) { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return object : KtVisitorVoid() { override fun visitClassOrObject(classOrObject: KtClassOrObject) { verifyName(classOrObject, holder) } override fun visitEnumEntry(enumEntry: KtEnumEntry) { // do nothing } } } } class EnumEntryNameInspection : NamingConventionInspection( KotlinBundle.message("enum.entry"), "[A-Z]([A-Za-z\\d]*|[A-Z_\\d]*)", START_UPPER, NO_BAD_CHARACTERS_OR_UNDERSCORE ) { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return enumEntryVisitor { enumEntry -> verifyName(enumEntry, holder) } } } class FunctionNameInspection : NamingConventionInspection( KotlinBundle.message("function"), "[a-z][A-Za-z\\d]*", START_LOWER, NO_UNDERSCORES, NO_BAD_CHARACTERS ) { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return namedFunctionVisitor { function -> if (function.hasModifier(KtTokens.OVERRIDE_KEYWORD)) { return@namedFunctionVisitor } if (!TestUtils.isInTestSourceContent(function)) { verifyName(function, holder) { val functionName = function.name val typeReference = function.typeReference if (typeReference != null) { typeReference.text != functionName } else { function.resolveToDescriptorIfAny() ?.returnType ?.fqName ?.takeUnless(FqName::isRoot) ?.shortName() ?.asString() != functionName } } } } } } class TestFunctionNameInspection : NamingConventionInspection( KotlinBundle.message("test.function"), "[a-z][A-Za-z_\\d]*", START_LOWER ) { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return namedFunctionVisitor { function -> if (!TestUtils.isInTestSourceContent(function)) { return@namedFunctionVisitor } if (function.nameIdentifier?.text?.startsWith("`") == true) { return@namedFunctionVisitor } verifyName(function, holder) } } } abstract class PropertyNameInspectionBase protected constructor( private val kind: PropertyKind, entityName: String, defaultNamePattern: String, vararg rules: NamingRule ) : NamingConventionInspection(entityName, defaultNamePattern, *rules) { protected enum class PropertyKind { NORMAL, PRIVATE, OBJECT_OR_TOP_LEVEL, CONST, LOCAL } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return propertyVisitor { property -> if (property.hasModifier(KtTokens.OVERRIDE_KEYWORD)) { return@propertyVisitor } if (property.getKind() == kind) { verifyName(property, holder) } } } private fun KtProperty.getKind(): PropertyKind = when { isLocal -> PropertyKind.LOCAL containingClassOrObject is KtObjectDeclaration -> PropertyKind.OBJECT_OR_TOP_LEVEL isTopLevel -> PropertyKind.OBJECT_OR_TOP_LEVEL hasModifier(KtTokens.CONST_KEYWORD) -> PropertyKind.CONST visibilityModifierType() == KtTokens.PRIVATE_KEYWORD -> PropertyKind.PRIVATE else -> PropertyKind.NORMAL } } class PropertyNameInspection : PropertyNameInspectionBase( PropertyKind.NORMAL, KotlinBundle.message("property"), "[a-z][A-Za-z\\d]*", START_LOWER, NO_UNDERSCORES, NO_BAD_CHARACTERS ) class ObjectPropertyNameInspection : PropertyNameInspectionBase( PropertyKind.OBJECT_OR_TOP_LEVEL, KotlinBundle.message("object.or.top.level.property"), "[A-Za-z][_A-Za-z\\d]*", NO_START_UNDERSCORE, NO_BAD_CHARACTERS_OR_UNDERSCORE ) class PrivatePropertyNameInspection : PropertyNameInspectionBase( PropertyKind.PRIVATE, KotlinBundle.message("private.property"), "_?[a-z][A-Za-z\\d]*", NO_MIDDLE_UNDERSCORES, NO_BAD_CHARACTERS_OR_UNDERSCORE ) class ConstPropertyNameInspection : PropertyNameInspectionBase(PropertyKind.CONST, KotlinBundle.message("const.property"), "[A-Z][_A-Z\\d]*") class LocalVariableNameInspection : PropertyNameInspectionBase( PropertyKind.LOCAL, KotlinBundle.message("local.variable"), "[a-z][A-Za-z\\d]*", START_LOWER, NO_UNDERSCORES, NO_BAD_CHARACTERS ) private class PackageNameInspectionLocal( val parentInspection: InspectionProfileEntry, val namingSettings: NamingConventionInspectionSettings ) : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { return packageDirectiveVisitor { directive -> val packageNameExpression = directive.packageNameExpression ?: return@packageDirectiveVisitor val checkResult = checkPackageDirective(directive, namingSettings) ?: return@packageDirectiveVisitor val descriptionTemplate = checkResult.toProblemTemplateString() holder.registerProblem( packageNameExpression, descriptionTemplate, RenamePackageFix() ) } } companion object { data class CheckResult(val errorMessage: String, val isForPart: Boolean) fun CheckResult.toProblemTemplateString(): String { return KotlinBundle.message("package.name") + if (isForPart) { " <code>#ref</code> ${KotlinBundle.message("text.part")} $errorMessage #loc" } else { " <code>#ref</code> $errorMessage #loc" } } fun checkPackageDirective(directive: KtPackageDirective, namingSettings: NamingConventionInspectionSettings): CheckResult? { return checkQualifiedName(directive.qualifiedName, namingSettings) } fun checkQualifiedName(qualifiedName: String, namingSettings: NamingConventionInspectionSettings): CheckResult? { if (qualifiedName.isEmpty() || namingSettings.nameRegex?.matches(qualifiedName) != false) { return null } val partErrorMessage = if (namingSettings.namePattern == namingSettings.defaultNamePattern) { qualifiedName.split('.').asSequence() .mapNotNull { part -> findRuleMessage(part, PackageNameInspection.PART_RULES) } .firstOrNull() } else { null } return if (partErrorMessage != null) { CheckResult(partErrorMessage, true) } else { CheckResult(namingSettings.getDefaultErrorMessage(), false) } } } private class RenamePackageFix : RenameIdentifierFix() { override fun getElementToRename(element: PsiElement): PsiElement? { val packageDirective = element as? KtPackageDirective ?: return null return JavaPsiFacade.getInstance(element.project).findPackage(packageDirective.qualifiedName) } } override fun getShortName(): String = parentInspection.shortName override fun getDisplayName(): String = parentInspection.displayName } class PackageNameInspection : BaseGlobalInspection() { companion object { const val DEFAULT_PACKAGE_NAME_PATTERN = "[a-z_][a-zA-Z\\d_]*(\\.[a-z_][a-zA-Z\\d_]*)*" val PART_RULES = arrayOf(NO_BAD_CHARACTERS_OR_UNDERSCORE, NO_START_UPPER) private fun PackageNameInspectionLocal.Companion.CheckResult.toErrorMessage(qualifiedName: String): String { return KotlinBundle.message("package.name") + if (isForPart) { " <code>$qualifiedName</code> ${KotlinBundle.message("text.part")} $errorMessage" } else { " <code>$qualifiedName</code> $errorMessage" } } } // Serialized setting @Suppress("MemberVisibilityCanBePrivate") var namePattern: String = DEFAULT_PACKAGE_NAME_PATTERN private val namingSettings = NamingConventionInspectionSettings( KotlinBundle.message("text.Package"), DEFAULT_PACKAGE_NAME_PATTERN, setNamePatternCallback = { value -> namePattern = value } ) override fun checkElement( refEntity: RefEntity, analysisScope: AnalysisScope, inspectionManager: InspectionManager, globalInspectionContext: GlobalInspectionContext ): Array<CommonProblemDescriptor>? { when (refEntity) { is RefFile -> { val psiFile = refEntity.psiElement if (psiFile is KtFile && !psiFile.isInjectedFragment && !psiFile.packageMatchesDirectoryOrImplicit()) { val packageDirective = psiFile.packageDirective if (packageDirective != null) { val qualifiedName = packageDirective.qualifiedName val checkResult = PackageNameInspectionLocal.checkPackageDirective(packageDirective, namingSettings) if (checkResult != null) { return arrayOf(inspectionManager.createProblemDescriptor(checkResult.toErrorMessage(qualifiedName))) } } } } is RefPackage -> { @NonNls val name = StringUtil.getShortName(refEntity.getQualifiedName()) if (name.isEmpty() || InspectionsBundle.message("inspection.reference.default.package") == name) { return null } val checkResult = PackageNameInspectionLocal.checkQualifiedName(name, namingSettings) if (checkResult != null) { return arrayOf(inspectionManager.createProblemDescriptor(checkResult.toErrorMessage(name))) } } else -> { return null } } return null } override fun readSettings(element: Element) { super.readSettings(element) namingSettings.namePattern = namePattern } override fun createOptionsPanel() = namingSettings.createOptionsPanel() override fun getSharedLocalInspectionTool(): LocalInspectionTool { return PackageNameInspectionLocal(this, namingSettings) } }
apache-2.0
siosio/intellij-community
platform/dvcs-impl/src/com/intellij/dvcs/ignore/IgnoredToExcludedSynchronizer.kt
1
11918
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.dvcs.ignore import com.intellij.CommonBundle import com.intellij.ProjectTopics import com.intellij.icons.AllIcons import com.intellij.ide.BrowserUtil import com.intellij.ide.projectView.actions.MarkExcludeRootAction import com.intellij.ide.util.PropertiesComponent import com.intellij.idea.ActionsBundle import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.runInEdt import com.intellij.openapi.application.runReadAction import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtil import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.runModalTask import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.roots.* import com.intellij.openapi.util.Key import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.FilesProcessorImpl import com.intellij.openapi.vcs.VcsBundle.message import com.intellij.openapi.vcs.VcsConfiguration import com.intellij.openapi.vcs.VcsNotificationIdsHolder.Companion.IGNORED_TO_EXCLUDE_NOT_FOUND import com.intellij.openapi.vcs.VcsNotifier import com.intellij.openapi.vcs.changes.ChangeListManager import com.intellij.openapi.vcs.changes.VcsIgnoreManagerImpl import com.intellij.openapi.vcs.changes.ignore.lang.IgnoreFileType import com.intellij.openapi.vcs.changes.shelf.ShelveChangesManager import com.intellij.openapi.vcs.changes.ui.SelectFilesDialog import com.intellij.openapi.vcs.ignore.IgnoredToExcludedSynchronizerConstants.ASKED_MARK_IGNORED_FILES_AS_EXCLUDED_PROPERTY import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.EditorNotificationPanel import com.intellij.ui.EditorNotifications import java.util.* private val LOG = logger<IgnoredToExcludedSynchronizer>() private val excludeAction = object : MarkExcludeRootAction() { fun exclude(module: Module, dirs: Collection<VirtualFile>) = runInEdt { modifyRoots(module, dirs.toTypedArray()) } } /** * Shows [EditorNotifications] in .ignore files with suggestion to exclude ignored directories. * Silently excludes them if [VcsConfiguration.MARK_IGNORED_AS_EXCLUDED] is enabled. * * Not internal service. Can be used directly in related modules. */ @Service class IgnoredToExcludedSynchronizer(project: Project) : FilesProcessorImpl(project, project) { init { project.messageBus.connect(this).subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener { override fun rootsChanged(event: ModuleRootEvent) = updateNotificationState() }) project.messageBus.connect(this).subscribe(AdditionalLibraryRootsListener.TOPIC, (AdditionalLibraryRootsListener { _, _, _, _ -> updateNotificationState() })) } private fun updateNotificationState() { if (synchronizationTurnOff()) return // in case if the project roots changed (e.g. by build tools) then the directories shown in notification can be outdated. // filter directories which excluded or containing source roots and expire notification if needed. ChangeListManager.getInstance(project).invokeAfterUpdate(false) { val fileIndex = ProjectFileIndex.getInstance(project) val sourceRoots = getProjectSourceRoots(project) val acquiredFiles = selectValidFiles() LOG.debug("updateNotificationState, acquiredFiles", acquiredFiles) val filesToRemove = acquiredFiles .asSequence() .filter { file -> runReadAction { fileIndex.isExcluded(file) } || sourceRoots.contains(file) } .toList() LOG.debug("updateNotificationState, filesToRemove", filesToRemove) if (removeFiles(filesToRemove)) { EditorNotifications.getInstance(project).updateAllNotifications() } } } fun isNotEmpty() = !isFilesEmpty() fun clearFiles(files: Collection<VirtualFile>) = removeFiles(files) fun getValidFiles() = with(ChangeListManager.getInstance(project)) { selectValidFiles().filter(this::isIgnoredFile) } private fun wasAskedBefore() = PropertiesComponent.getInstance(project).getBoolean(ASKED_MARK_IGNORED_FILES_AS_EXCLUDED_PROPERTY, false) fun muteForCurrentProject() { PropertiesComponent.getInstance(project).setValue(ASKED_MARK_IGNORED_FILES_AS_EXCLUDED_PROPERTY, true) clearFiles() } fun mutedForCurrentProject() = wasAskedBefore() && !needDoForCurrentProject() override fun doActionOnChosenFiles(files: Collection<VirtualFile>) { if (files.isEmpty()) return markIgnoredAsExcluded(project, files) } override fun doFilterFiles(files: Collection<VirtualFile>) = files.filter(VirtualFile::isValid) override fun needDoForCurrentProject() = VcsConfiguration.getInstance(project).MARK_IGNORED_AS_EXCLUDED fun ignoredUpdateFinished(ignoredPaths: Collection<FilePath>) { ProgressManager.checkCanceled() if (synchronizationTurnOff()) return if (mutedForCurrentProject()) return processIgnored(ignoredPaths) } private fun processIgnored(ignoredPaths: Collection<FilePath>) { val ignoredDirs = determineIgnoredDirsToExclude(project, ignoredPaths) if (allowShowNotification()) { processFiles(ignoredDirs) val editorNotifications = EditorNotifications.getInstance(project) FileEditorManager.getInstance(project).openFiles .forEach { openFile -> if (openFile.fileType is IgnoreFileType) { editorNotifications.updateNotifications(openFile) } } } else if (needDoForCurrentProject()) { doActionOnChosenFiles(doFilterFiles(ignoredDirs)) } } } private fun markIgnoredAsExcluded(project: Project, files: Collection<VirtualFile>) { val ignoredDirsByModule = files .groupBy { ModuleUtil.findModuleForFile(it, project) } //if the directory already excluded then ModuleUtil.findModuleForFile return null and this will filter out such directories from processing. .filterKeys(Objects::nonNull) for ((module, ignoredDirs) in ignoredDirsByModule) { excludeAction.exclude(module!!, ignoredDirs) } } private fun getProjectSourceRoots(project: Project): Set<VirtualFile> = runReadAction { OrderEnumerator.orderEntries(project).withoutSdk().withoutLibraries().sources().usingCache().roots.toHashSet() } private fun containsShelfDirectoryOrUnderIt(filePath: FilePath, shelfPath: String) = FileUtil.isAncestor(shelfPath, filePath.path, false) || FileUtil.isAncestor(filePath.path, shelfPath, false) private fun determineIgnoredDirsToExclude(project: Project, ignoredPaths: Collection<FilePath>): List<VirtualFile> { val sourceRoots = getProjectSourceRoots(project) val fileIndex = ProjectFileIndex.getInstance(project) val shelfPath = ShelveChangesManager.getShelfPath(project) return ignoredPaths .asSequence() .filter(FilePath::isDirectory) //shelf directory usually contains in project and excluding it prevents local history to work on it .filterNot { containsShelfDirectoryOrUnderIt(it, shelfPath) } .mapNotNull(FilePath::getVirtualFile) .filterNot { runReadAction { fileIndex.isExcluded(it) } } //do not propose to exclude if there is a source root inside .filterNot { ignored -> sourceRoots.contains(ignored) } .toList() } private fun selectFilesToExclude(project: Project, ignoredDirs: List<VirtualFile>): Collection<VirtualFile> { val dialog = IgnoredToExcludeSelectDirectoriesDialog(project, ignoredDirs) if (!dialog.showAndGet()) return emptyList() return dialog.selectedFiles } private fun allowShowNotification() = Registry.`is`("vcs.propose.add.ignored.directories.to.exclude", true) private fun synchronizationTurnOff() = !Registry.`is`("vcs.enable.add.ignored.directories.to.exclude", true) class IgnoredToExcludeNotificationProvider : EditorNotifications.Provider<EditorNotificationPanel>() { companion object { private val KEY: Key<EditorNotificationPanel> = Key.create("IgnoredToExcludeNotificationProvider") } override fun getKey(): Key<EditorNotificationPanel> = KEY private fun canCreateNotification(project: Project, file: VirtualFile) = file.fileType is IgnoreFileType && with(project.service<IgnoredToExcludedSynchronizer>()) { !synchronizationTurnOff() && allowShowNotification() && !mutedForCurrentProject() && isNotEmpty() } private fun showIgnoredAction(project: Project) { val allFiles = project.service<IgnoredToExcludedSynchronizer>().getValidFiles() if (allFiles.isEmpty()) return val userSelectedFiles = selectFilesToExclude(project, allFiles) if (userSelectedFiles.isEmpty()) return with(project.service<IgnoredToExcludedSynchronizer>()) { markIgnoredAsExcluded(project, userSelectedFiles) clearFiles(userSelectedFiles) } } private fun muteAction(project: Project) = Runnable { project.service<IgnoredToExcludedSynchronizer>().muteForCurrentProject() EditorNotifications.getInstance(project).updateNotifications(this@IgnoredToExcludeNotificationProvider) } override fun createNotificationPanel(file: VirtualFile, fileEditor: FileEditor, project: Project): EditorNotificationPanel? { if (!canCreateNotification(project, file)) return null return EditorNotificationPanel(fileEditor).apply { icon(AllIcons.General.Information) text = message("ignore.to.exclude.notification.message") createActionLabel(message("ignore.to.exclude.notification.action.view")) { showIgnoredAction(project) } createActionLabel(message("ignore.to.exclude.notification.action.mute"), muteAction(project)) createActionLabel(message("ignore.to.exclude.notification.action.details")) { BrowserUtil.browse("https://www.jetbrains.com/help/idea/content-roots.html#folder-categories") } } } } internal class CheckIgnoredToExcludeAction : DumbAwareAction() { override fun update(e: AnActionEvent) { e.presentation.isEnabled = e.project != null } override fun actionPerformed(e: AnActionEvent) { val project = e.project!! runModalTask(ActionsBundle.message("action.CheckIgnoredAndNotExcludedDirectories.progress"), project, true) { VcsIgnoreManagerImpl.getInstanceImpl(project).awaitRefreshQueue() val ignoredFilePaths = ChangeListManager.getInstance(project).ignoredFilePaths val dirsToExclude = determineIgnoredDirsToExclude(project, ignoredFilePaths) if (dirsToExclude.isEmpty()) { VcsNotifier.getInstance(project) .notifyMinorInfo(IGNORED_TO_EXCLUDE_NOT_FOUND, "", message("ignore.to.exclude.no.directories.found")) } else { val userSelectedFiles = selectFilesToExclude(project, dirsToExclude) if (userSelectedFiles.isNotEmpty()) { markIgnoredAsExcluded(project, userSelectedFiles) } } } } } // do not use SelectFilesDialog.init because it doesn't provide clear statistic: what exactly dialog shown/closed, action clicked private class IgnoredToExcludeSelectDirectoriesDialog( project: Project?, files: List<VirtualFile> ) : SelectFilesDialog(project, files, message("ignore.to.exclude.notification.notice"), null, true, true) { init { title = message("ignore.to.exclude.view.dialog.title") selectedFiles = files setOKButtonText(message("ignore.to.exclude.view.dialog.exclude.action")) setCancelButtonText(CommonBundle.getCancelButtonText()) init() } }
apache-2.0
jwren/intellij-community
plugins/kotlin/uast/uast-kotlin-idea/src/org/jetbrains/uast/kotlin/generate/KotlinUastCodeGenerationPlugin.kt
1
22422
// 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.uast.kotlin.generate import com.intellij.lang.Language import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.* import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.core.* import org.jetbrains.kotlin.idea.refactoring.fqName.fqName import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import org.jetbrains.kotlin.idea.references.KtSimpleNameReferenceDescriptorsImpl import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.idea.util.resolveToKotlinType import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier import org.jetbrains.kotlin.utils.addToStdlib.safeAs import org.jetbrains.uast.* import org.jetbrains.uast.generate.UParameterInfo import org.jetbrains.uast.generate.UastCodeGenerationPlugin import org.jetbrains.uast.generate.UastElementFactory import org.jetbrains.uast.kotlin.* import org.jetbrains.uast.kotlin.internal.KotlinFakeUElement class KotlinUastCodeGenerationPlugin : UastCodeGenerationPlugin { override val language: Language get() = KotlinLanguage.INSTANCE override fun getElementFactory(project: Project): UastElementFactory = KotlinUastElementFactory(project) override fun <T : UElement> replace(oldElement: UElement, newElement: T, elementType: Class<T>): T? { val oldPsi = oldElement.toSourcePsiFakeAware().singleOrNull() ?: return null val newPsi = newElement.sourcePsi?.let { when { it is KtCallExpression && it.parent is KtQualifiedExpression -> it.parent else -> it } } ?: return null val psiFactory = KtPsiFactory(oldPsi.project) val oldParentPsi = oldPsi.parent val (updOldPsi, updNewPsi) = when { oldParentPsi is KtStringTemplateExpression && oldParentPsi.entries.size == 1 -> oldParentPsi to newPsi oldPsi is KtStringTemplateEntry && newPsi !is KtStringTemplateEntry && newPsi is KtExpression -> oldPsi to psiFactory.createBlockStringTemplateEntry(newPsi) oldPsi is KtBlockExpression && newPsi is KtBlockExpression -> { if (!hasBraces(oldPsi) && hasBraces(newPsi)) { oldPsi to psiFactory.createLambdaExpression("none", newPsi.statements.joinToString("\n") { "println()" }).bodyExpression!!.also { it.statements.zip(newPsi.statements).forEach { it.first.replace(it.second) } } } else oldPsi to newPsi } else -> oldPsi to newPsi } val replaced = updOldPsi.replace(updNewPsi)?.safeAs<KtElement>()?.let { ShortenReferences.DEFAULT.process(it) } return when { newElement.sourcePsi is KtCallExpression && replaced is KtQualifiedExpression -> replaced.selectorExpression else -> replaced }?.toUElementOfExpectedTypes(elementType) } override fun bindToElement(reference: UReferenceExpression, element: PsiElement): PsiElement? { val sourcePsi = reference.sourcePsi ?: return null if (sourcePsi !is KtSimpleNameExpression) return null return KtSimpleNameReferenceDescriptorsImpl(sourcePsi) .bindToElement(element, KtSimpleNameReference.ShorteningMode.FORCED_SHORTENING) } override fun shortenReference(reference: UReferenceExpression): UReferenceExpression? { val sourcePsi = reference.sourcePsi ?: return null if (sourcePsi !is KtElement) return null return ShortenReferences.DEFAULT.process(sourcePsi).toUElementOfType() } } private fun hasBraces(oldPsi: KtBlockExpression): Boolean = oldPsi.lBrace != null && oldPsi.rBrace != null class KotlinUastElementFactory(project: Project) : UastElementFactory { private val psiFactory = KtPsiFactory(project) @Suppress("UNUSED_PARAMETER") override fun createQualifiedReference(qualifiedName: String, context: PsiElement?): UQualifiedReferenceExpression? { return psiFactory.createExpression(qualifiedName).let { when (it) { is KtDotQualifiedExpression -> KotlinUQualifiedReferenceExpression(it, null) is KtSafeQualifiedExpression -> KotlinUSafeQualifiedExpression(it, null) else -> null } } } override fun createCallExpression( receiver: UExpression?, methodName: String, parameters: List<UExpression>, expectedReturnType: PsiType?, kind: UastCallKind, context: PsiElement? ): UCallExpression? { if (kind != UastCallKind.METHOD_CALL) return null val name = methodName.quoteIfNeeded() val methodCall = psiFactory.createExpression( buildString { if (receiver != null) { append("a") receiver.sourcePsi?.nextSibling.safeAs<PsiWhiteSpace>()?.let { whitespaces -> append(whitespaces.text) } append(".") } append(name) append("()") } ).getPossiblyQualifiedCallExpression() ?: return null if (receiver != null) { methodCall.parent.safeAs<KtDotQualifiedExpression>()?.receiverExpression?.replace(wrapULiteral(receiver).sourcePsi!!) } val valueArgumentList = methodCall.valueArgumentList for (parameter in parameters) { valueArgumentList?.addArgument(psiFactory.createArgument(wrapULiteral(parameter).sourcePsi as KtExpression)) } if (context !is KtElement) return KotlinUFunctionCallExpression(methodCall, null) val analyzableMethodCall = psiFactory.getAnalyzableMethodCall(methodCall, context) if (analyzableMethodCall.canMoveLambdaOutsideParentheses()) { analyzableMethodCall.moveFunctionLiteralOutsideParentheses() } if (expectedReturnType == null) return KotlinUFunctionCallExpression(analyzableMethodCall, null) val methodCallPsiType = KotlinUFunctionCallExpression(analyzableMethodCall, null).getExpressionType() if (methodCallPsiType == null || !expectedReturnType.isAssignableFrom(GenericsUtil.eliminateWildcards(methodCallPsiType))) { val typeParams = (context as? KtElement)?.let { kontext -> val resolutionFacade = kontext.getResolutionFacade() (expectedReturnType as? PsiClassType)?.parameters?.map { it.resolveToKotlinType(resolutionFacade) } } if (typeParams == null) return KotlinUFunctionCallExpression(analyzableMethodCall, null) for (typeParam in typeParams) { val typeParameter = psiFactory.createTypeArgument(typeParam.fqName?.asString().orEmpty()) analyzableMethodCall.addTypeArgument(typeParameter) } return KotlinUFunctionCallExpression(analyzableMethodCall, null) } return KotlinUFunctionCallExpression(analyzableMethodCall, null) } private fun KtPsiFactory.getAnalyzableMethodCall(methodCall: KtCallExpression, context: KtElement): KtCallExpression { val analyzableElement = ((createExpressionCodeFragment("(null)", context).copy() as KtExpressionCodeFragment) .getContentElement()!! as KtParenthesizedExpression).expression!! val isQualified = methodCall.parent is KtQualifiedExpression return if (isQualified) { (analyzableElement.replaced(methodCall.parent) as KtQualifiedExpression).lastChild as KtCallExpression } else { analyzableElement.replaced(methodCall) } } override fun createCallableReferenceExpression( receiver: UExpression?, methodName: String, context: PsiElement? ): UCallableReferenceExpression? { val text = receiver?.sourcePsi?.text ?: "" val callableExpression = psiFactory.createCallableReferenceExpression("$text::$methodName") ?: return null return KotlinUCallableReferenceExpression(callableExpression, null) } override fun createStringLiteralExpression(text: String, context: PsiElement?): ULiteralExpression { return KotlinStringULiteralExpression(psiFactory.createExpression(StringUtil.wrapWithDoubleQuote(text)), null) } override fun createLongConstantExpression(long: Long, context: PsiElement?): UExpression? { return when (val literalExpr = psiFactory.createExpression(long.toString() + "L")) { is KtConstantExpression -> KotlinULiteralExpression(literalExpr, null) is KtPrefixExpression -> KotlinUPrefixExpression(literalExpr, null) else -> null } } override fun createNullLiteral(context: PsiElement?): ULiteralExpression { return psiFactory.createExpression("null").toUElementOfType()!! } @Suppress("UNUSED_PARAMETER") /*override*/ fun createIntLiteral(value: Int, context: PsiElement?): ULiteralExpression { return psiFactory.createExpression(value.toString()).toUElementOfType()!! } private fun KtExpression.ensureBlockExpressionBraces(): KtExpression { if (this !is KtBlockExpression || hasBraces(this)) return this val blockExpression = psiFactory.createBlock(this.statements.joinToString("\n") { "println()" }) for ((placeholder, statement) in blockExpression.statements.zip(this.statements)) { placeholder.replace(statement) } return blockExpression } @Deprecated("use version with context parameter") fun createIfExpression(condition: UExpression, thenBranch: UExpression, elseBranch: UExpression?): UIfExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createIfExpression(condition, thenBranch, elseBranch, null) } override fun createIfExpression( condition: UExpression, thenBranch: UExpression, elseBranch: UExpression?, context: PsiElement? ): UIfExpression? { val conditionPsi = condition.sourcePsi as? KtExpression ?: return null val thenBranchPsi = thenBranch.sourcePsi as? KtExpression ?: return null val elseBranchPsi = elseBranch?.sourcePsi as? KtExpression return KotlinUIfExpression( psiFactory.createIf(conditionPsi, thenBranchPsi.ensureBlockExpressionBraces(), elseBranchPsi?.ensureBlockExpressionBraces()), givenParent = null ) } @Deprecated("use version with context parameter") fun createParenthesizedExpression(expression: UExpression): UParenthesizedExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createParenthesizedExpression(expression, null) } override fun createParenthesizedExpression(expression: UExpression, context: PsiElement?): UParenthesizedExpression? { val source = expression.sourcePsi ?: return null val parenthesized = psiFactory.createExpression("(${source.text})") as? KtParenthesizedExpression ?: return null return KotlinUParenthesizedExpression(parenthesized, null) } @Deprecated("use version with context parameter") fun createSimpleReference(name: String): USimpleNameReferenceExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createSimpleReference(name, null) } override fun createSimpleReference(name: String, context: PsiElement?): USimpleNameReferenceExpression { return KotlinUSimpleReferenceExpression(psiFactory.createSimpleName(name), null) } @Deprecated("use version with context parameter") fun createSimpleReference(variable: UVariable): USimpleNameReferenceExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createSimpleReference(variable, null) } override fun createSimpleReference(variable: UVariable, context: PsiElement?): USimpleNameReferenceExpression? { return createSimpleReference(variable.name ?: return null, context) } @Deprecated("use version with context parameter") fun createReturnExpresion(expression: UExpression?, inLambda: Boolean): UReturnExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createReturnExpresion(expression, inLambda, null) } override fun createReturnExpresion(expression: UExpression?, inLambda: Boolean, context: PsiElement?): UReturnExpression { val label = if (inLambda && context != null) getParentLambdaLabelName(context)?.let { "@$it" } ?: "" else "" val returnExpression = psiFactory.createExpression("return$label 1") as KtReturnExpression val sourcePsi = expression?.sourcePsi if (sourcePsi != null) { returnExpression.returnedExpression!!.replace(sourcePsi) } else { returnExpression.returnedExpression?.delete() } return KotlinUReturnExpression(returnExpression, null) } private fun getParentLambdaLabelName(context: PsiElement): String? { val lambdaExpression = context.getParentOfType<KtLambdaExpression>(false) ?: return null lambdaExpression.parent.safeAs<KtLabeledExpression>()?.let { return it.getLabelName() } val callExpression = lambdaExpression.getStrictParentOfType<KtCallExpression>() ?: return null callExpression.valueArguments.find { it.getArgumentExpression()?.unpackFunctionLiteral(allowParentheses = false) === lambdaExpression } ?: return null return callExpression.getCallNameExpression()?.text } @Deprecated("use version with context parameter") fun createBinaryExpression( leftOperand: UExpression, rightOperand: UExpression, operator: UastBinaryOperator ): UBinaryExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createBinaryExpression(leftOperand, rightOperand, operator, null) } override fun createBinaryExpression( leftOperand: UExpression, rightOperand: UExpression, operator: UastBinaryOperator, context: PsiElement? ): UBinaryExpression? { val binaryExpression = joinBinaryExpression(leftOperand, rightOperand, operator) ?: return null return KotlinUBinaryExpression(binaryExpression, null) } private fun joinBinaryExpression( leftOperand: UExpression, rightOperand: UExpression, operator: UastBinaryOperator ): KtBinaryExpression? { val leftPsi = leftOperand.sourcePsi ?: return null val rightPsi = rightOperand.sourcePsi ?: return null val binaryExpression = psiFactory.createExpression("a ${operator.text} b") as? KtBinaryExpression ?: return null binaryExpression.left?.replace(leftPsi) binaryExpression.right?.replace(rightPsi) return binaryExpression } @Deprecated("use version with context parameter") fun createFlatBinaryExpression( leftOperand: UExpression, rightOperand: UExpression, operator: UastBinaryOperator ): UPolyadicExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createFlatBinaryExpression(leftOperand, rightOperand, operator, null) } override fun createFlatBinaryExpression( leftOperand: UExpression, rightOperand: UExpression, operator: UastBinaryOperator, context: PsiElement? ): UPolyadicExpression? { fun unwrapParentheses(exp: KtExpression?) { if (exp !is KtParenthesizedExpression) return if (!KtPsiUtil.areParenthesesUseless(exp)) return exp.expression?.let { exp.replace(it) } } val binaryExpression = joinBinaryExpression(leftOperand, rightOperand, operator) ?: return null unwrapParentheses(binaryExpression.left) unwrapParentheses(binaryExpression.right) return psiFactory.createExpression(binaryExpression.text).toUElementOfType()!! } @Deprecated("use version with context parameter") fun createBlockExpression(expressions: List<UExpression>): UBlockExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createBlockExpression(expressions, null) } override fun createBlockExpression(expressions: List<UExpression>, context: PsiElement?): UBlockExpression { val sourceExpressions = expressions.flatMap { it.toSourcePsiFakeAware() } val block = psiFactory.createBlock( sourceExpressions.joinToString(separator = "\n") { "println()" } ) for ((placeholder, psiElement) in block.statements.zip(sourceExpressions)) { placeholder.replace(psiElement) } return KotlinUBlockExpression(block, null) } @Deprecated("use version with context parameter") fun createDeclarationExpression(declarations: List<UDeclaration>): UDeclarationsExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createDeclarationExpression(declarations, null) } override fun createDeclarationExpression(declarations: List<UDeclaration>, context: PsiElement?): UDeclarationsExpression { return object : KotlinUDeclarationsExpression(null), KotlinFakeUElement { override var declarations: List<UDeclaration> = declarations override fun unwrapToSourcePsi(): List<PsiElement> = declarations.flatMap { it.toSourcePsiFakeAware() } } } override fun createLambdaExpression( parameters: List<UParameterInfo>, body: UExpression, context: PsiElement? ): ULambdaExpression? { val resolutionFacade = (context as? KtElement)?.getResolutionFacade() val validator = (context as? KtElement)?.let { usedNamesFilter(it) } ?: { true } val newLambdaStatements = if (body is UBlockExpression) { body.expressions.flatMap { member -> when { member is UReturnExpression -> member.returnExpression?.toSourcePsiFakeAware().orEmpty() else -> member.toSourcePsiFakeAware() } } } else listOf(body.sourcePsi!!) val ktLambdaExpression = psiFactory.createLambdaExpression( parameters.joinToString(", ") { p -> val ktype = resolutionFacade?.let { p.type?.resolveToKotlinType(it) } StringBuilder().apply { append(p.suggestedName ?: ktype?.let { KotlinNameSuggester.suggestNamesByType(it, validator).firstOrNull() }) ?: KotlinNameSuggester.suggestNameByName("v", validator) ktype?.fqName?.toString()?.let { append(": ").append(it) } } }, newLambdaStatements.joinToString("\n") { "placeholder" } ) for ((old, new) in ktLambdaExpression.bodyExpression!!.statements.zip(newLambdaStatements)) { old.replace(new) } return ktLambdaExpression.toUElementOfType()!! } @Deprecated("use version with context parameter") fun createLambdaExpression(parameters: List<UParameterInfo>, body: UExpression): ULambdaExpression? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createLambdaExpression(parameters, body, null) } override fun createLocalVariable( suggestedName: String?, type: PsiType?, initializer: UExpression, immutable: Boolean, context: PsiElement? ): ULocalVariable { val resolutionFacade = (context as? KtElement)?.getResolutionFacade() val validator = (context as? KtElement)?.let { usedNamesFilter(it) } ?: { true } val ktype = resolutionFacade?.let { type?.resolveToKotlinType(it) } val function = psiFactory.createFunction( buildString { append("fun foo() { ") append(if (immutable) "val" else "var") append(" ") append(suggestedName ?: ktype?.let { KotlinNameSuggester.suggestNamesByType(it, validator).firstOrNull() }) ?: KotlinNameSuggester.suggestNameByName("v", validator) ktype?.fqName?.toString()?.let { append(": ").append(it) } append(" = null") append("}") } ) val ktVariable = PsiTreeUtil.findChildOfType(function, KtVariableDeclaration::class.java)!! val newVariable = ktVariable.initializer!!.replace(initializer.sourcePsi!!).parent return newVariable.toUElementOfType<UVariable>() as ULocalVariable } @Deprecated("use version with context parameter") fun createLocalVariable( suggestedName: String?, type: PsiType?, initializer: UExpression, immutable: Boolean ): ULocalVariable? { logger<KotlinUastElementFactory>().error("Please switch caller to the version with a context parameter") return createLocalVariable(suggestedName, type, initializer, immutable, null) } } private fun usedNamesFilter(context: KtElement): (String) -> Boolean { val scope = context.getResolutionScope() return { name: String -> scope.findClassifier(Name.identifier(name), NoLookupLocation.FROM_IDE) == null } }
apache-2.0
jwren/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/search/usagesSearch/utilsIndependent.kt
4
5279
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.search.usagesSearch import com.intellij.openapi.application.ApplicationManager import com.intellij.psi.* import com.intellij.psi.search.SearchScope import com.intellij.psi.search.searches.MethodReferencesSearch import com.intellij.psi.search.searches.ReferencesSearch import org.jetbrains.kotlin.asJava.elements.KtLightElement import org.jetbrains.kotlin.asJava.elements.KtLightMethod import org.jetbrains.kotlin.asJava.toLightMethods import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.createConstructorHandle import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest import org.jetbrains.kotlin.idea.search.declarationsSearch.searchInheritors import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.contains fun PsiElement.processDelegationCallConstructorUsages(scope: SearchScope, process: (KtCallElement) -> Boolean): Boolean { val task = buildProcessDelegationCallConstructorUsagesTask(scope, process) return task() } // should be executed under read-action, returns long-running part to be executed outside read-action fun PsiElement.buildProcessDelegationCallConstructorUsagesTask(scope: SearchScope, process: (KtCallElement) -> Boolean): () -> Boolean { ApplicationManager.getApplication().assertReadAccessAllowed() val task1 = buildProcessDelegationCallKotlinConstructorUsagesTask(scope, process) val task2 = buildProcessDelegationCallJavaConstructorUsagesTask(scope, process) return { task1() && task2() } } private fun PsiElement.buildProcessDelegationCallKotlinConstructorUsagesTask( scope: SearchScope, process: (KtCallElement) -> Boolean ): () -> Boolean { val element = unwrapped if (element != null && element !in scope) return { true } val klass = when (element) { is KtConstructor<*> -> element.getContainingClassOrObject() is KtClass -> element else -> return { true } } if (klass !is KtClass || element !is KtDeclaration) return { true } val constructorHandler = createConstructorHandle(element) if (!processClassDelegationCallsToSpecifiedConstructor(klass, constructorHandler, process)) return { false } // long-running task, return it to execute outside read-action return { processInheritorsDelegatingCallToSpecifiedConstructor(klass, scope, constructorHandler, process) } } private fun PsiElement.buildProcessDelegationCallJavaConstructorUsagesTask( scope: SearchScope, process: (KtCallElement) -> Boolean ): () -> Boolean { if (this is KtLightElement<*, *>) return { true } // TODO: Temporary hack to avoid NPE while KotlinNoOriginLightMethod is around if (this is KtLightMethod && this.kotlinOrigin == null) return { true } if (!(this is PsiMethod && isConstructor)) return { true } val klass = containingClass ?: return { true } val ctorHandle = createConstructorHandle(this) return { processInheritorsDelegatingCallToSpecifiedConstructor(klass, scope, ctorHandle, process) } } private fun processInheritorsDelegatingCallToSpecifiedConstructor( klass: PsiElement, scope: SearchScope, constructorCallComparator: KotlinSearchUsagesSupport.ConstructorCallHandle, process: (KtCallElement) -> Boolean ): Boolean { return HierarchySearchRequest(klass, scope, false).searchInheritors().all { runReadAction { val unwrapped = it.takeIf { it.isValid }?.unwrapped if (unwrapped is KtClass) processClassDelegationCallsToSpecifiedConstructor(unwrapped, constructorCallComparator, process) else true } } } private fun processClassDelegationCallsToSpecifiedConstructor( klass: KtClass, constructorCallHandle: KotlinSearchUsagesSupport.ConstructorCallHandle, process: (KtCallElement) -> Boolean ): Boolean { for (secondaryConstructor in klass.secondaryConstructors) { val delegationCall = secondaryConstructor.getDelegationCall() if (constructorCallHandle.referencedTo(delegationCall)) { if (!process(delegationCall)) return false } } if (!klass.isEnum()) return true for (declaration in klass.declarations) { if (declaration is KtEnumEntry) { val delegationCall = declaration.superTypeListEntries.firstOrNull() as? KtSuperTypeCallEntry ?: continue if (constructorCallHandle.referencedTo(delegationCall.calleeExpression)) { if (!process(delegationCall)) return false } } } return true } fun PsiElement.searchReferencesOrMethodReferences(): Collection<PsiReference> { val lightMethods = toLightMethods() return if (lightMethods.isNotEmpty()) { lightMethods.flatMapTo(LinkedHashSet()) { MethodReferencesSearch.search(it) } } else { ReferencesSearch.search(this).findAll() } }
apache-2.0
vovagrechka/fucking-everything
phizdets/phizdetsc/src/org/jetbrains/kotlin/js/descriptorUtils/descriptorUtils.kt
3
2315
/* * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.js.descriptorUtils import com.intellij.openapi.util.text.StringUtil import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.utils.addToStdlib.check val KotlinType.nameIfStandardType: Name? get() = constructor.declarationDescriptor?.check(KotlinBuiltIns::isBuiltIn)?.name fun KotlinType.getJetTypeFqName(printTypeArguments: Boolean): String { val declaration = requireNotNull(constructor.declarationDescriptor) if (declaration is TypeParameterDescriptor) { return StringUtil.join(declaration.upperBounds, { type -> type.getJetTypeFqName(printTypeArguments) }, "&") } val typeArguments = arguments val typeArgumentsAsString: String if (printTypeArguments && !typeArguments.isEmpty()) { val joinedTypeArguments = StringUtil.join(typeArguments, { projection -> projection.type.getJetTypeFqName(false) }, ", ") typeArgumentsAsString = "<$joinedTypeArguments>" } else { typeArgumentsAsString = "" } return DescriptorUtils.getFqName(declaration).asString() + typeArgumentsAsString } fun ClassDescriptor.hasPrimaryConstructor(): Boolean = unsubstitutedPrimaryConstructor != null val DeclarationDescriptor.isCoroutineLambda: Boolean get() = this is AnonymousFunctionDescriptor && isSuspend
apache-2.0
jwren/intellij-community
plugins/git4idea/src/git4idea/pull/GitPullDialog.kt
1
14707
// 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 git4idea.pull import com.intellij.codeInsight.hint.HintUtil import com.intellij.dvcs.DvcsUtil.sortRepositories import com.intellij.ide.actions.RefreshAction import com.intellij.ide.ui.laf.darcula.DarculaUIUtil.BW import com.intellij.openapi.actionSystem.* import com.intellij.openapi.components.service import com.intellij.openapi.keymap.KeymapUtil import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task.Backgroundable import com.intellij.openapi.project.Project import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.text.HtmlChunk import com.intellij.openapi.util.text.HtmlChunk.Element.html import com.intellij.openapi.vcs.VcsNotifier import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.MutableCollectionComboBoxModel import com.intellij.ui.SimpleListCellRenderer import com.intellij.ui.components.DropDownLink import com.intellij.util.ui.JBDimension import com.intellij.util.ui.JBUI import git4idea.GitNotificationIdsHolder.Companion.FETCH_ERROR import git4idea.GitRemoteBranch import git4idea.GitUtil import git4idea.GitVcs import git4idea.branch.GitBranchUtil import git4idea.config.GitExecutableManager import git4idea.config.GitPullSettings import git4idea.config.GitVersionSpecialty.NO_VERIFY_SUPPORTED import git4idea.fetch.GitFetchSupport import git4idea.i18n.GitBundle import git4idea.merge.GIT_REF_PROTOTYPE_VALUE import git4idea.merge.createRepositoryField import git4idea.merge.createSouthPanelWithOptionsDropDown import git4idea.merge.dialog.* import git4idea.merge.validateBranchExists import git4idea.repo.GitRemote import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryManager import git4idea.ui.ComboBoxWithAutoCompletion import net.miginfocom.layout.AC import net.miginfocom.layout.CC import net.miginfocom.layout.LC import net.miginfocom.swing.MigLayout import java.awt.Insets import java.awt.event.ItemEvent import java.awt.event.KeyEvent import javax.swing.JComponent import javax.swing.JPanel import javax.swing.KeyStroke import javax.swing.SwingConstants class GitPullDialog(private val project: Project, private val roots: List<VirtualFile>, private val defaultRoot: VirtualFile) : DialogWrapper(project) { val selectedOptions = mutableSetOf<GitPullOption>() private val fetchSupport = project.service<GitFetchSupport>() private val pullSettings = project.service<GitPullSettings>() private val repositories = sortRepositories(GitRepositoryManager.getInstance(project).repositories) private val branches = collectBranches().toMutableMap() private val optionInfos = mutableMapOf<GitPullOption, OptionInfo<GitPullOption>>() private val popupBuilder = createPopupBuilder() private val repositoryField = createRepoField() private val remoteField = createRemoteField() private val branchField = createBranchField() private val commandPanel = createCommandPanel() private val optionsPanel = GitOptionsPanel(::optionChosen, ::getOptionInfo) private val panel = createPanel() private val isNoVerifySupported = NO_VERIFY_SUPPORTED.existsIn(GitExecutableManager.getInstance().getVersion(project)) init { updateTitle() setOKButtonText(GitBundle.message("pull.button")) loadSettings() updateRemotesField() init() updateUi() } override fun createCenterPanel() = panel override fun getPreferredFocusedComponent() = branchField override fun createSouthPanel() = createSouthPanelWithOptionsDropDown(super.createSouthPanel(), createOptionsDropDown()) override fun getHelpId() = "reference.VersionControl.Git.Pull" override fun doValidateAll() = listOf(::validateRepositoryField, ::validateRemoteField, ::validateBranchField).mapNotNull { it() } override fun doOKAction() { try { saveSettings() } finally { super.doOKAction() } } fun gitRoot() = getSelectedRepository()?.root ?: error("No selected repository found") fun getSelectedRemote(): GitRemote = remoteField.item ?: error("No selected remote found") fun getSelectedBranch(): GitRemoteBranch { val repository = getSelectedRepository() ?: error("No selected repository found") val remote = getSelectedRemote() val branchName = "${remote.name}/${branchField.item}" return repository.branches.findRemoteBranch(branchName) ?: error("Unable to find remote branch: $branchName") } fun isCommitAfterMerge() = GitPullOption.NO_COMMIT !in selectedOptions private fun getRemote(): GitRemote? = remoteField.item private fun loadSettings() { selectedOptions += pullSettings.options } private fun saveSettings() { pullSettings.options = selectedOptions } private fun collectBranches() = repositories.associateWith { repository -> getBranchesInRepo(repository) } private fun getBranchesInRepo(repository: GitRepository) = repository.branches.remoteBranches .sortedBy { branch -> branch.nameForRemoteOperations } .groupBy { branch -> branch.remote } private fun validateRepositoryField(): ValidationInfo? { return if (getSelectedRepository() != null) null else ValidationInfo(GitBundle.message("pull.repository.not.selected.error"), repositoryField) } private fun validateRemoteField(): ValidationInfo? { return if (getRemote() != null) null else ValidationInfo(GitBundle.message("pull.remote.not.selected"), remoteField) } private fun validateBranchField() = validateBranchExists(branchField, "pull.branch.not.selected.error") private fun getSelectedRepository(): GitRepository? = repositoryField.item private fun updateRemotesField() { val repository = getSelectedRepository() val model = remoteField.model as MutableCollectionComboBoxModel model.update(repository?.remotes?.toList() ?: emptyList()) model.selectedItem = getCurrentOrDefaultRemote(repository) } private fun updateBranchesField() { var branchToSelect = branchField.item val repository = getSelectedRepository() ?: return val remote = getRemote() ?: return val branches = GitBranchUtil.sortBranchNames(getRemoteBranches(repository, remote)) val model = branchField.model as MutableCollectionComboBoxModel model.update(branches) if (branchToSelect == null || branchToSelect !in branches) { branchToSelect = repository.currentBranch?.findTrackedBranch(repository)?.nameForRemoteOperations ?: branches.find { branch -> branch == repository.currentBranchName } ?: "" } if (branchToSelect.isEmpty()) { startTrackingValidation() } branchField.selectedItem = branchToSelect } private fun getRemoteBranches(repository: GitRepository, remote: GitRemote): List<String> { return branches[repository]?.get(remote)?.map { it.nameForRemoteOperations } ?: emptyList() } private fun getCurrentOrDefaultRemote(repository: GitRepository?): GitRemote? { val remotes = repository?.remotes ?: return null if (remotes.isEmpty()) { return null } return GitUtil.getTrackInfoForCurrentBranch(repository)?.remote ?: GitUtil.getDefaultOrFirstRemote(remotes) } private fun optionChosen(option: GitPullOption) { if (option !in selectedOptions) { selectedOptions += option } else { selectedOptions -= option } updateUi() } private fun performFetch() { if (fetchSupport.isFetchRunning) { return } val repository = getSelectedRepository() val remote = getRemote() if (repository == null || remote == null) { VcsNotifier.getInstance(project).notifyError(FETCH_ERROR, GitBundle.message("pull.fetch.failed.notification.title"), GitBundle.message("pull.fetch.failed.notification.text")) return } GitVcs.runInBackground(getFetchTask(repository, remote)) } private fun getFetchTask(repository: GitRepository, remote: GitRemote) = object : Backgroundable(project, GitBundle.message("fetching"), true) { override fun run(indicator: ProgressIndicator) { fetchSupport.fetch(repository, remote) } override fun onSuccess() { branches[repository] = getBranchesInRepo(repository) if (getSelectedRepository() == repository && getRemote() == remote) { updateBranchesField() } } } private fun createPopupBuilder() = GitOptionsPopupBuilder( project, GitBundle.message("pull.options.modify.popup.title"), ::getOptions, ::getOptionInfo, ::isOptionSelected, ::isOptionEnabled, ::optionChosen ) private fun isOptionSelected(option: GitPullOption) = option in selectedOptions private fun createOptionsDropDown() = DropDownLink(GitBundle.message("merge.options.modify")) { popupBuilder.createPopup() }.apply { mnemonic = KeyEvent.VK_M } private fun getOptionInfo(option: GitPullOption) = optionInfos.computeIfAbsent(option) { OptionInfo(option, option.option, option.description) } private fun getOptions(): List<GitPullOption> = GitPullOption.values().toMutableList().apply { if (!isNoVerifySupported) { remove(GitPullOption.NO_VERIFY) } } private fun updateUi() { optionsPanel.rerender(selectedOptions) rerender() } private fun rerender() { window.pack() window.revalidate() pack() repaint() } private fun isOptionEnabled(option: GitPullOption) = selectedOptions.all { it.isOptionSuitable(option) } private fun updateTitle() { val currentBranchName = getSelectedRepository()?.currentBranchName title = (if (currentBranchName.isNullOrEmpty()) GitBundle.message("pull.dialog.title") else GitBundle.message("pull.dialog.with.branch.title", currentBranchName)) } private fun createPanel() = JPanel().apply { layout = MigLayout(LC().insets("0").hideMode(3), AC().grow()) add(commandPanel, CC().growX()) add(optionsPanel, CC().newline().width("100%").alignY("top")) } private fun showRootField() = roots.size > 1 private fun createCommandPanel() = JPanel().apply { val colConstraints = if (showRootField()) AC().grow(100f, 0, 3) else AC().grow(100f, 2) layout = MigLayout( LC() .fillX() .insets("0") .gridGap("0", "0") .noVisualPadding(), colConstraints) if (showRootField()) { add(repositoryField, CC() .gapAfter("0") .minWidth("${JBUI.scale(115)}px") .growX()) } add(createCmdLabel(), CC() .gapAfter("0") .alignY("top") .minWidth("${JBUI.scale(85)}px")) add(remoteField, CC() .alignY("top") .minWidth("${JBUI.scale(90)}px")) add(branchField, CC() .alignY("top") .minWidth("${JBUI.scale(250)}px") .growX()) } private fun createCmdLabel() = CmdLabel("git pull", Insets(1, if (showRootField()) 0 else 1, 1, 0), JBDimension(JBUI.scale(85), branchField.preferredSize.height, true)) private fun createRepoField() = createRepositoryField(repositories, defaultRoot).apply { addActionListener { updateTitle() updateRemotesField() } } private fun createRemoteField() = ComboBox<GitRemote>(MutableCollectionComboBoxModel()).apply { isSwingPopup = false renderer = SimpleListCellRenderer.create( HtmlChunk.text(GitBundle.message("util.remote.renderer.none")).italic().wrapWith(html()).toString() ) { it.name } @Suppress("UsePropertyAccessSyntax") setUI(FlatComboBoxUI( outerInsets = Insets(BW.get(), 0, BW.get(), 0), popupEmptyText = GitBundle.message("pull.branch.no.matching.remotes"))) item = getCurrentOrDefaultRemote(getSelectedRepository()) addItemListener { e -> if (e.stateChange == ItemEvent.SELECTED) { updateBranchesField() } } } private fun createBranchField() = ComboBoxWithAutoCompletion(MutableCollectionComboBoxModel(mutableListOf<String>()), project).apply { prototypeDisplayValue = GIT_REF_PROTOTYPE_VALUE setPlaceholder(GitBundle.message("pull.branch.field.placeholder")) object : RefreshAction() { override fun actionPerformed(e: AnActionEvent) { popup?.hide() performFetch() } override fun update(e: AnActionEvent) { e.presentation.isEnabled = true } }.registerCustomShortcutSet(getFetchActionShortcut(), this) @Suppress("UsePropertyAccessSyntax") setUI(FlatComboBoxUI( Insets(1, 0, 1, 1), Insets(BW.get(), 0, BW.get(), BW.get()), GitBundle.message("pull.branch.nothing.to.pull"), this@GitPullDialog::createBranchFieldPopupComponent)) } private fun createBranchFieldPopupComponent(content: JComponent) = JPanel().apply { layout = MigLayout(LC().insets("0")) add(content, CC().width("100%")) val hintLabel = HintUtil.createAdComponent( GitBundle.message("pull.dialog.fetch.shortcuts.hint", getFetchActionShortcutText()), JBUI.CurrentTheme.BigPopup.advertiserBorder(), SwingConstants.LEFT) hintLabel.preferredSize = JBDimension.create(hintLabel.preferredSize, true) .withHeight(17) add(hintLabel, CC().newline().width("100%")) } private fun getFetchActionShortcut(): ShortcutSet { val refreshActionShortcut = ActionManager.getInstance().getAction(IdeActions.ACTION_REFRESH).shortcutSet if (refreshActionShortcut.shortcuts.isNotEmpty()) { return refreshActionShortcut } else { return FETCH_ACTION_SHORTCUT } } private fun getFetchActionShortcutText() = KeymapUtil.getPreferredShortcutText(getFetchActionShortcut().shortcuts) companion object { private val FETCH_ACTION_SHORTCUT = if (SystemInfo.isMac) CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_R, KeyEvent.META_DOWN_MASK)) else CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_F5, KeyEvent.CTRL_DOWN_MASK)) } }
apache-2.0
jwren/intellij-community
plugins/kotlin/completion/tests/testData/handlers/charFilter/CommaForFunction1.kt
13
73
fun foo() {} fun bar() { x(<caret>) } // ELEMENT: foo // CHAR: ','
apache-2.0
jwren/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/functionWithLambdaExpressionBody/wrapRun/getterIsUsed.kt
1
616
// "Convert to run { ... }" "false" // TOOL: org.jetbrains.kotlin.idea.inspections.FunctionWithLambdaExpressionBodyInspection // ACTION: Convert property getter to initializer // ACTION: Convert to anonymous function // ACTION: Convert to block body // ACTION: Convert to multi-line lambda // ACTION: Do not show return expression hints // ACTION: Enable a trailing comma by default in the formatter // ACTION: Specify explicit lambda signature // ACTION: Specify explicit lambda signature // ACTION: Specify type explicitly // ACTION: Specify type explicitly val test get() = <caret>{ "" } fun foo() { test() }
apache-2.0
vovagrechka/fucking-everything
phizdets/phizdetsc/src/org/jetbrains/kotlin/js/parser/parserUtils.kt
3
2955
/* * Copyright 2010-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.kotlin.js.parser import com.google.gwt.dev.js.* import com.google.gwt.dev.js.rhino.* import org.jetbrains.kotlin.js.backend.ast.JsFunction import org.jetbrains.kotlin.js.backend.ast.JsFunctionScope import org.jetbrains.kotlin.js.backend.ast.JsScope import org.jetbrains.kotlin.js.backend.ast.JsStatement import org.jetbrains.kotlin.js.common.SourceInfoImpl import java.io.* import java.util.* private val FAKE_SOURCE_INFO = SourceInfoImpl(null, 0, 0, 0, 0) fun parse(code: String, reporter: ErrorReporter, scope: JsScope): List<JsStatement> { val insideFunction = scope is JsFunctionScope val node = parse(code, 0, reporter, insideFunction, Parser::parse) return node.toJsAst(scope, JsAstMapper::mapStatements) } fun parseFunction(code: String, offset: Int, reporter: ErrorReporter, scope: JsScope): JsFunction = parse(code, offset, reporter, insideFunction = false) { addObserver(FunctionParsingObserver()) primaryExpr(it) }.toJsAst(scope, JsAstMapper::mapFunction) private class FunctionParsingObserver : Observer { var functionsStarted = 0 override fun update(o: Observable?, arg: Any?) { when (arg) { is ParserEvents.OnFunctionParsingStart -> { functionsStarted++ } is ParserEvents.OnFunctionParsingEnd -> { functionsStarted-- if (functionsStarted == 0) { arg.tokenStream.ungetToken(TokenStream.EOF) } } } } } inline private fun parse( code: String, offset: Int, reporter: ErrorReporter, insideFunction: Boolean, parseAction: Parser.(TokenStream)->Any ): Node { Context.enter().setErrorReporter(reporter) try { val ts = TokenStream(StringReader(code, offset), "<parser>", FAKE_SOURCE_INFO.line) val parser = Parser(IRFactory(ts), insideFunction) return parser.parseAction(ts) as Node } finally { Context.exit() } } inline private fun <T> Node.toJsAst(scope: JsScope, mapAction: JsAstMapper.(Node)->T): T = JsAstMapper(scope).mapAction(this) private fun StringReader(string: String, offset: Int): Reader { val reader = StringReader(string) reader.skip(offset.toLong()) return reader }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/redundantIf/assignExpression.kt
13
110
// "Remove redundant 'if' statement" "true" fun bar(p: Int) { val v1 = <caret>if (p > 0) true else false }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/movePackage/movePackage/before/a/specificImportsWithAliases.kt
26
139
package a import A as AA import foo as foofoo import x as xx fun bar() { val t: AA = AA() foofoo() println(xx) xx = "" }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/j2k/new/tests/testData/newJ2k/for/nameConflict4.kt
13
199
internal class A { fun foo(p: Boolean) { var i = 1 while (i < 1000) { println(i) i *= 2 } if (p) { val i = 10 } } }
apache-2.0
zielu/GitToolBox
src/test/kotlin/zielu/gittoolbox/ui/config/v2/props/IntPropWithOverrideTest.kt
1
2463
package zielu.gittoolbox.ui.config.v2.props import com.intellij.openapi.observable.properties.AtomicBooleanProperty import com.intellij.openapi.observable.properties.AtomicLazyProperty import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertAll import zielu.gittoolbox.config.override.IntValueOverride import zielu.intellij.test.MockItemSelectable internal class IntPropWithOverrideTest { private val valueProperty = AtomicLazyProperty { 0 } private val overrideProperty = AtomicBooleanProperty(false) private var appValue = 0 private val prjValue = IntValueOverride() private var valueUi = 0 private val overrideUi = MockItemSelectable() private fun createProp(): IntPropWithOverride { return IntPropWithOverride( valueProperty, overrideProperty, this::appValue, prjValue, { valueUi = it }, overrideUi ) } @Test fun `initial app value is propagated to value property`() { // given appValue = 1 // when createProp() // then assertThat(valueProperty.get()).isEqualTo(appValue) } @Test fun `initial project value is propagated to value property`() { // given prjValue.enabled = true prjValue.value = 1 // when createProp() // then assertThat(valueProperty.get()).isEqualTo(prjValue.value) } @Test fun `value is applied to project config when override is enabled`() { // given val prop = createProp() overrideProperty.set(true) valueProperty.set(1) // when prop.apply() // then assertAll( { assertThat(prjValue.enabled).isTrue }, { assertThat(prjValue.value).isEqualTo(valueProperty.get()) } ) } @Test fun `value is not applied to project config when override is enabled`() { // given val prop = createProp() // when prop.apply() // then assertAll( { assertThat(prjValue.enabled).isFalse }, { assertThat(prjValue.value).isZero() } ) } @Test fun `ui is refreshed when override is changed`() { // given val valueForPrj = 1 prjValue.value = valueForPrj createProp() // when overrideUi.selectedObjects = arrayOf(1) overrideUi.fireSelected() // then assertThat(valueUi).isEqualTo(valueForPrj) // when overrideUi.selectedObjects = null overrideUi.fireSelected() // then assertThat(valueUi).isZero() } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/kdoc/KDocFinderTest.kt
2
3733
// 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.kdoc import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.test.util.slashedPath import org.junit.Assert import org.junit.internal.runners.JUnit38ClassRunner import org.junit.runner.RunWith @RunWith(JUnit38ClassRunner::class) class KDocFinderTest : LightPlatformCodeInsightFixtureTestCase() { override fun getTestDataPath() = IDEA_TEST_DATA_DIR.resolve("kdoc/finder").slashedPath fun testConstructor() { myFixture.configureByFile(getTestName(false) + ".kt") val declaration = (myFixture.file as KtFile).declarations[0] val descriptor = declaration.unsafeResolveToDescriptor() as ClassDescriptor val constructorDescriptor = descriptor.unsubstitutedPrimaryConstructor!! val doc = constructorDescriptor.findKDoc() Assert.assertEquals("Doc for constructor of class C.", doc!!.getContent()) } fun testAnnotated() { myFixture.configureByFile(getTestName(false) + ".kt") val declaration = (myFixture.file as KtFile).declarations[0] val descriptor = declaration.unsafeResolveToDescriptor() as ClassDescriptor val overriddenFunctionDescriptor = descriptor.defaultType.memberScope.getContributedFunctions(Name.identifier("xyzzy"), NoLookupLocation.FROM_TEST).single() val doc = overriddenFunctionDescriptor.findKDoc() Assert.assertEquals("Doc for method xyzzy", doc!!.getContent()) } fun testOverridden() { myFixture.configureByFile(getTestName(false) + ".kt") val declaration = (myFixture.file as KtFile).declarations.single { it.name == "Bar" } val descriptor = declaration.unsafeResolveToDescriptor() as ClassDescriptor val overriddenFunctionDescriptor = descriptor.defaultType.memberScope.getContributedFunctions(Name.identifier("xyzzy"), NoLookupLocation.FROM_TEST).single() val doc = overriddenFunctionDescriptor.findKDoc() Assert.assertEquals("Doc for method xyzzy", doc!!.getContent()) } fun testOverriddenWithSubstitutedType() { myFixture.configureByFile(getTestName(false) + ".kt") val declaration = (myFixture.file as KtFile).declarations.single { it.name == "Bar" } val descriptor = declaration.unsafeResolveToDescriptor() as ClassDescriptor val overriddenFunctionDescriptor = descriptor.defaultType.memberScope.getContributedFunctions(Name.identifier("xyzzy"), NoLookupLocation.FROM_TEST).single() val doc = overriddenFunctionDescriptor.findKDoc() Assert.assertEquals("Doc for method xyzzy", doc!!.getContent()) } fun testProperty() { myFixture.configureByFile(getTestName(false) + ".kt") val declaration = (myFixture.file as KtFile).declarations.single { it.name == "Foo" } val descriptor = declaration.unsafeResolveToDescriptor() as ClassDescriptor val propertyDescriptor = descriptor.defaultType.memberScope.getContributedVariables(Name.identifier("xyzzy"), NoLookupLocation.FROM_TEST).single() val doc = propertyDescriptor.findKDoc() Assert.assertEquals("Doc for property xyzzy", doc!!.getContent()) } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/util/ijPlatformUtil.kt
3
451
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:JvmName("IjPlatformUtil") package org.jetbrains.kotlin.idea.util import com.intellij.openapi.projectRoots.ProjectJdkTable import org.jetbrains.kotlin.idea.util.application.runReadAction fun getProjectJdkTableSafe(): ProjectJdkTable = runReadAction { ProjectJdkTable.getInstance() }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/checker/NullAsAnnotationArgument.kt
13
142
// test for KT-5337 package test annotation class A(val value: String) @A(<error>null</error>) fun foo() {} @A(<error>null</error>) class B
apache-2.0
xmartlabs/bigbang
ui/src/main/java/com/xmartlabs/bigbang/ui/common/recyclerview/BaseViewHolder.kt
1
568
package com.xmartlabs.bigbang.ui.common.recyclerview import android.content.Context import android.content.res.Resources import android.support.v7.widget.RecyclerView import android.view.View open class BaseViewHolder(view: View) : RecyclerView.ViewHolder(view) { /** * Returns the context the view is running in, through which it can * access the current theme, resources, etc. */ protected val context: Context = itemView.context /** Resources instance for the application's package */ protected val resources: Resources = context.resources }
apache-2.0
testIT-LivingDoc/livingdoc2
livingdoc-converters/src/main/kotlin/org/livingdoc/converters/time/LocalDateTimeConverter.kt
2
596
package org.livingdoc.converters.time import java.time.LocalDateTime import java.time.format.DateTimeFormatter /** * This converter parses a String to the local date and time format */ open class LocalDateTimeConverter : AbstractTemporalConverter<LocalDateTime>() { override fun defaultFormatter(): DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME override fun doParse(value: String, formatter: DateTimeFormatter): LocalDateTime = LocalDateTime.parse(value, formatter) override fun canConvertTo(targetType: Class<*>) = LocalDateTime::class.java == targetType }
apache-2.0
joaomneto/TitanCompanion
src/main/java/pt/joaomneto/titancompanion/adapter/SavegameListAdapter.kt
1
2452
package pt.joaomneto.titancompanion.adapter import android.content.Context import android.view.ContextMenu import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.ImageView import android.widget.TextView import java.text.SimpleDateFormat import pt.joaomneto.titancompanion.LoadAdventureActivity import pt.joaomneto.titancompanion.R import pt.joaomneto.titancompanion.consts.FightingFantasyGamebook class SavegameListAdapter(private val ctx: Context, private val values: List<Savegame>) : ArrayAdapter<Savegame>( ctx, -1, values ), View.OnCreateContextMenuListener { private val adv: LoadAdventureActivity = ctx as LoadAdventureActivity override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val inflater = ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater val robotView = inflater.inflate(R.layout.component_load_dventure, parent, false) val nameValue = robotView.rootView.findViewById<TextView>(R.id.nameValue) val gamebookValue = robotView.rootView.findViewById<TextView>(R.id.gamebookValue) val dateValue = robotView.rootView.findViewById<TextView>(R.id.dateValue) val gamebookIcon = robotView.rootView.findViewById<ImageView>(R.id.gamebookIcon) val value = values[position].getFilename() val tokens = value.split("_".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() nameValue.text = tokens[2] val gamebookNameId = adv.resources.getIdentifier( tokens[1].toLowerCase(), "string", adv.applicationContext.packageName ) val gamebookCoverId = adv.resources.getIdentifier( "ff" + FightingFantasyGamebook.gamebookFromInitials(tokens[1].toLowerCase()), "drawable", adv.applicationContext.packageName ) gamebookValue.setText(gamebookNameId) dateValue.text = df.format(values[position].getLastUpdated()) gamebookIcon.setImageResource(gamebookCoverId) return robotView } override fun onCreateContextMenu( contextMenu: ContextMenu, view: View, contextMenuInfo: ContextMenu.ContextMenuInfo ) { println() } companion object { private val df = SimpleDateFormat("yyyy-MM-dd HH:mm") } }
lgpl-3.0
TachiWeb/TachiWeb-Server
Tachiyomi-App/src/main/java/eu/kanade/tachiyomi/network/PersistentCookieStore.kt
1
2455
package eu.kanade.tachiyomi.network import android.content.Context import okhttp3.Cookie import okhttp3.HttpUrl import java.net.URI import java.util.concurrent.ConcurrentHashMap class PersistentCookieStore(context: Context) { private val cookieMap = ConcurrentHashMap<String, List<Cookie>>() private val prefs = context.getSharedPreferences("cookie_store", Context.MODE_PRIVATE) init { for ((key, value) in prefs.all) { @Suppress("UNCHECKED_CAST") val cookies = value as? Set<String> if (cookies != null) { try { val url = HttpUrl.parse("http://$key") ?: continue val nonExpiredCookies = cookies.mapNotNull { Cookie.parse(url, it) } .filter { !it.hasExpired() } cookieMap.put(key, nonExpiredCookies) } catch (e: Exception) { // Ignore } } } } @Synchronized fun addAll(url: HttpUrl, cookies: List<Cookie>) { val key = url.uri().host // Append or replace the cookies for this domain. val cookiesForDomain = cookieMap[key].orEmpty().toMutableList() for (cookie in cookies) { // Find a cookie with the same name. Replace it if found, otherwise add a new one. val pos = cookiesForDomain.indexOfFirst { it.name() == cookie.name() } if (pos == -1) { cookiesForDomain.add(cookie) } else { cookiesForDomain[pos] = cookie } } cookieMap.put(key, cookiesForDomain) // Get cookies to be stored in disk val newValues = cookiesForDomain.asSequence() .filter { it.persistent() && !it.hasExpired() } .map(Cookie::toString) .toSet() prefs.edit().putStringSet(key, newValues).apply() } @Synchronized fun removeAll() { prefs.edit().clear().apply() cookieMap.clear() } fun remove(uri: URI) { prefs.edit().remove(uri.host).apply() cookieMap.remove(uri.host) } fun get(url: HttpUrl) = get(url.uri().host) fun get(uri: URI) = get(uri.host) private fun get(url: String): List<Cookie> { return cookieMap[url].orEmpty().filter { !it.hasExpired() } } private fun Cookie.hasExpired() = System.currentTimeMillis() >= expiresAt() }
apache-2.0
holgerbrandl/kscript-support-api
src/main/kotlin/kscript/text/StreamUtil.kt
1
2895
package kscript.text /** A `Sequence<String>` iterator for standard input */ public val stdin by lazy { generateSequence() { readLine() } } fun linesFrom(file: java.io.File) = java.io.BufferedReader(java.io.FileReader(file)).lineSequence() /** * File argument processor that works similar to awk: If data is available on stdin, use it. If not expect a file argument and read from that one instead. * */ fun resolveArgFile(args: Array<String>, position: Int = 0): Sequence<String> { // if (stdin.iterator().hasNext()) return stdin if (System.`in`.available() > 0) return kscript.text.stdin kscript.stopIfNot(args.isNotEmpty()) { "Missing file or input input stream" } kscript.stopIfNot(args.size >= position) { "arg position ${position} exceeds number of arguments ${args.size} " } val fileArg = args[position] // stdinNames: List<String> = listOf("-", "stdin") // if (stdinNames.contains(fileArg)) return stdin val inputFile = java.io.File(fileArg) kscript.stopIfNot(inputFile.canRead()) { "Can not read from '${fileArg}'" } // test for compression and uncompress files automatically val isCompressedInput = inputFile.name.run { endsWith(".zip") || endsWith(".gz") } val lineReader = if (isCompressedInput) { java.io.InputStreamReader(java.util.zip.GZIPInputStream(java.io.FileInputStream(inputFile))) } else { java.io.FileReader(inputFile) } // todo we don't close the buffer with this approach // BufferedReader(FileReader(inputFile )).use { return it } return java.io.BufferedReader(lineReader).lineSequence() } /** Endpoint for a kscript pipe. */ fun Sequence<String>.print() = forEach { println(it) } /** Endpoint for a kscript pipe. */ fun Iterable<String>.print() = forEach { println(it) } fun Iterable<String>.trim() = map { it.trim() } fun Sequence<String>.trim() = map { it.trim() } //https://dzone.com/articles/readingwriting-compressed-and /** Save a list of items into a file. Output can be option ally zipped and a the stringifying operation can be changed from toString to custom operation if needed. */ fun <T> Iterable<T>.saveAs(f: java.io.File, transform: (T) -> String = { it.toString() }, separator: Char = '\n', overwrite: Boolean = true, compress: Boolean = f.name.let { it.endsWith(".zip") || it.endsWith(".gz") }) { // ensure that file is not yet there or overwrite flag is set require(!f.isFile || overwrite) { "$f is present already. Use overwrite=true to enforce file replacement." } val p = if (!compress) java.io.PrintWriter(f) else java.io.BufferedWriter(java.io.OutputStreamWriter(java.util.zip.GZIPOutputStream(java.io.FileOutputStream(f)))) toList().forEach { p.write(transform(it) + separator) } p.close() }
mit
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/exceptions/DigestAuthException.kt
1
332
package ch.rmy.android.http_shortcuts.exceptions import android.content.Context import ch.rmy.android.http_shortcuts.R class DigestAuthException(private val detail: String) : UserException() { override fun getLocalizedMessage(context: Context): String = context.getString(R.string.error_digest_auth_failed, detail) }
mit
beamishjabberwock/kedux
src/test/kotlin/com/angusmorton/kedux/Actions.kt
2
408
package com.angusmorton.kedux internal val PLUS_ACTION = "com.angusmorton.kedux.getPLUS_ACTION" internal val MINUS_ACTION = "com.angusmorton.kedux.getMINUS_ACTION" internal val RESET_ACTION = "com.angusmorton.kedux.getRESET_ACTION" internal val NO_ACTION = "com.angusmorton.kedux.getNO_ACTION" internal data class TestState(val value: Int) internal data class TestAction(val type: String, val by: Int) { }
apache-2.0
shabtaisharon/ds3_java_browser
dsb-gui/src/test/java/com/spectralogic/dsbrowser/gui/util/FunctionalExtensionsTest.kt
1
2162
/* * *************************************************************************** * Copyright 2014-2017 Spectra Logic Corporation. 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. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file 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.spectralogic.dsbrowser.gui.util import com.spectralogic.dsbrowser.util.andThen import com.spectralogic.dsbrowser.util.exists import org.assertj.core.api.Assertions.* import org.junit.Test class FunctionalExtensionsTest { @Test fun existDoesNotFalseExecute() { val h: String? = null var b = false h.exists { b = true it } assertThat(b).isFalse() } @Test fun existDoesOnExist() { val h: String? = "Hello World" var b = false h.exists { b = true null } assertThat(b).isTrue() } @Test fun existsAssignment() { val h: String? = "Hello World" val b = h.exists { it } assertThat(b).isEqualTo("Hello World") } @Test fun existsInlineAssignment() { val b = "H".exists { it } assertThat(b).isEqualTo("H") } @Test fun existsNull() { val b = null.exists { "Hello World" } assertThat(b).isNull() } @Test fun notExistingAssignment() { val h: String? = null val b = h.exists { it } assertThat(b).isNull() } @Test fun andThenTest() { val a = { b: Int -> b + 2 } var f = false val c = a.andThen { f = true }.invoke(1) assertThat(f).isTrue() assertThat(c).isEqualTo(3) } }
apache-2.0
sksamuel/ktest
kotest-assertions/kotest-assertions-shared/src/commonMain/kotlin/io/kotest/assertions/Exceptions.kt
1
1161
package io.kotest.assertions /** * Use this object to create exceptions on a target platform. * This will create the most appropriate exception type, such as org.opentest4j.AssertionFailedError on * platforms that support it, and defaulting to the basic kotlin AssertionError in the degenerative case. */ expect object Exceptions { /** * Creates an [AssertionError] from the given message. If the platform supports nested exceptions, the cause * is set to the given [cause]. */ fun createAssertionError(message: String, cause: Throwable?): AssertionError /** * Creates the best error type supported on the platform (eg opentest4j.AssertionFailedException) from the * given message and expected and actual values. If the platform supports nested exceptions, the cause * is set to the given [cause]. * * If the platform has opentest4k, jUnit5 or jUnit5 on the classpath, it will use exceptions from those platforms * for compatibility with tools that look for these special exception types. */ fun createAssertionError(message: String, cause: Throwable?, expected: Expected, actual: Actual): Throwable }
mit
MichelPro/CoolWeather
app/src/main/java/com/michel/coolweather/activity/WeatherActivity.kt
1
6618
package com.michel.coolweather.activity import android.graphics.Color import android.os.Build import android.os.Bundle import android.preference.PreferenceManager import android.util.Log import android.view.LayoutInflater import android.view.View import android.widget.ImageView import android.widget.LinearLayout import android.widget.ScrollView import android.widget.TextView import com.bumptech.glide.Glide import com.michel.coolweather.R import com.michel.coolweather.base.BaseActivity import com.michel.coolweather.entity.Weather import com.michel.coolweather.other.Constant import com.michel.coolweather.other.setVisible import com.michel.coolweather.utils.SpUtils import com.michel.coolweather.utils.Utility import com.zhy.http.okhttp.OkHttpUtils import com.zhy.http.okhttp.callback.StringCallback import okhttp3.Call import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.debug import org.jetbrains.anko.find import org.jetbrains.anko.toast import java.lang.Exception class WeatherActivity : BaseActivity(), AnkoLogger { lateinit var bingPicImg: ImageView lateinit var weatherLayout: ScrollView lateinit var titleCity: TextView lateinit var titleUpdateTime: TextView lateinit var degreeText: TextView lateinit var weatherInfoText: TextView lateinit var forecastLayout: LinearLayout lateinit var aqiText: TextView lateinit var pm25Text: TextView lateinit var comfortText: TextView lateinit var carWashText: TextView lateinit var sportText: TextView override fun onCreate(savedInstanceState: Bundle?) { // ้€ๆ˜Ž็Šถๆ€ๆ  if (Build.VERSION.SDK_INT >= 21) { val decorView = window.decorView decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE window.statusBarColor = Color.TRANSPARENT } super.onCreate(savedInstanceState) } override fun initVariables() { } override fun getLayoutResId(): Int = R.layout.activity_weather override fun initViews(savedInstanceState: Bundle?) { bingPicImg = find(R.id.bing_pic_img) weatherLayout = find(R.id.weather_layout) titleCity = find(R.id.title_city) titleUpdateTime = find(R.id.title_update_time) degreeText = find(R.id.degree_text) weatherInfoText = find(R.id.weather_info_text) forecastLayout = find(R.id.forecast_layout) aqiText = find(R.id.api_text) pm25Text = find(R.id.pm25_text) comfortText = find(R.id.comfort_text) carWashText = find(R.id.car_wash_text) sportText = find(R.id.sport_text) } override fun initData() { val bingPic = SpUtils.instance.get("bing_pic", "") as String if (bingPic.isNotEmpty()) { Glide.with(this).load(bingPic).into(bingPicImg) } else { loadBingPic() } val weatherString = SpUtils.instance.get("weather", "") as String if (weatherString.isNotEmpty()) { // ๆœ‰็ผ“ๅญ˜ๆ—ถ็›ดๆŽฅ่งฃๆžๅคฉๆฐ”ๆ•ฐๆฎ val weather = Utility.handleWeatherResponse(weatherString) showWeatherInfo(weather) } else { // ๆ— ็ผ“ๅญ˜ๆ—ถๅŽปๆœๅŠกๅ™จๆŸฅ่ฏขๅคฉๆฐ” val weatherId = intent.getStringExtra("weather_id") Log.d("CoolWeather", "weather_idๆ˜ฏ$weatherId") weatherLayout.setVisible(false) requestWeather(weatherId) } } /** * ๅŠ ่ฝฝๅฟ…ๅบ”ๆฏๆ—ฅไธ€ๅ›พ */ private fun loadBingPic() { OkHttpUtils.get().url(Constant.URL_BING_PIC).build().execute(object : StringCallback(){ override fun onResponse(response: String, id: Int) { SpUtils.instance.put("bing_pic", response) Glide.with(this@WeatherActivity).load(response).into(bingPicImg) } override fun onError(call: Call?, e: Exception, id: Int) { e.printStackTrace() } }) } /** * ๆ นๆฎๅคฉๆฐ”id่ฏทๆฑ‚ๅคฉๆฐ”ไฟกๆฏ */ private fun requestWeather(weatherId: String?) { OkHttpUtils.get().url(Constant.URL_WEATHER).addParams("cityid", weatherId) .addParams("key", Constant.KEY_WEATHER) .build().execute(object : StringCallback(){ override fun onResponse(response: String, id: Int) { Log.d("CoolWeather", "่ฟ”ๅ›ž็ป“ๆžœๆ˜ฏ$response") val weather = Utility.handleWeatherResponse(response) if (weather != null && "ok" == weather.status) { SpUtils.instance.put("weather", response) showWeatherInfo(weather) } else { toast("่Žทๅ–ๅคฉๆฐ”ไฟกๆฏๅคฑ่ดฅ") } } override fun onError(call: Call?, e: Exception, id: Int) { e.printStackTrace() toast("่Žทๅ–ๅคฉๆฐ”ไฟกๆฏๅคฑ่ดฅ") } }) } /** * ๅค„็†ๅนถๅฑ•็คบWeatherๅฎžไฝ“็ฑปไธญ็š„ๆ•ฐๆฎ */ private fun showWeatherInfo(weather: Weather) { val cityName = weather.basic.cityName val updateTime = weather.basic.update.updateTime.split(" ")[1] val degree = weather.now.temperature + "โ„ƒ" val weatherInfo = weather.now.more.info titleCity.text = cityName titleUpdateTime.text = updateTime degreeText.text = degree weatherInfoText.text = weatherInfo forecastLayout.removeAllViews() weather.forecastList.forEach { val view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayout, false) val dateText = view.find<TextView>(R.id.date_text) val infoText = view.find<TextView>(R.id.info_text) val maxText = view.find<TextView>(R.id.max_text) val minText = view.find<TextView>(R.id.min_text) dateText.text = it.date infoText.text = it.more.info maxText.text = it.temperature.max minText.text = it.temperature.min forecastLayout.addView(view) } weather.aqi?.let { aqiText.text = it.city.aqi pm25Text.text = it.city.pm25 } val comfort = "่ˆ’้€‚ๅบฆ๏ผš${weather.suggestion.comfort.info}" val carWash = "ๆด—่ฝฆๆŒ‡ๆ•ฐ๏ผš${weather.suggestion.carWash.info}" val sport = "่ฟๅŠจๅปบ่ฎฎ๏ผš${weather.suggestion.sport.info}" comfortText.text = comfort carWashText.text = carWash sportText.text = sport weatherLayout.setVisible(true) } }
apache-2.0
NicholasFeldman/NudeKt
src/main/kotlin/tech/feldman/nudekt/colorUtils.kt
1
1039
package tech.feldman.nudekt internal fun maxRgb(r: Float, g: Float, b: Float): Float { return Math.max(Math.max(r, g), b) } internal fun minRgb(r: Float, g: Float, b: Float): Float { return Math.min(Math.min(r, g), b) } internal data class NormalizedRGB(val r: Float, val g: Float, val b: Float) internal fun toNormalizedRgb(r: Float, g: Float, b: Float): NormalizedRGB { val sum = r + g + b val nr = r / sum val ng = g / sum val nb = b / sum return NormalizedRGB(nr, ng, nb) } internal data class Hsv(val h: Float, val s: Float, val v: Float) internal fun toHsv(r: Float, g: Float, b: Float): Hsv { val sum = r + g + b val max = maxRgb(r, g, b) val min = minRgb(r, g, b) val diff = max - min var h = when (max) { r -> (g - b) / diff g -> 2 + (g - r) / diff else -> 4 + (r - g) / diff }.toFloat() h *= 60 if (h < 0) { h += 360 } val s = 1 - 3.toFloat() * (min / sum) val v = (1 / 3.toFloat()) * max return Hsv(h, s, v) }
mit
migafgarcia/programming-challenges
advent_of_code/2018/solutions/day_5_a.kt
1
491
import java.io.File fun main(args: Array<String>) { var input = File(args[0]).readText().trim() var i = 0 while(i < input.length - 1) { if(((input[i].isLowerCase() && input[i+1].isUpperCase()) || (input[i].isUpperCase() && input[i+1].isLowerCase())) && input[i].equals(input[i+1], true)) { input = input.removeRange(i..i+1) i = maxOf(i - 1, 0) } else i++ } println(input.length) }
mit
rive-app/rive-flutter
example/android/app/src/main/kotlin/com/example/rive_example/MainActivity.kt
1
129
package com.example.rive_example import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
mit
kvnxiao/meirei
meirei-jda/src/main/kotlin/com/github/kvnxiao/discord/meirei/jda/command/CommandBuilder.kt
1
10719
/* * Copyright (C) 2017-2018 Ze Hao Xiao * * 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.kvnxiao.discord.meirei.jda.command import com.github.kvnxiao.discord.meirei.command.CommandContext import com.github.kvnxiao.discord.meirei.command.CommandDefaults import com.github.kvnxiao.discord.meirei.command.CommandPackage import com.github.kvnxiao.discord.meirei.command.CommandProperties import com.github.kvnxiao.discord.meirei.jda.permission.LevelDefaults import com.github.kvnxiao.discord.meirei.jda.permission.PermissionPropertiesJDA import com.github.kvnxiao.discord.meirei.permission.PermissionData import com.github.kvnxiao.discord.meirei.permission.PermissionDefaults import net.dv8tion.jda.core.Permission import net.dv8tion.jda.core.events.message.MessageReceivedEvent import java.util.Arrays import java.util.HashSet /** * Builder class to help create a (JDA) command package for adding to the command registry */ class CommandBuilder /** * Creates a command builder instance with the specified unique command id. * @param id the unique identifier (name) for the command */ (private val id: String) { // Command properties private val aliases = HashSet<String>() private var prefix = CommandDefaults.PREFIX private var parentId = CommandDefaults.PARENT_ID // Settings private var execWithSubCommands = CommandDefaults.EXEC_ALONGSIDE_SUBCOMMANDS private var isDisabled = CommandDefaults.IS_DISABLED // Metadata private var description = CommandDefaults.NO_DESCRIPTION private var usage = CommandDefaults.NO_USAGE // Permission properties private var allowDm = PermissionDefaults.ALLOW_DIRECT_MSGING private var forceDm = PermissionDefaults.FORCE_DIRECT_MSGING private var forceDmReply = PermissionDefaults.FORCE_DIRECT_REPLY private var removeCallMsg = PermissionDefaults.REMOVE_CALL_MSG private var rateLimitPeriodMs = PermissionDefaults.RATE_LIMIT_PERIOD_MS private var tokensPerPeriod = PermissionDefaults.TOKENS_PER_PERIOD private var rateLimitOnGuild = PermissionDefaults.RATE_LIMIT_ON_GUILD private var reqBotOwner = PermissionDefaults.REQUIRE_BOT_OWNER private var reqGuildOwner = PermissionDefaults.REQUIRE_GUILD_OWNER private var reqMention = PermissionDefaults.REQUIRE_MENTION // Command registry settings private var isRegistryAware = CommandDefaults.IS_REGISTRY_AWARE // Discord permissions private var permissionLevel = LevelDefaults.DEFAULT_PERMS_RW /** * Sets the alias(es) for the command. * @param aliases the command alias(es) * @return the current command builder */ fun aliases(vararg aliases: String): CommandBuilder { this.aliases.addAll(Arrays.asList(*aliases)) return this } /** * Sets the prefix for the command. * @param prefix the command prefix * @return the current command builder */ fun prefix(prefix: String): CommandBuilder { this.prefix = prefix return this } /** * Sets the parentId for this command. * @param parentId the parent command's id * @return the current command builder */ fun parentId(parentId: String): CommandBuilder { this.parentId = parentId return this } /** * Sets whether the command should execute along with its sub-commands. * @param execWithSubCommands a boolean * @return the current command builder */ fun execWithSubCommands(execWithSubCommands: Boolean): CommandBuilder { this.execWithSubCommands = execWithSubCommands return this } /** * Sets whether the command is disabled or not. * @param isDisabled a boolean * @return the current command builder */ fun isDisabled(isDisabled: Boolean): CommandBuilder { this.isDisabled = isDisabled return this } /** * Sets the description for the command. * @param description the description string * @return the current command builder */ fun description(description: String): CommandBuilder { this.description = description return this } /** * Sets the usage details for the command. * @param usage the usage string * @return the current command builder */ fun usage(usage: String): CommandBuilder { this.usage = usage return this } /** * Sets whether the command is allowed to be executed through direct messages to the bot (otherwise it is guild only). * @param allowDm a boolean * @return the current command builder */ fun allowDirectMessages(allowDm: Boolean): CommandBuilder { this.allowDm = allowDm return this } /** * Sets whether the command can only be executed through direct messages to the bot from the user. * @param forceDm a boolean * @return the current command builder */ fun forceDirectMessages(forceDm: Boolean): CommandBuilder { this.forceDm = forceDm return this } /** * Sets whether the bot is forced to reply with a direct message to the user during command execution. * @param forceDmReply a boolean * @return the current command builder */ fun forceDirectMessageReply(forceDmReply: Boolean): CommandBuilder { this.forceDmReply = forceDmReply return this } /** * Sets whether or not the user's message that executed the command should be deleted upon execution. * @param removeCallMsg a boolean * @return the current command builder */ fun removeCallMessage(removeCallMsg: Boolean): CommandBuilder { this.removeCallMsg = removeCallMsg return this } /** * Sets the rate limit period in milliseconds for the command call, before the rate limits are reset on a per-period basis. * @param rateLimitPeriodMs the period in milliseconds * @return the current command builder */ fun rateLimitPeriodMs(rateLimitPeriodMs: Long): CommandBuilder { this.rateLimitPeriodMs = rateLimitPeriodMs return this } /** * Sets the number of tokens (number of calls to the command) allowed per rate limit period. * @param tokensPerPeriod the number of tokens per period * @return the current command builder */ fun tokensPerPeriod(tokensPerPeriod: Long): CommandBuilder { this.tokensPerPeriod = tokensPerPeriod return this } /** * Sets whether the rate limiting for the command should be done on a per-guild basis, or a per-user basis. * @param rateLimitOnGuild a boolean * @return the current command builder */ fun rateLimitOnGuild(rateLimitOnGuild: Boolean): CommandBuilder { this.rateLimitOnGuild = rateLimitOnGuild return this } /** * Sets whether the command requires bot owner privileges in order to be successfully executed. * @param reqBotOwner a boolean * @return the current command builder */ fun requireBotOwner(reqBotOwner: Boolean): CommandBuilder { this.reqBotOwner = reqBotOwner return this } /** * Sets whether the command requires guild owner privileges in order to be successfully executed. * @param reqGuildOwner a boolean * @return the current command builder */ fun requireGuildOwner(reqGuildOwner: Boolean): CommandBuilder { this.reqGuildOwner = reqGuildOwner return this } /** * Sets whether the command requires an '@' mention before the command prefix and alias in order to be executed. * @param reqMention a boolean * @return the current command builder */ fun requireMention(reqMention: Boolean): CommandBuilder { this.reqMention = reqMention return this } /** * Sets the command's discord permissions that are required for a user to execute the command * @param permissions the required discord permissions * @return the current command builder */ fun permissionLevel(vararg permissions: Permission): CommandBuilder { this.permissionLevel.clear() this.permissionLevel.addAll(permissions) return this } /** * Sets whether the command is capable of reading the command registry to retrieve information regarding other commands. * @param isRegistryAware whether the command is registry aware * @return the current command builder */ fun isRegistryAware(isRegistryAware: Boolean): CommandBuilder { this.isRegistryAware = isRegistryAware return this } /** * Builds the JDA command package using the values set in the builder. * @param executable the command method * @return the (JDA) command package containing the executable, command properties, and permission properties */ fun build(executable: CommandExecutable): CommandPackage { if (this.aliases.isEmpty()) { this.aliases.add(this.id) } return CommandPackage( object : CommandJDA(this.id, this.isRegistryAware) { override fun execute(context: CommandContext, event: MessageReceivedEvent) { executable.execute(context, event) } }, CommandProperties(this.id, this.aliases, this.prefix, this.description, this.usage, this.execWithSubCommands, this.isDisabled, this.parentId), PermissionPropertiesJDA(PermissionData(this.allowDm, this.forceDm, this.forceDmReply, this.removeCallMsg, this.rateLimitPeriodMs, this.tokensPerPeriod, this.rateLimitOnGuild, this.reqGuildOwner, this.reqBotOwner, this.reqMention), this.permissionLevel) ) } } /** * Kotlin-based lambda helper for building CommandPackages */ fun CommandBuilder.build(execute: (context: CommandContext, event: MessageReceivedEvent) -> Unit): CommandPackage { return this.build(object : CommandExecutable { override fun execute(context: CommandContext, event: MessageReceivedEvent) { execute.invoke(context, event) } }) }
apache-2.0
JetBrains/teamcity-azure-plugin
plugin-azure-server/src/main/kotlin/jetbrains/buildServer/clouds/azure/arm/connector/tasks/RestartVirtualMachineTaskImpl.kt
1
2158
/* * Copyright 2000-2021 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.buildServer.clouds.azure.arm.connector.tasks import com.intellij.openapi.diagnostic.Logger import com.microsoft.azure.management.Azure import jetbrains.buildServer.clouds.azure.arm.throttler.AzureTaskNotifications import jetbrains.buildServer.clouds.azure.arm.throttler.AzureThrottlerTaskBaseImpl import rx.Observable import rx.Single data class RestartVirtualMachineTaskParameter( val groupId: String, val name: String) class RestartVirtualMachineTaskImpl(private val myNotifications: AzureTaskNotifications) : AzureThrottlerTaskBaseImpl<Azure, RestartVirtualMachineTaskParameter, Unit>() { override fun create(api: Azure, parameter: RestartVirtualMachineTaskParameter): Single<Unit> { return api .virtualMachines() .getByResourceGroupAsync(parameter.groupId, parameter.name) .flatMap { vm -> if (vm != null) { vm.restartAsync().toObservable<Unit>().doOnCompleted { myNotifications.raise(AzureTaskVirtualMachineStatusChangedEventArgs(api, vm)) } } else { LOG.warnAndDebugDetails("Could not find virtual machine to restart. GroupId: ${parameter.groupId}, Name: ${parameter.name}", null) Observable.just(Unit) } } .defaultIfEmpty(Unit) .toSingle() } companion object { private val LOG = Logger.getInstance(RestartVirtualMachineTaskImpl::class.java.name) } }
apache-2.0
hazuki0x0/YuzuBrowser
module/adblock/src/main/java/jp/hazuki/yuzubrowser/adblock/filter/unified/io/ElementReader.kt
1
3369
/* * Copyright (C) 2017-2019 Hazuki * * 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 jp.hazuki.yuzubrowser.adblock.filter.unified.io import jp.hazuki.yuzubrowser.adblock.filter.toInt import jp.hazuki.yuzubrowser.adblock.filter.unified.ELEMENT_FILTER_CACHE_HEADER import jp.hazuki.yuzubrowser.adblock.filter.unified.element.ElementFilter import jp.hazuki.yuzubrowser.adblock.filter.unified.element.PlaneElementFilter import jp.hazuki.yuzubrowser.adblock.filter.unified.element.TldRemovedElementFilter import jp.hazuki.yuzubrowser.adblock.filter.unified.readVariableInt import java.io.InputStream class ElementReader(private val input: InputStream) { fun checkHeader(): Boolean { val header = ELEMENT_FILTER_CACHE_HEADER.toByteArray() val data = ByteArray(header.size) input.read(data) return header contentEquals data } fun readAll() = sequence { val intBuf = ByteArray(4) val shortBuf = ByteArray(2) input.read(intBuf) val size = intBuf.toInt() val list = ArrayList<ElementFilter>(size) var patternBuffer = ByteArray(32) loop@ for (loop in 0 until size) { val filterType = input.read() if (filterType < 0) break val isHide = when (input.read()) { 0 -> false 1 -> true else -> break@loop } val isNot = when (input.read()) { 0 -> false 1 -> true else -> break@loop } val patternSize = input.readVariableInt(shortBuf, intBuf) if (patternSize == -1) break if (patternBuffer.size < patternSize) { patternBuffer = ByteArray(patternSize) } if (input.read(patternBuffer, 0, patternSize) != patternSize) break val pattern = String(patternBuffer, 0, patternSize) val selectorSize = input.readVariableInt(shortBuf, intBuf) if (selectorSize == -1) break if (patternBuffer.size < selectorSize) { patternBuffer = ByteArray(selectorSize) } if (input.read(patternBuffer, 0, selectorSize) != selectorSize) break val selector = String(patternBuffer, 0, selectorSize) val filter = when (filterType) { ElementFilter.TYPE_PLANE -> PlaneElementFilter( pattern, isHide, isNot, selector, ) ElementFilter.TYPE_TLD_REMOVED -> TldRemovedElementFilter( pattern, isHide, isNot, selector, ) else -> break@loop } yield(filter) } } }
apache-2.0
kpspemu/kpspemu
src/commonMain/kotlin/com/soywiz/kpspemu/hle/manager/FileManager.kt
1
4805
package com.soywiz.kpspemu.hle.manager import com.soywiz.korio.async.* import com.soywiz.korio.file.* import com.soywiz.korio.file.VfsUtil import com.soywiz.korio.lang.* import com.soywiz.korio.stream.* import com.soywiz.kpspemu.* import com.soywiz.kpspemu.util.* import kotlinx.coroutines.* class FileManager(val emulator: Emulator) { companion object { val INIT_CURRENT_DIRECTORY = "umd0:" val INIT_EXECUTABLE_FILE = "umd0:/PSP_GAME/USRDIR/EBOOT.BIN" } val deviceManager get() = emulator.deviceManager var currentDirectory = INIT_CURRENT_DIRECTORY var executableFile = INIT_EXECUTABLE_FILE val fileDescriptors = ResourceList<FileDescriptor>("FileDescriptor") { FileDescriptor(it) } val directoryDescriptors = ResourceList<DirectoryDescriptor>("DirectoryDescriptor") { DirectoryDescriptor(it) } fun reset() { currentDirectory = INIT_CURRENT_DIRECTORY executableFile = INIT_EXECUTABLE_FILE fileDescriptors.reset() directoryDescriptors.reset() } fun resolvePath(path: String): String { if (path.contains(':')) { return path } else { if (path.startsWith('/')) { return currentDirectory.split(':').first() + ":" + path } else { return VfsUtil.combine(currentDirectory, path) } } } fun resolve(path: String): VfsFile { val resolvedPath = resolvePath(path) //println("resolvedPath --> $resolvedPath") return deviceManager.root[resolvedPath] } } class FileDescriptor(override val id: Int) : ResourceItem { lateinit var fileName: String lateinit var file: VfsFile lateinit var stream: AsyncStream var doLater: (suspend () -> Unit)? = null var asyncPromise: Deferred<Unit>? = null var asyncResult: Long = 0L var asyncDone: Boolean = false } class DirectoryDescriptor(override val id: Int) : ResourceItem { lateinit var directory: VfsFile var pos: Int = 0 var files: List<VfsFile> = listOf() val remaining: Int get() = files.size - pos } data class SceIoStat( var mode: Int = 0, // SceMode var attributes: Int = 0, // IOFileModes.File var size: Long = 0L, var timeCreation: ScePspDateTime = ScePspDateTime(0L), var timeLastAccess: ScePspDateTime = ScePspDateTime(0L), var timeLastModification: ScePspDateTime = ScePspDateTime(0L), var device: IntArray = IntArray(6) ) { companion object : Struct<SceIoStat>( { SceIoStat() }, SceIoStat::mode AS INT32, SceIoStat::attributes AS INT32, SceIoStat::size AS INT64, SceIoStat::timeCreation AS ScePspDateTime, SceIoStat::timeLastAccess AS ScePspDateTime, SceIoStat::timeLastModification AS ScePspDateTime, SceIoStat::device AS INTLIKEARRAY(INT32, 6) ) } //class SceIoStat( // val mode: Int, // val attributes: Int, // val size: Long, // val timeCreation: ScePspDateTime, // val timeLastAccess: ScePspDateTime, // val timeLastModifications: ScePspDateTime, // val device: IntArray = IntArray(6) //) { // fun write(s: SyncStream) = s.run { // write32_le(mode) // write32_le(attributes) // write64_le(size) // timeCreation.write(s) // timeLastAccess.write(s) // timeLastModifications.write(s) // for (n in 0 until 6) write32_le(device[n]) // } //} data class HleIoDirent( var stat: SceIoStat = SceIoStat(), var name: String = "", var privateData: Int = 0, var dummy: Int = 0 ) { companion object : Struct<HleIoDirent>( { HleIoDirent() }, HleIoDirent::stat AS SceIoStat, HleIoDirent::name AS STRINGZ(UTF8, 256), HleIoDirent::privateData AS INT32, HleIoDirent::dummy AS INT32 ) } object IOFileModes { val DIR = 0x1000 val FILE = 0x2000 val FormatMask = 0x0038 val SymbolicLink = 0x0008 val Directory = 0x0010 val File = 0x0020 val CanRead = 0x0004 val CanWrite = 0x0002 val CanExecute = 0x0001 } object SeekType { val Set = 0 val Cur = 1 val End = 2 val Tell = 65536 } object FileOpenFlags { val Read = 0x0001 val Write = 0x0002 val ReadWrite = Read or Write val NoBlock = 0x0004 val _InternalDirOpen = 0x0008 // Internal use for dopen val Append = 0x0100 val Create = 0x0200 val Truncate = 0x0400 val Excl = 0x0800 val Unknown1 = 0x4000 // something async? val NoWait = 0x8000 val Unknown2 = 0xf0000 // seen on Wipeout Pure and Infected val Unknown3 = 0x2000000 // seen on Puzzle Guzzle, Hammerin' Hero } //object IOFileModes { // val FormatMask = 0x0038 // val SymbolicLink = 0x0008 // val Directory = 0x0010 // val File = 0x0020 // val CanRead = 0x0004 // val CanWrite = 0x0002 // val CanExecute = 0x0001 //}
mit
osfans/trime
app/src/main/java/com/osfans/trime/data/db/CollectionHelper.kt
1
1106
package com.osfans.trime.data.db import android.content.Context import androidx.room.Room import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob object CollectionHelper : CoroutineScope by CoroutineScope(SupervisorJob() + Dispatchers.Default) { private lateinit var cltDb: Database private lateinit var cltDao: DatabaseDao fun init(context: Context) { cltDb = Room .databaseBuilder(context, Database::class.java, "collection.db") .addMigrations(Database.MIGRATION_3_4) .build() cltDao = cltDb.databaseDao() } suspend fun insert(bean: DatabaseBean) = cltDao.insert(bean) suspend fun getAll() = cltDao.getAll() suspend fun pin(id: Int) = cltDao.updatePinned(id, true) suspend fun unpin(id: Int) = cltDao.updatePinned(id, false) suspend fun delete(id: Int) = cltDao.delete(id) suspend fun deleteAll(skipPinned: Boolean = true) { if (skipPinned) cltDao.deleteAllUnpinned() else cltDao.deleteAll() } }
gpl-3.0
RocketChat/Rocket.Chat.Android
app/src/main/java/chat/rocket/android/profile/ui/ProfileFragment.kt
2
14005
package chat.rocket.android.profile.ui import DrawableHelper import android.app.Activity import android.content.Intent import android.content.pm.PackageManager import android.graphics.Bitmap import android.os.Build import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.RadioGroup import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.view.ActionMode import androidx.core.net.toUri import androidx.core.view.isVisible import androidx.fragment.app.Fragment import chat.rocket.android.R import chat.rocket.android.analytics.AnalyticsManager import chat.rocket.android.analytics.event.ScreenViewEvent import chat.rocket.android.helper.AndroidPermissionsHelper import chat.rocket.android.helper.AndroidPermissionsHelper.getCameraPermission import chat.rocket.android.helper.AndroidPermissionsHelper.hasCameraPermission import chat.rocket.android.main.ui.MainActivity import chat.rocket.android.profile.presentation.ProfilePresenter import chat.rocket.android.profile.presentation.ProfileView import chat.rocket.android.util.extension.asObservable import chat.rocket.android.util.extension.dispatchImageSelection import chat.rocket.android.util.extension.dispatchTakePicture import chat.rocket.android.util.extensions.inflate import chat.rocket.android.util.extensions.showToast import chat.rocket.android.util.extensions.textContent import chat.rocket.android.util.extensions.ui import chat.rocket.common.model.UserStatus import chat.rocket.common.model.userStatusOf import com.facebook.drawee.backends.pipeline.Fresco import com.google.android.material.snackbar.Snackbar import dagger.android.support.AndroidSupportInjection import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.Observables import kotlinx.android.synthetic.main.app_bar.* import kotlinx.android.synthetic.main.avatar_profile.* import kotlinx.android.synthetic.main.fragment_profile.* import kotlinx.android.synthetic.main.update_avatar_options.* import javax.inject.Inject internal const val TAG_PROFILE_FRAGMENT = "ProfileFragment" private const val REQUEST_CODE_FOR_PERFORM_SAF = 1 private const val REQUEST_CODE_FOR_PERFORM_CAMERA = 2 fun newInstance() = ProfileFragment() class ProfileFragment : Fragment(), ProfileView, ActionMode.Callback { @Inject lateinit var presenter: ProfilePresenter @Inject lateinit var analyticsManager: AnalyticsManager private var currentStatus = "" private var currentName = "" private var currentUsername = "" private var currentEmail = "" private var actionMode: ActionMode? = null private val editTextsDisposable = CompositeDisposable() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) AndroidSupportInjection.inject(this) setHasOptionsMenu(true) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = container?.inflate(R.layout.fragment_profile) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupToolbar() if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) { tintEditTextDrawableStart() } presenter.loadUserProfile() setupListeners() subscribeEditTexts() analyticsManager.logScreenView(ScreenViewEvent.Profile) } override fun onDestroyView() { super.onDestroyView() unsubscribeEditTexts() } override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) { resultData?.run { if (resultCode == Activity.RESULT_OK) { if (requestCode == REQUEST_CODE_FOR_PERFORM_SAF) { data?.let { presenter.updateAvatar(it) } } else if (requestCode == REQUEST_CODE_FOR_PERFORM_CAMERA) { extras?.get("data")?.let { presenter.preparePhotoAndUpdateAvatar(it as Bitmap) } } } } } override fun onPrepareOptionsMenu(menu: Menu) { if (actionMode != null) { menu.clear() } super.onPrepareOptionsMenu(menu) } override fun showProfile( status: String, avatarUrl: String, name: String, username: String, email: String? ) { ui { text_status.text = getString(R.string.status, status.capitalize()) image_avatar.setImageURI(avatarUrl) text_name.textContent = name text_username.textContent = username text_email.textContent = email ?: "" currentStatus = status currentName = name currentUsername = username currentEmail = email ?: "" profile_container.isVisible = true } } override fun reloadUserAvatar(avatarUrl: String) { Fresco.getImagePipeline().evictFromCache(avatarUrl.toUri()) image_avatar?.setImageURI(avatarUrl) } override fun onProfileUpdatedSuccessfully( updatedEmail: String, updatedName: String, updatedUserName: String ) { currentEmail = updatedEmail currentName = updatedName currentUsername = updatedUserName showMessage(getString(R.string.msg_profile_updated_successfully)) } override fun showLoading() { enableUserInput(false) ui { view_loading.isVisible = true } } override fun hideLoading() { ui { if (view_loading != null) { view_loading.isVisible = false } } enableUserInput(true) } override fun showMessage(resId: Int) { ui { showToast(resId) } } override fun showMessage(message: String) { ui { showToast(message) } } override fun showGenericErrorMessage() = showMessage(getString(R.string.msg_generic_error)) override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { mode.menuInflater.inflate(R.menu.action_mode_profile, menu) mode.title = getString(R.string.title_update_profile) return true } override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean = false override fun onActionItemClicked(mode: ActionMode, menuItem: MenuItem): Boolean { return when (menuItem.itemId) { R.id.action_update_profile -> { updateProfile() mode.finish() true } else -> false } } override fun onDestroyActionMode(mode: ActionMode) { actionMode = null if (text_email.textContent != currentEmail || text_username.textContent != currentUsername || text_name.textContent != currentName ) { showChangesNotSavedDialog() } } private fun setupToolbar() { with((activity as AppCompatActivity)) { with(toolbar) { setSupportActionBar(this) title = getString(R.string.title_profile) setNavigationIcon(R.drawable.ic_arrow_back_white_24dp) setNavigationOnClickListener { activity?.onBackPressed() } } } } private fun setupListeners() { text_status.setOnClickListener { showStatusDialog(currentStatus) } image_avatar.setOnClickListener { showUpdateAvatarOptions() } view_dim.setOnClickListener { hideUpdateAvatarOptions() } button_open_gallery.setOnClickListener { dispatchImageSelection(REQUEST_CODE_FOR_PERFORM_SAF) hideUpdateAvatarOptions() } button_take_a_photo.setOnClickListener { context?.let { if (hasCameraPermission(it)) { dispatchTakePicture(REQUEST_CODE_FOR_PERFORM_CAMERA) } else { getCameraPermission(this) } } hideUpdateAvatarOptions() } button_reset_avatar.setOnClickListener { hideUpdateAvatarOptions() presenter.resetAvatar() } button_view_profile_photo.setOnClickListener { hideUpdateAvatarOptions() presenter.toProfileImage() } } private fun showUpdateAvatarOptions() { view_dim.isVisible = true layout_update_avatar_options.isVisible = true } private fun hideUpdateAvatarOptions() { layout_update_avatar_options.isVisible = false view_dim.isVisible = false } private fun tintEditTextDrawableStart() { (activity as MainActivity).apply { val personDrawable = DrawableHelper.getDrawableFromId(R.drawable.ic_person_black_20dp, this) val atDrawable = DrawableHelper.getDrawableFromId(R.drawable.ic_at_black_20dp, this) val emailDrawable = DrawableHelper.getDrawableFromId(R.drawable.ic_email_black_20dp, this) val drawables = arrayOf(personDrawable, atDrawable, emailDrawable) DrawableHelper.wrapDrawables(drawables) DrawableHelper.tintDrawables(drawables, this, R.color.colorDrawableTintGrey) DrawableHelper.compoundDrawables( arrayOf(text_name, text_username, text_email), drawables ) } } private fun subscribeEditTexts() { editTextsDisposable.add(Observables.combineLatest( text_name.asObservable(), text_username.asObservable(), text_email.asObservable() ) { text_name, text_username, text_email -> return@combineLatest (text_name.toString() != currentName || text_username.toString() != currentUsername || text_email.toString() != currentEmail) }.subscribe { isValid -> activity?.invalidateOptionsMenu() if (isValid) { startActionMode() } else { finishActionMode() } }) } private fun unsubscribeEditTexts() = editTextsDisposable.clear() private fun startActionMode() { if (actionMode == null) { actionMode = (activity as MainActivity).startSupportActionMode(this) } } private fun finishActionMode() = actionMode?.finish() private fun enableUserInput(value: Boolean) { ui { text_username.isEnabled = value text_username.isEnabled = value text_email.isEnabled = value } } private fun showStatusDialog(currentStatus: String) { val dialogLayout = layoutInflater.inflate(R.layout.dialog_status, null) val radioGroup = dialogLayout.findViewById<RadioGroup>(R.id.radio_group_status) radioGroup.check( when (userStatusOf(currentStatus)) { is UserStatus.Online -> R.id.radio_button_online is UserStatus.Away -> R.id.radio_button_away is UserStatus.Busy -> R.id.radio_button_busy else -> R.id.radio_button_invisible } ) var newStatus: UserStatus = userStatusOf(currentStatus) radioGroup.setOnCheckedChangeListener { _, checkId -> when (checkId) { R.id.radio_button_online -> newStatus = UserStatus.Online() R.id.radio_button_away -> newStatus = UserStatus.Away() R.id.radio_button_busy -> newStatus = UserStatus.Busy() else -> newStatus = UserStatus.Offline() } } context?.let { AlertDialog.Builder(it) .setView(dialogLayout) .setPositiveButton(R.string.msg_change_status) { dialog, _ -> presenter.updateStatus(newStatus) text_status.text = getString(R.string.status, newStatus.toString().capitalize()) this.currentStatus = newStatus.toString() dialog.dismiss() }.show() } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) when (requestCode) { AndroidPermissionsHelper.CAMERA_CODE -> { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted dispatchTakePicture(REQUEST_CODE_FOR_PERFORM_CAMERA) } else { // permission denied Snackbar.make( relative_layout, R.string.msg_camera_permission_denied, Snackbar.LENGTH_SHORT ).show() } return } } } private fun showChangesNotSavedDialog() { context?.let { val builder = AlertDialog.Builder(it) builder.setMessage(R.string.msg_changes_not_saved) .setPositiveButton(R.string.msg_save) { _, _ -> updateProfile() } .setNegativeButton(android.R.string.cancel) { _, _ -> text_email.setText(currentEmail) text_username.setText(currentUsername) text_name.setText(currentName) } .create() .show() } } private fun updateProfile() { presenter.updateUserProfile( text_email.textContent, text_name.textContent, text_username.textContent ) } }
mit
zitmen/thunderstorm-algorithms
src/main/kotlin/cz/cuni/lf1/thunderstorm/parser/FormulaParser.kt
1
7531
package cz.cuni.lf1.thunderstorm.parser import cz.cuni.lf1.thunderstorm.parser.syntaxtree.* internal class FormulaParser(formula: String) { private val lexer = FormulaLexer(formula) private var token: FormulaToken? = null private fun peek(): FormulaToken { if(token == null) token = lexer.nextToken() return token!! } @Throws(FormulaParserException::class) private fun match(type: FormulaToken): String { if(peek() == type) { val tok = token!!.token token = null return tok!! } error("Syntax error near `${token!!.token}`. Expected `$type` instead!") } @Throws(FormulaParserException::class) public fun parse(): Node { return expr() } /* ---------------------------------------------- * --- Implementation of LL1 recursive parser --- * ---------------------------------------------- */ @Throws(FormulaParserException::class) private fun error(message: String?): Nothing { if((message == null) || message.trim().isEmpty()) { throw FormulaParserException("Syntax error!") } throw FormulaParserException(message) } @Throws(FormulaParserException::class) private fun expr(): Node { return logOrExpr() } @Throws(FormulaParserException::class) private fun logOrExpr(): Node { // l|r return logOrExprTail(logAndExpr()) } @Throws(FormulaParserException::class) private fun logOrExprTail(l: Node): Node { // l|r when (peek()) { FormulaToken.OP_OR -> { match(FormulaToken.OP_OR) return logOrExprTail(BinaryOperator(Operator.OR, l, logAndExpr())) } else -> { return l } } } @Throws(FormulaParserException::class) private fun logAndExpr(): Node { // l&r return logAndExprTail(relExpr()) } @Throws(FormulaParserException::class) private fun logAndExprTail(l: Node): Node { // l&r when (peek()) { FormulaToken.OP_AND -> { match(FormulaToken.OP_AND) return logAndExprTail(BinaryOperator(Operator.AND, l, relExpr())) } else -> { return l } } } @Throws(FormulaParserException::class) private fun relExpr(): Node { // l=r, l!=r, l<r, l>r return relExprTail(addSubExpr()) } @Throws(FormulaParserException::class) private fun relExprTail(l: Node): Node { // l=r, l<r, l>r when (peek()) { FormulaToken.OP_NOT -> { match(FormulaToken.OP_NOT) match(FormulaToken.OP_EQ) return relExprTail(BinaryOperator(Operator.NEQ, l, addSubExpr())) } FormulaToken.OP_EQ -> { match(FormulaToken.OP_EQ) return relExprTail(BinaryOperator(Operator.EQ, l, addSubExpr())) } FormulaToken.OP_GT -> { match(FormulaToken.OP_GT) return relExprTail(BinaryOperator(Operator.GT, l, addSubExpr())) } FormulaToken.OP_LT -> { match(FormulaToken.OP_LT) return relExprTail(BinaryOperator(Operator.LT, l, addSubExpr())) } else -> { return l } } } @Throws(FormulaParserException::class) private fun addSubExpr(): Node { // l+r, l-r return addSubExprTail(mulDivExpr()) } @Throws(FormulaParserException::class) private fun addSubExprTail(l: Node): Node { // l+r, l-r when (peek()) { FormulaToken.OP_ADD -> { match(FormulaToken.OP_ADD) return addSubExprTail(BinaryOperator(Operator.ADD, l, mulDivExpr())) } FormulaToken.OP_SUB -> { match(FormulaToken.OP_SUB) return addSubExprTail(BinaryOperator(Operator.SUB, l, mulDivExpr())) } else -> { return l } } } @Throws(FormulaParserException::class) private fun mulDivExpr(): Node { // l*r, l/r, l%r return mulDivExprTail(powExpr()) } @Throws(FormulaParserException::class) private fun mulDivExprTail(l: Node): Node { // l*r, l/r, l%r when (peek()) { FormulaToken.OP_MUL -> { match(FormulaToken.OP_MUL) return mulDivExprTail(BinaryOperator(Operator.MUL, l, powExpr())) } FormulaToken.OP_DIV -> { match(FormulaToken.OP_DIV) return mulDivExprTail(BinaryOperator(Operator.DIV, l, powExpr())) } FormulaToken.OP_MOD -> { match(FormulaToken.OP_MOD) return mulDivExprTail(BinaryOperator(Operator.MOD, l, powExpr())) } else -> { return l } } } @Throws(FormulaParserException::class) private fun powExpr(): Node { // x^n return powExprTail(unaryExpr()) } @Throws(FormulaParserException::class) private fun powExprTail(l: Node): Node { // x^n when (peek()) { FormulaToken.OP_POW -> { match(FormulaToken.OP_POW) return powExprTail(BinaryOperator(Operator.POW, l, unaryExpr())) } else -> { return l } } } @Throws(FormulaParserException::class) private fun unaryExpr(): Node { // -x or +x when (peek()) { FormulaToken.OP_ADD -> { match(FormulaToken.OP_ADD) return BinaryOperator(Operator.ADD, Constant(0.0), atom()) } FormulaToken.OP_SUB -> { match(FormulaToken.OP_SUB) return BinaryOperator(Operator.SUB, Constant(0.0), atom()) } else -> { return atom() } } } @Throws(FormulaParserException::class) private fun atom(): Node { when (peek()) { FormulaToken.LPAR -> { match(FormulaToken.LPAR) val e = expr() match(FormulaToken.RPAR) return e } FormulaToken.FLOAT -> { return floatVal() } FormulaToken.NAME -> { return name() } else -> { error("Syntax error near `${token!!.token}`. Expected `(expression)` or a number or a variable instead!") } } } @Throws(FormulaParserException::class) private fun name(): Node { val tok = match(FormulaToken.NAME) when (peek()) { FormulaToken.DOT -> { match(FormulaToken.DOT) return Variable(namespace = tok, varName = match(FormulaToken.NAME)) } FormulaToken.LPAR -> { match(FormulaToken.LPAR) val arg = expr() match(FormulaToken.RPAR) return Function(tok, arg) // function call } else -> { return Variable(varName = tok) // just a variable (no object) } } } @Throws(FormulaParserException::class) private fun floatVal(): Node { return Constant(match(FormulaToken.FLOAT).toDouble()) } }
gpl-3.0
grote/Liberario
app/src/main/java/de/grobox/transportr/trips/detail/LegAdapter.kt
1
2018
/* * Transportr * * Copyright (c) 2013 - 2018 Torsten Grote * * This program is Free Software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.grobox.transportr.trips.detail import androidx.recyclerview.widget.RecyclerView.Adapter import android.view.LayoutInflater import android.view.ViewGroup import de.grobox.transportr.R import de.grobox.transportr.trips.detail.LegViewHolder.LegType import de.grobox.transportr.trips.detail.LegViewHolder.LegType.* import de.schildbach.pte.dto.Trip.Leg internal class LegAdapter internal constructor( private val legs: List<Leg>, private val listener: LegClickListener, private val showLineName: Boolean) : Adapter<LegViewHolder>() { override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): LegViewHolder { val v = LayoutInflater.from(viewGroup.context).inflate(R.layout.list_item_leg, viewGroup, false) return LegViewHolder(v, listener, showLineName) } override fun onBindViewHolder(ui: LegViewHolder, i: Int) { val leg = legs[i] ui.bind(leg, getLegType(i)) } override fun getItemCount(): Int { return legs.size } private fun getLegType(position: Int): LegType { return when { legs.size == 1 -> FIRST_LAST position == 0 -> FIRST position == legs.size - 1 -> LAST else -> MIDDLE } } }
gpl-3.0
AlburIvan/MavenRepoShell
src/main/kotlin/com.raworkstudio.spring/Main.kt
1
499
package com.raworkstudio.spring import org.springframework.shell.Bootstrap import java.io.IOException /** * Driver class to run the helloworld example. * @author Mark Pollack */ object Main { /** * Main class that delegates to Spring Shell's Bootstrap class in order to simplify debugging inside an IDE * @param args * * * @throws IOException */ @Throws(IOException::class) @JvmStatic fun main(args: Array<String>) { Bootstrap.main(args) } }
apache-2.0
ihmc/nomads
misc/java/netjson-to-measure/src/main/kotlin/netjson/messages/NetworkCollectionMessage.kt
1
199
package netjson.messages import netjson.general.NetJSONObject class NetworkCollectionMessage : NetJSONObject() { override val type: String = "" val collection: List<NetJSONObject>? = null }
gpl-3.0
Jire/Acelta
src/main/kotlin/com/acelta/packet/SplitPacketeer.kt
1
1752
package com.acelta.packet import com.acelta.packet.Packeteer.AccessMode open class SplitPacketeer<T : Packeteer> : Packeteer { open lateinit var read: T open lateinit var write: T override var readIndex: Int get() = read.readIndex set(value) { read.readIndex = value } override fun get(index: Int) = read[index] override fun skip(bytes: Int) = read.skip(bytes) override val readable: Int get() = read.readable override val byte: Byte get() = read.byte override val short: Short get() = read.short override val int: Int get() = read.int override val long: Long get() = read.long override val string: String get() = read.string override var writeIndex: Int get() = write.writeIndex set(value) { write.writeIndex = value } override fun clear() = write.clear() override fun ensureWritable(bytes: Int) = write.ensureWritable(bytes) override fun set(index: Int, value: Int) { write[index] = value } override fun plus(values: ByteArray) = write + values override fun plus(value: Packeteer) = write + value override fun plus(value: Byte) = write + value override fun plus(value: Short) = write + value override fun plus(value: Int) = write + value override fun plus(value: Long) = write + value override fun plus(value: String) = write + value override var bitIndex: Int = 0 get() = write.bitIndex override var accessMode: AccessMode get() = write.accessMode set(value) { write.accessMode = value } override fun bitAccess() = write.bitAccess() override fun finishBitAccess() = write.finishBitAccess() override fun ensureAccessMode(accessMode: AccessMode) = write.ensureAccessMode(accessMode) override fun bits(numBits: Int, value: Int) = write.bits(numBits, value) }
gpl-3.0
google/private-compute-libraries
java/com/google/android/libraries/pcc/chronicle/codegen/Type.kt
1
4324
/* * Copyright 2022 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.google.android.libraries.pcc.chronicle.codegen /** * A [TypeSet] contains the result of the run of a converter frontend. It contains a single * top-level type, along with any supporting types needed to fully represent the fields of the type, * including any recursive dependencies required by nested types. */ data class TypeSet(val primary: Type, val additional: Set<Type> = emptySet()) : Set<Type> { constructor(vararg allTypes: Type) : this(allTypes.first(), allTypes.drop(1).toSet()) override val size = additional.size + 1 override fun contains(element: Type) = primary == element || additional.contains(element) override fun containsAll(elements: Collection<Type>) = elements.all { contains(it) } override fun isEmpty() = false override fun iterator(): Iterator<Type> { return iterator { yield(primary) additional.forEach { yield(it) } } } } /** * Intermediary representation of a POJO/Proto for use converting to a Chronicle schema. * * @param location The [TypeLocation] of the underlying Java/Kotlin type * @param fields The fields the type contains * @param oneOfs Information about mutually-exclusive field groups (from protos) conversion. The * `Set<Type>` returned from a frontend should contain exactly one item with this flag set. */ data class Type( val location: TypeLocation, val fields: List<FieldEntry>, val oneOfs: OneOfs = OneOfs(), val jvmLocation: TypeLocation = location, val tooling: Tooling = Tooling.UNKNOWN ) { val name = location.name val enclosingNames = location.enclosingNames val pkg = location.pkg /** * The library or framework within which the type was defined. * * This can be useful when generating code when it comes to knowing how to approach doing things * like creating a new instance of a type or returning a copy with a changed field. */ enum class Tooling { /** The [Type] was defined by a protocol buffer descriptor. */ PROTO, /** The [Type] was defined as an AutoValue abstract class. */ AUTOVALUE, /** The [Type] was defined as a kotlin data class. */ DATA_CLASS, /** It is either unknown or unsupported which system the [Type] was defined within. */ UNKNOWN, } } /** * Information needed to locate a Java/Kotlin type. * * @param name The simple name of the type * @param enclosingNames a list of names of enclosing types for the type, ordered innermost-first. * @param pkg The package containing the type */ data class TypeLocation( val name: String, val enclosingNames: List<String> = emptyList(), val pkg: String ) { override fun toString(): String { val fullName = (enclosingNames.reversed().filter { it.isNotEmpty() } + name).joinToString(".") return "$pkg.$fullName" } } /** * Describes one field in a structure that will become a Chronicle schema. * * @property name the name to use in the generated schema * @property category the FieldCategory of the field * @property sourceName the name in the source structure, can be an arbitrary code snippet * @property presenceCondition the code to emit to detect the presence of this field in the object */ data class FieldEntry( val name: String, val category: FieldCategory, val sourceName: String = name, val presenceCondition: String = "" ) /** * A structure to hold information of "oneof" protobuf fields. * * @property oneOfForField a map from a field name to the field name of its containing oneof field. * @property fieldsForOneOf a map from a oneof field name to a list of the field names it contains. */ data class OneOfs( val oneOfForField: Map<String, String> = emptyMap(), val fieldsForOneOf: Map<String, List<String>> = emptyMap() )
apache-2.0
kamgurgul/cpu-info
app/src/main/java/com/kgurgul/cpuinfo/features/information/sensors/SensorsInfoViewModel.kt
1
5907
/* * Copyright 2017 KG Soft * * 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.kgurgul.cpuinfo.features.information.sensors import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import androidx.lifecycle.ViewModel import com.kgurgul.cpuinfo.utils.lifecycleawarelist.ListLiveData import com.kgurgul.cpuinfo.utils.round1 import com.kgurgul.cpuinfo.utils.runOnApiAbove import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject /** * ViewModel for sensors data * * @author kgurgul */ @HiltViewModel class SensorsInfoViewModel @Inject constructor( private val sensorManager: SensorManager ) : ViewModel(), SensorEventListener { val listLiveData = ListLiveData<Pair<String, String>>() private val sensorList = sensorManager.getSensorList(Sensor.TYPE_ALL) @Synchronized fun startProvidingData() { if (listLiveData.isEmpty()) { listLiveData.addAll(sensorList.map { Pair(it.name, " ") }) } // Start register process on new Thread to avoid UI block Thread { for (sensor in sensorList) { sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL) } }.start() } fun stopProvidingData() { Thread { sensorManager.unregisterListener(this) }.start() } override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) { // Do nothing } override fun onSensorChanged(event: SensorEvent) { updateSensorInfo(event) } /** * Replace sensor value with the new one */ @Synchronized private fun updateSensorInfo(event: SensorEvent) { val updatedRowId = sensorList.indexOf(event.sensor) listLiveData[updatedRowId] = Pair(event.sensor.name, getSensorData(event)) } /** * Detect sensor type for passed [SensorEvent] and format it to the correct unit */ @Suppress("DEPRECATION") private fun getSensorData(event: SensorEvent): String { var data = " " val sensorType = event.sensor.type when (sensorType) { Sensor.TYPE_ACCELEROMETER, Sensor.TYPE_GRAVITY, Sensor.TYPE_LINEAR_ACCELERATION -> data = "X=${event.values[0].round1()}m/sยฒ Y=${ event.values[1].round1()}m/sยฒ Z=${event.values[2].round1()}m/sยฒ" Sensor.TYPE_GYROSCOPE -> data = "X=${event.values[0].round1()}rad/s Y=${ event.values[1].round1()}rad/s Z=${event.values[2].round1()}rad/s" Sensor.TYPE_ROTATION_VECTOR -> data = "X=${event.values[0].round1()} Y=${ event.values[1].round1()} Z=${event.values[2].round1()}" Sensor.TYPE_MAGNETIC_FIELD -> data = "X=${event.values[0].round1()}ฮผT Y=${ event.values[1].round1()}ฮผT Z=${event.values[2].round1()}ฮผT" Sensor.TYPE_ORIENTATION -> data = "Azimuth=${event.values[0].round1()}ยฐ Pitch=${ event.values[1].round1()}ยฐ Roll=${event.values[2].round1()}ยฐ" Sensor.TYPE_PROXIMITY -> data = "Distance=${event.values[0].round1()}cm" Sensor.TYPE_AMBIENT_TEMPERATURE -> data = "Air temperature=${event.values[0].round1()}ยฐC" Sensor.TYPE_LIGHT -> data = "Illuminance=${event.values[0].round1()}lx" Sensor.TYPE_PRESSURE -> data = "Air pressure=${event.values[0].round1()}hPa" Sensor.TYPE_RELATIVE_HUMIDITY -> data = "Relative humidity=${event.values[0].round1()}%" Sensor.TYPE_TEMPERATURE -> data = "Device temperature=${event.values[0].round1()}ยฐC" } // TODO: Multiline support for this kind of data is necessary runOnApiAbove(17) { when (sensorType) { Sensor.TYPE_GYROSCOPE_UNCALIBRATED -> data = "X=${event.values[0].round1()}rad/s Y=${ event.values[1].round1()}rad/s Z=${ event.values[2].round1()}rad/s" /*\nEstimated drift: X=${ event.values[3].round1() }rad/s Y=${ event.values[4].round1() }rad/s Z=${ event.values[5].round1() }rad/s"*/ Sensor.TYPE_GAME_ROTATION_VECTOR -> data = "X=${event.values[0].round1()} Y=${ event.values[1].round1()} Z=${event.values[2].round1()}" Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED -> data = "X=${event.values[0].round1()}ฮผT Y=${ event.values[1].round1()}ฮผT Z=${ event.values[2].round1()}ฮผT" /*\nIron bias: X=${ event.values[3].round1() }ฮผT Y=${ event.values[4].round1() }ฮผT Z=${ event.values[5].round1() }ฮผT"*/ } } runOnApiAbove(18) { when (sensorType) { Sensor.TYPE_GEOMAGNETIC_ROTATION_VECTOR -> data = "X=${event.values[0].round1()} Y=${ event.values[1].round1()} Z=${event.values[2].round1()}" } } return data } }
apache-2.0
funfunStudy/algorithm
kotlin/src/main/kotlin/LilyHomework.kt
1
2437
import java.util.* fun main(args: Array<String>) { require(lilysHomework(arrayOf(3, 5, 2, 6, 1)) == 2) require(lilysHomework(arrayOf(3, 2, 1)) == 0) } fun lilysHomework(arr: Array<Int>): Int { val startSize = arr.size val asc = asc(Arrays.copyOf(arr, startSize), startSize) val desc = desc(Arrays.copyOf(arr, startSize), startSize) return if (asc < desc) asc else desc } tailrec fun asc(arrays: Array<Int>, startSize: Int, acc: Int = 0): Int { return when (arrays.size) { 0 -> acc else -> { val firstValue = arrays[0] val position = getMinValuePosition(arrays.toList(), 0, firstValue, 0) arrays[0] = arrays[position] arrays[position] = firstValue val arrayCopy = arrays.sliceArray(1 until startSize) asc(arrayCopy, startSize - 1, acc + if (position == 0) 0 else 1) } } } tailrec fun desc(arrays: Array<Int>, startSize: Int, acc: Int = 0): Int { return when (arrays.size) { 0 -> acc else -> { val firstValue = arrays[0] val position = getMaxValuePosition(arrays.toList(), 0, firstValue, 0) arrays[0] = arrays[position] arrays[position] = firstValue val arrayCopy = arrays.sliceArray(1 until startSize) desc(arrayCopy, startSize - 1, acc + if (position == 0) 0 else 1) } } } tailrec fun getMinValuePosition( list: List<Int>, position: Int, min: Int, currentPosition: Int ): Int = when (list.isEmpty()) { true -> position false -> { val firstValue = list[0] getMinValuePosition( list.drop(1), if (min < firstValue) position else currentPosition, if (min < firstValue) min else firstValue, currentPosition + 1) } } tailrec fun getMaxValuePosition(list: List<Int>, position: Int, max: Int, currentPosition: Int): Int = when (list.isEmpty()) { true -> position false -> { val firstValueInList = list[0] getMaxValuePosition( list.drop(1), if (max > firstValueInList) position else currentPosition, if (max > firstValueInList) max else firstValueInList, currentPosition + 1 ) } }
mit
joseph-roque/BowlingCompanion
app/src/main/java/ca/josephroque/bowlingcompanion/statistics/impl/general/BowlerNameStatistic.kt
1
1857
package ca.josephroque.bowlingcompanion.statistics.impl.general import android.os.Parcel import android.os.Parcelable import ca.josephroque.bowlingcompanion.R import ca.josephroque.bowlingcompanion.common.interfaces.parcelableCreator import ca.josephroque.bowlingcompanion.statistics.StatisticsCategory import ca.josephroque.bowlingcompanion.statistics.StringStatistic import ca.josephroque.bowlingcompanion.statistics.unit.BowlerUnit import ca.josephroque.bowlingcompanion.statistics.unit.GameUnit import ca.josephroque.bowlingcompanion.statistics.unit.LeagueUnit import ca.josephroque.bowlingcompanion.statistics.unit.SeriesUnit import ca.josephroque.bowlingcompanion.statistics.unit.StatisticsUnit /** * Copyright (C) 2018 Joseph Roque * * Name of the bowler whose statistics are on display. */ class BowlerNameStatistic(override var value: String = "") : StringStatistic { // MARK: Modifiers /** @Override */ override fun modify(unit: StatisticsUnit) { when (unit) { is GameUnit -> value = unit.bowlerName is SeriesUnit -> value = unit.bowlerName is LeagueUnit -> value = unit.bowlerName is BowlerUnit -> value = unit.name } } // MARK: Overrides override val titleId = Id override val id = Id.toLong() override val category = StatisticsCategory.General override fun isModifiedBy(unit: StatisticsUnit) = true // MARK: Parcelable companion object { /** Creator, required by [Parcelable]. */ @Suppress("unused") @JvmField val CREATOR = parcelableCreator(::BowlerNameStatistic) /** Unique ID for the statistic. */ const val Id = R.string.statistic_bowler } /** * Construct this statistic from a [Parcel]. */ private constructor(p: Parcel): this(value = p.readString()!!) }
mit
rori-dev/lunchbox
backend-spring-kotlin/src/test/kotlin/lunchbox/util/pdf/PdfTextGroupStripperTest.kt
1
3505
package lunchbox.util.pdf import io.mockk.every import io.mockk.mockk import org.amshove.kluent.shouldBe import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldHaveSize import org.apache.pdfbox.text.TextPosition import org.junit.jupiter.api.Test class PdfTextGroupStripperTest { @Test fun `should equip TextGroup with one letter`() { val text_a = text(Pos(1.0f, 2.0f), 1.0f, 2.0f, "a") val group = TextGroup(listOf(text_a)) group.toString() shouldBeEqualTo "a" group.xMin() shouldBeEqualTo 1.0f group.xMid() shouldBeEqualTo 1.5f group.xMax() shouldBeEqualTo 2.0f group.yMin() shouldBeEqualTo 2.0f group.yMid() shouldBeEqualTo 3.0f group.yMax() shouldBeEqualTo 4.0f group.width() shouldBeEqualTo 1.0f group.height() shouldBeEqualTo 2.0f group.xIn(0.8f) shouldBe false group.xIn(1.0f) shouldBe true group.xIn(1.5f) shouldBe true group.xIn(2.0f) shouldBe true group.xIn(2.2f) shouldBe false group.yIn(1.8f) shouldBe false group.yIn(2.0f) shouldBe true group.yIn(3.0f) shouldBe true group.yIn(4.0f) shouldBe true group.yIn(4.2f) shouldBe false } @Test fun `should equip TextGroup with three letters`() { val text_a = text(Pos(1.0f, 2.0f), 1.0f, 2.0f, "a") val text_b = text(Pos(2.0f, 2.0f), 1.0f, 2.0f, "b") val text_c = text(Pos(3.0f, 2.0f), 1.0f, 2.0f, "c") val group = TextGroup(listOf(text_a, text_b, text_c)) group.toString() shouldBeEqualTo "abc" group.xMin() shouldBeEqualTo 1.0f group.xMax() shouldBeEqualTo 4.0f group.xMid() shouldBeEqualTo 2.5f group.yMin() shouldBeEqualTo 2.0f group.yMax() shouldBeEqualTo 4.0f group.yMid() shouldBeEqualTo 3.0f group.width() shouldBeEqualTo 3.0f group.height() shouldBeEqualTo 2.0f group.xIn(0.8f) shouldBe false group.xIn(1.0f) shouldBe true group.xIn(2.5f) shouldBe true group.xIn(4.0f) shouldBe true group.xIn(4.2f) shouldBe false group.yIn(1.8f) shouldBe false group.yIn(2.0f) shouldBe true group.yIn(3.0f) shouldBe true group.yIn(4.0f) shouldBe true group.yIn(4.2f) shouldBe false } @Test fun `extract text groups from simple table`() { val url = javaClass.getResource("/simple_table.pdf") val textGroups = PdfExtractor.extractGroups(url) textGroups shouldHaveSize 4 val text_11 = textGroups.filter { it.toString() == "row 1 column 1" } text_11 shouldHaveSize 1 val text_12 = textGroups.filter { it.toString() == "row 1 column 2" } text_12 shouldHaveSize 1 val text_21 = textGroups.filter { it.toString() == "row 2 column 1" } text_21 shouldHaveSize 1 val text_22 = textGroups.filter { it.toString() == "row 2 column 2" } text_22 shouldHaveSize 1 text_11[0].xIn(text_12[0].xMid()) shouldBe false text_11[0].yIn(text_12[0].yMid()) shouldBe true text_11[0].xIn(text_21[0].xMid()) shouldBe true text_11[0].yIn(text_21[0].yMid()) shouldBe false text_11[0].xIn(text_22[0].xMid()) shouldBe false text_11[0].yIn(text_22[0].yMid()) shouldBe false } private fun text(pos: Pos, width: Float, height: Float, char: String): TextPosition { val mockPos = mockk<TextPosition>() every { mockPos.x } returns pos.x every { mockPos.y } returns pos.y every { mockPos.width } returns width every { mockPos.height } returns height every { mockPos.toString() } returns char return mockPos } data class Pos(val x: Float, val y: Float) }
mit
ajalt/clikt
clikt/src/jsMain/kotlin/com/github/ajalt/clikt/mpp/JsCompat.kt
1
2100
package com.github.ajalt.clikt.mpp // https://github.com/iliakan/detect-node private val isNode: Boolean = js( "Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'" ) as Boolean /** Load module [mod], or throw an exception if not running on NodeJS */ internal fun nodeRequire(mod: String): dynamic { require(isNode) { "Module not available: $mod" } // This hack exists to silence webpack warnings when running on the browser. `require` is a // built-in function on Node, and doesn't exist on browsers. Webpack will statically look for // calls to `require` and rewrite them into its own module loading system. This means that when // we have `require("fs")` in our code, webpack will complain during compilation with two types // of warnings: // // 1. It will warn about the module not existing (since it's node-only), even if we never // execute that statement at runtime on the browser. // 2. It will complain with a different warning if the argument to `require` isn't static // (e.g. `fun myRequire(m:String) { require(m) }`). // // If we do run `require("fs")` on the browser, webpack will normally cause it to throw a // `METHOD_NOT_FOUND` error. If the user marks `fs` as "external" in their webpack // configuration, it will silence the first type of warning above, and the `require` call // will now return `undefined` instead of throwing an exception. // // So since we never call `require` at runtime on browsers anyway, we hide our `require` // calls from webpack by loading the method dynamically. This prevents any warnings, and // doesn't require users to add anything to their webpack config. val imported = try { js("module['' + 'require']")(mod) } catch (e: dynamic) { throw IllegalArgumentException("Module not available: $mod", e as? Throwable) } require( imported != null && js("typeof imported !== 'undefined'").unsafeCast<Boolean>() ) { "Module not available: $mod" } return imported }
apache-2.0
cketti/k-9
app/ui/message-list-widget/src/main/java/app/k9mail/ui/widget/list/MessageListItem.kt
1
565
package app.k9mail.ui.widget.list import com.fsck.k9.controller.MessageReference internal data class MessageListItem( val displayName: String, val displayDate: String, val subject: String, val preview: String, val isRead: Boolean, val hasAttachments: Boolean, val threadCount: Int, val accountColor: Int, val messageReference: MessageReference, val uniqueId: Long, val sortSubject: String?, val sortMessageDate: Long, val sortInternalDate: Long, val sortIsStarred: Boolean, val sortDatabaseId: Long, )
apache-2.0
BracketCove/PosTrainer
androiddata/src/main/java/com/wiseassblog/androiddata/data/reminderapi/NotificationManager.kt
1
2816
package com.wiseassblog.androiddata.data.reminderapi import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.graphics.Color import android.os.Build import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import com.wiseassblog.androiddata.R import com.wiseassblog.androiddata.data.* object NotificationManager { internal fun showNotification(reminderId: String, context: Context) { createNotificationChannel(context) val notification = NotificationCompat.Builder(context, CHANNEL_REMINDER) .setContentTitle(NOTIFICATION_DISMISS_TITLE) .setContentText(NOTIFICATION_CONTENT) .setColor(Color.BLUE) .setSmallIcon(R.drawable.ic_alarm_black_48dp) .setOngoing(true) //cancel on click .setAutoCancel(true) .setDefaults(NotificationCompat.DEFAULT_LIGHTS) .setWhen(0) .setCategory(NotificationCompat.CATEGORY_REMINDER) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setLocalOnly(true) notification.setContentIntent( getDismissIntent(context, reminderId) ) notification.setPriority(NotificationCompat.PRIORITY_MAX) NotificationManagerCompat.from(context).notify( NOTIFICATION_DISMISS_ID, notification.build() ) } private fun getDismissIntent(context: Context, reminderId: String): PendingIntent { return Intent(context, ReminderService::class.java).let { it.action = ACTION_REMINDER_DISMISSED it.putExtra(REMINDER_ID, reminderId) PendingIntent.getService( context, NOTIFICATION_DISMISS_ID, it, PendingIntent.FLAG_UPDATE_CURRENT ) } } private fun createNotificationChannel(context: Context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Create the NotificationChannel val name = CHANNEL_REMINDER val descriptionText = CHANNEL_DISMISS_DESCRIPTION val importance = NotificationManager.IMPORTANCE_HIGH val channel = NotificationChannel(CHANNEL_REMINDER, CHANNEL_DISMISS_NAME, importance) channel.description = descriptionText // Register the channel with the system; you can't change the importance // or other notification behaviors after this val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) } } }
apache-2.0
JustinMullin/drifter-kotlin
src/main/kotlin/xyz/jmullin/drifter/rendering/shader/ShaderUniforms.kt
1
3581
package xyz.jmullin.drifter.rendering.shader import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.glutils.ShaderProgram import com.badlogic.gdx.math.Matrix3 import com.badlogic.gdx.math.Matrix4 import com.badlogic.gdx.math.Vector2 import com.badlogic.gdx.math.Vector3 abstract class ShaderUniform<T>(internal val program: ShaderProgram, internal val name: String, open val tick: (() -> T)?) { abstract fun set(value: T) fun setFromTick() { tick?.let { set(it()) } } } typealias Uniform<T> = (program: ShaderProgram, name: String) -> (T) -> Unit object Uniforms { val boolean: Uniform<Boolean> = { p, name -> { value -> p.setUniformi(name, if(value) 1 else 0) } } val int: Uniform<Int> = { p, name -> { value -> p.setUniformi(name, value) } } val float: Uniform<Float> = { p, name -> { value -> p.setUniformf(name, value) } } val vector2: Uniform<Vector2> = { p, name -> { value -> p.setUniformf(name, value) } } val vector3: Uniform<Vector3> = { p, name -> { value -> p.setUniformf(name, value) } } val matrix3: Uniform<Matrix3> = { p, name -> { value -> p.setUniformMatrix(name, value) } } val matrix4: Uniform<Matrix4> = { p, name -> { value -> p.setUniformMatrix(name, value) } } val color: Uniform<Color> = { p, name -> { value -> p.setUniformf(name, value) } } } class BooleanUniform(program: ShaderProgram, name: String, override val tick: (() -> Boolean)?) : ShaderUniform<Boolean>(program, name, tick) { override fun set(value: Boolean) = Uniforms.boolean(program, name)(value) } class IntUniform(program: ShaderProgram, name: String, override val tick: (() -> Int)?) : ShaderUniform<Int>(program, name, tick) { override fun set(value: Int) = Uniforms.int(program, name)(value) } class FloatUniform(program: ShaderProgram, name: String, override val tick: (() -> Float)?) : ShaderUniform<Float>(program, name, tick) { override fun set(value: Float) = Uniforms.float(program, name)(value) } class Vector2Uniform(program: ShaderProgram, name: String, override val tick: (() -> Vector2)?) : ShaderUniform<Vector2>(program, name, tick) { override fun set(value: Vector2) = Uniforms.vector2(program, name)(value) } class Vector3Uniform(program: ShaderProgram, name: String, override val tick: (() -> Vector3)?) : ShaderUniform<Vector3>(program, name, tick) { override fun set(value: Vector3) = Uniforms.vector3(program, name)(value) } class Matrix3Uniform(program: ShaderProgram, name: String, override val tick: (() -> Matrix3)?) : ShaderUniform<Matrix3>(program, name, tick) { override fun set(value: Matrix3) = Uniforms.matrix3(program, name)(value) } class Matrix4Uniform(program: ShaderProgram, name: String, override val tick: (() -> Matrix4)?) : ShaderUniform<Matrix4>(program, name, tick) { override fun set(value: Matrix4) = Uniforms.matrix4(program, name)(value) } class ColorUniform(program: ShaderProgram, name: String, override val tick: (() -> Color)?) : ShaderUniform<Color>(program, name, tick) { override fun set(value: Color) = Uniforms.color(program, name)(value) } class ArrayUniform<T>(program: ShaderProgram, name: String, private val subUniform: Uniform<T>, override val tick: (() -> List<T>)?) : ShaderUniform<List<T>>(program, name, tick) { override fun set(value: List<T>) { value.forEachIndexed { i, v -> subUniform(program, "$name[$i]")(v) } } }
mit
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/utils/sources/UserTokenSource.kt
1
1397
package net.perfectdreams.loritta.cinnamon.discord.utils.sources import dev.kord.core.Kord import dev.kord.core.cache.data.MemberData import dev.kord.core.cache.data.UserData import net.perfectdreams.loritta.cinnamon.discord.utils.DiscordUserAvatar import net.perfectdreams.loritta.common.utils.Placeholders class UserTokenSource( private val kord: Kord, private val user: UserData, private val member: MemberData? ) : TokenSource { override fun tokens() = mapOf( Placeholders.USER_MENTION to "<@${user.id}>", Placeholders.USER_NAME_SHORT to user.username, Placeholders.USER_NAME to user.username, Placeholders.USER_DISCRIMINATOR to user.discriminator, Placeholders.USER_ID to user.id.toString(), Placeholders.USER_AVATAR_URL to DiscordUserAvatar(kord, user.id, user.discriminator, user.avatar).cdnUrl.toUrl(), Placeholders.USER_TAG to "${user.username}#${user.discriminator}", Placeholders.USER_NICKNAME to (member?.nick?.value ?: user.username), Placeholders.Deprecated.USER_NICKNAME to (member?.nick?.value ?: user.username), Placeholders.Deprecated.USER_ID to user.id.toString(), Placeholders.Deprecated.USER_DISCRIMINATOR to user.discriminator, Placeholders.Deprecated.USER_AVATAR_URL to DiscordUserAvatar(kord, user.id, user.discriminator, user.avatar).cdnUrl.toUrl() ) }
agpl-3.0
signed/intellij-community
platform/platform-impl/src/com/intellij/openapi/keymap/impl/DefaultKeymap.kt
1
4745
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.keymap.impl import com.intellij.configurationStore.SchemeDataHolder import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diagnostic.catchAndLog import com.intellij.openapi.extensions.Extensions import com.intellij.openapi.keymap.Keymap import com.intellij.openapi.keymap.KeymapManager import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtilRt import gnu.trove.THashMap import org.jdom.Element import java.util.* private val LOG = Logger.getInstance("#com.intellij.openapi.keymap.impl.DefaultKeymap") open class DefaultKeymap { private val myKeymaps = ArrayList<Keymap>() private val nameToScheme = THashMap<String, Keymap>() protected open val providers: Array<BundledKeymapProvider> get() = Extensions.getExtensions(BundledKeymapProvider.EP_NAME) init { for (provider in providers) { for (fileName in provider.keymapFileNames) { // backward compatibility (no external usages of BundledKeymapProvider, but maybe it is not published to plugin manager) val key = when (fileName) { "Keymap_Default.xml" -> "\$default.xml" "Keymap_Mac.xml" -> "Mac OS X 10.5+.xml" "Keymap_MacClassic.xml" -> "Mac OS X.xml" "Keymap_GNOME.xml" -> "Default for GNOME.xml" "Keymap_KDE.xml" -> "Default for KDE.xml" "Keymap_XWin.xml" -> "Default for XWin.xml" "Keymap_EclipseMac.xml" -> "Eclipse (Mac OS X).xml" "Keymap_Eclipse.xml" -> "Eclipse.xml" "Keymap_Emacs.xml" -> "Emacs.xml" "JBuilderKeymap.xml" -> "JBuilder.xml" "Keymap_Netbeans.xml" -> "NetBeans 6.5.xml" "Keymap_ReSharper_OSX.xml" -> "ReSharper OSX.xml" "Keymap_ReSharper.xml" -> "ReSharper.xml" "RM_TextMateKeymap.xml" -> "TextMate.xml" "Keymap_Xcode.xml" -> "Xcode.xml" else -> fileName } LOG.catchAndLog { loadKeymapsFromElement(object: SchemeDataHolder<KeymapImpl> { override fun read() = provider.load(key) { JDOMUtil.load(it) } override fun updateDigest(scheme: KeymapImpl) { } override fun updateDigest(data: Element) { } }, FileUtilRt.getNameWithoutExtension(key)) } } } } companion object { @JvmStatic val instance: DefaultKeymap get() = ServiceManager.getService(DefaultKeymap::class.java) @JvmStatic fun matchesPlatform(keymap: Keymap): Boolean { val name = keymap.name return when (name) { KeymapManager.DEFAULT_IDEA_KEYMAP -> SystemInfo.isWindows KeymapManager.MAC_OS_X_KEYMAP, KeymapManager.MAC_OS_X_10_5_PLUS_KEYMAP -> SystemInfo.isMac KeymapManager.X_WINDOW_KEYMAP, KeymapManager.GNOME_KEYMAP, KeymapManager.KDE_KEYMAP -> SystemInfo.isXWindow else -> true } } } private fun loadKeymapsFromElement(dataHolder: SchemeDataHolder<KeymapImpl>, keymapName: String) { val keymap = if (keymapName.startsWith(KeymapManager.MAC_OS_X_KEYMAP)) MacOSDefaultKeymap(dataHolder, this) else DefaultKeymapImpl(dataHolder, this) keymap.name = keymapName myKeymaps.add(keymap) nameToScheme.put(keymapName, keymap) } val keymaps: Array<Keymap> get() = myKeymaps.toTypedArray() internal fun findScheme(name: String) = nameToScheme.get(name) open val defaultKeymapName: String get() = when { SystemInfo.isMac -> KeymapManager.MAC_OS_X_KEYMAP SystemInfo.isGNOME -> KeymapManager.GNOME_KEYMAP SystemInfo.isKDE -> KeymapManager.KDE_KEYMAP SystemInfo.isXWindow -> KeymapManager.X_WINDOW_KEYMAP else -> KeymapManager.DEFAULT_IDEA_KEYMAP } open fun getKeymapPresentableName(keymap: KeymapImpl): String { val name = keymap.name // Netbeans keymap is no longer for version 6.5, but we need to keep the id if (name == "NetBeans 6.5") { return "NetBeans" } return if (KeymapManager.DEFAULT_IDEA_KEYMAP == name) "Default" else name } }
apache-2.0
saru95/DSA
Kotlin/InsertionSort.kt
1
1187
// cruxiu :) import java.util.ArrayList import java.util.Scanner class InsertionSort { fun insertionSort(list: Array<Integer>): Array<Integer> { var temp: Int for (i in 1 until list.size) { for (j in i downTo 1) { if (list[j] < list[j - 1]) { temp = list[j].toInt() list[j] = list[j - 1] list[j - 1] = temp } } } return list } fun main(a: Array<String>) { val scanner = Scanner(System.`in`) val arrayList = ArrayList<Integer>() System.out.println("Please, enter the elements of the list.") while (scanner.hasNextInt()) { arrayList.add(scanner.nextInt()) } var array = arrayList.toArray(arrayOfNulls<Integer>(0)) System.out.println("Now, we will sort the list. Your list now is:") for (i in array.indices) { System.out.println(array[i]) } array = insertionSort(array) System.out.println("After sort, your list now is:") for (i in array.indices) { System.out.println(array[i]) } } }
mit
christophpickl/gadsu
src/test/kotlin/at/cpickl/gadsu/testinfra/date.kt
1
755
package at.cpickl.gadsu.testinfra import at.cpickl.gadsu.service.* import org.joda.time.DateTime val TEST_UUID1 = "1"//"11111111-1234-1234-1234-000000000000" val TEST_UUID2 = "2"//"22222222-1234-1234-1234-000000000000" val TEST_DATETIME1 = "01.01.2000 00:15:20".parseDateTime() val TEST_DATETIME_FOR_TREATMENT_DATE = TEST_DATETIME1.clearMinutes() val TEST_DATETIME2 = "31.12.2002 23:59:58".parseDateTime() val TEST_DATETIME2_WITHOUT_SECONDS = TEST_DATETIME2.clearSeconds() val TEST_DATE_1985 = DateFormats.DATE.parseDateTime("10.03.1985").clearTime() class SimpleTestableClock(_now: DateTime? = null): Clock { var now: DateTime = _now ?: TEST_DATETIME1 override fun now() = now override fun nowWithoutSeconds() = now.clearSeconds() }
apache-2.0
christophpickl/gadsu
src/main/kotlin/at/cpickl/gadsu/version/service.kt
1
3928
package at.cpickl.gadsu.version import at.cpickl.gadsu.global.APP_SUFFIX import at.cpickl.gadsu.global.AppStartupEvent import at.cpickl.gadsu.global.GadsuSystemProperty import at.cpickl.gadsu.preferences.Prefs import at.cpickl.gadsu.service.InternetConnectionLostEvent import at.cpickl.gadsu.service.LOG import at.cpickl.gadsu.service.NoInternetConnectionException import at.cpickl.gadsu.service.OpenWebpageEvent import at.cpickl.gadsu.view.AsyncDialogSettings import at.cpickl.gadsu.view.AsyncWorker import at.cpickl.gadsu.view.components.DialogType import at.cpickl.gadsu.view.components.Dialogs import at.cpickl.gadsu.view.currentActiveJFrame import com.google.common.eventbus.EventBus import com.google.common.eventbus.Subscribe import java.net.URL import javax.inject.Inject interface VersionUpdater { // nothing, just via events :) } open class VersionUpdaterImpl @Inject constructor( private val checker: VersionChecker, private val dialogs: Dialogs, private val asyncWorker: AsyncWorker, private val bus: EventBus, private val prefs: Prefs ) : VersionUpdater { private val log = LOG(javaClass) private val dialogTitle = "Auto Update" private fun checkForUpdates(settings: AsyncDialogSettings?) { log.debug("validateVersion(settings)") asyncWorker.doInBackground(settings, { checker.check() }, { onResult(result = it!!, suppressUpToDateDialog = settings == null) }, { e -> if (e is NoInternetConnectionException) { bus.post(InternetConnectionLostEvent()) } else { throw e } }) } @Subscribe open fun onAppStartupEvent(event: AppStartupEvent) { if (prefs.preferencesData.checkUpdates) { if (GadsuSystemProperty.disableAutoUpdate.isEnabledOrFalse()) { log.warn("Auto update disabled (most likely because of UI test).") } else { log.debug("Preferences stated we should check updates on startup") checkForUpdates(null) // dont display progress dialog when checking at startup } } } @Subscribe open fun onCheckForUpdatesEvent(event: CheckForUpdatesEvent) { checkForUpdates(AsyncDialogSettings(dialogTitle, "Prรผfe die aktuellste Version ...")) } private fun onResult(result: VersionCheckResult, suppressUpToDateDialog: Boolean = false) { log.trace("onResult(result={}, suppressUpToDateDialog={})", result, suppressUpToDateDialog) when (result) { is VersionCheckResult.UpToDate -> { if (!suppressUpToDateDialog) { dialogs.show(dialogTitle, "Juchu, du hast die aktuellste Version installiert!", arrayOf("Ok"), null, DialogType.INFO, currentActiveJFrame()) } } is VersionCheckResult.OutDated -> { val selected = dialogs.show(dialogTitle, "Es gibt eine neuere Version von Gadsu.\n" + "Du benutzt zur Zeit ${result.current.toLabel()} aber es ist bereits Version ${result.latest.toLabel()} verfรผgbar.\n" + "Bitte lade die neueste Version herunter.", arrayOf("Download starten"), null, DialogType.WARN, currentActiveJFrame()) if (selected == null) { log.debug("User closed window by hitting the close button, seems as he doesnt care about using the latest version :-/") return } val version = result.latest.toLabel() val downloadUrl = "https://github.com/christophpickl/gadsu/releases/download/v$version/Gadsu-$version.${APP_SUFFIX}" log.info("Going to download latest gadsu version from: {}", downloadUrl) bus.post(OpenWebpageEvent(URL(downloadUrl))) } } } }
apache-2.0
Bombe/Sone
src/test/kotlin/net/pterodactylus/sone/fcp/GetSoneCommandTest.kt
1
3302
package net.pterodactylus.sone.fcp import net.pterodactylus.sone.core.Core import net.pterodactylus.sone.freenet.fcp.FcpException import net.pterodactylus.sone.test.whenever import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.equalTo import org.hamcrest.Matchers.nullValue import org.junit.Test /** * Unit test for [GetSoneCommand]. */ class GetSoneCommandTest : SoneCommandTest() { private val sone = createSone("SoneId", "Sone", "Sone", "#1", 1000).apply { profile.addField("Test").value = "true" profile.addField("More Test").value = "also true" } override fun createCommand(core: Core) = GetSoneCommand(core) @Test fun `command does not require write access`() { assertThat(command.requiresWriteAccess, equalTo(false)) } @Test fun `request without any parameters results in fcp exception`() { requestWithoutAnyParameterResultsInFcpException() } @Test fun `request with empty Sone parameter results in fcp exception`() { requestWithEmptySoneParameterResultsInFcpException() } @Test fun `request with invalid Sone parameter results in fcp exception`() { requestWithInvalidSoneParameterResultsInFcpException() } @Test fun `request with valid Sone parameter results in response with Sone information`() { whenever(core.getSone("SoneId")).thenReturn(sone) parameters += "Sone" to "SoneId" val replyParameters = command.execute(parameters).replyParameters assertThat(replyParameters["Message"], equalTo("Sone")) assertThat(replyParameters.parseSone("Sone."), matchesSone(sone)) assertThat(replyParameters["Sone.Followed"], nullValue()) } @Test fun `request with local sone parameter results in followed being true for friend sone`() { whenever(core.getSone("SoneId")).thenReturn(sone) whenever(core.getSone("LocalSone")).thenReturn(localSone) whenever(localSone.id).thenReturn("LocalSone") whenever(localSone.hasFriend("SoneId")).thenReturn(true) parameters += "Sone" to "SoneId" parameters += "LocalSone" to "LocalSone" val replyParameters = command.execute(parameters).replyParameters assertThat(replyParameters["Message"], equalTo("Sone")) assertThat(replyParameters.parseSone("Sone."), matchesSone(sone)) assertThat(replyParameters["Sone.Followed"], equalTo("true")) } @Test fun `request with local sone parameter results in followed being false for non-friend sone`() { whenever(core.getSone("SoneId")).thenReturn(sone) whenever(core.getSone("LocalSone")).thenReturn(localSone) whenever(localSone.id).thenReturn("LocalSone") parameters += "Sone" to "SoneId" parameters += "LocalSone" to "LocalSone" val replyParameters = command.execute(parameters).replyParameters assertThat(replyParameters["Message"], equalTo("Sone")) assertThat(replyParameters.parseSone("Sone."), matchesSone(sone)) assertThat(replyParameters["Sone.Followed"], equalTo("false")) } @Test fun `request with remote sone as local sone parameter results in fcp exception`() { whenever(core.getSone("SoneId")).thenReturn(sone) whenever(core.getSone("RemoteSone")).thenReturn(remoteSone) whenever(localSone.id).thenReturn("RemoteSone") parameters += "Sone" to "SoneId" parameters += "LocalSone" to "RemoteSone" expectedException.expect(FcpException::class.java) command.execute(parameters) } }
gpl-3.0
JackParisi/DroidBox
droidbox/src/main/java/com/github/giacomoparisi/droidbox/validator/rule/core/DroidValidatorRule.kt
1
844
package com.github.giacomoparisi.droidbox.validator.rule.core import android.view.View /** * Created by Giacomo Parisi on 29/01/18. * https://github.com/giacomoParisi */ abstract class DroidValidatorRule<ViewType : View, ValueType>( view: ViewType, protected var value: ValueType, protected var errorMessage: String) { var view: ViewType protected set init { this.view = view } fun validate(): Boolean { val valid = isValid(view) if (valid) { onValidationSucceeded(view) } else { onValidationFailed(view) } return valid } protected abstract fun isValid(view: ViewType): Boolean protected open fun onValidationSucceeded(view: ViewType) {} protected open fun onValidationFailed(view: ViewType) {} }
apache-2.0
jiangkang/KTools
image/src/main/java/com/jiangkang/image/glide/GlideHelper.kt
1
60
package com.jiangkang.image.glide object GlideHelper { }
mit
jiangkang/KTools
hybrid/src/main/java/com/jiangkang/hybrid/web/WebArgs.kt
1
432
package com.jiangkang.hybrid.web /** * Created by jiangkang on 2018/2/27. * description๏ผš */ class WebArgs { var isLoadImgLazy: Boolean = false var isInterceptResources: Boolean = false companion object { val IS_LOAD_IMG_LAZY = "is_load_img_lazy" val IS_INTERCEPT_RESOURCES = "IS_INTERCEPT_RESOURCES" val STR_INJECTED_JS = "str_injected_js" } var jsInjected: String = "" }
mit
andrei-heidelbacher/algostorm
algostorm-core/src/main/kotlin/com/andreihh/algostorm/core/engine/Engine.kt
1
5309
/* * Copyright (c) 2017 Andrei Heidelbacher <[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 com.andreihh.algostorm.core.engine import com.andreihh.algostorm.core.engine.Engine.Status.RELEASED import com.andreihh.algostorm.core.engine.Engine.Status.RUNNING import com.andreihh.algostorm.core.engine.Engine.Status.STOPPED import com.andreihh.algostorm.core.engine.Engine.Status.STOPPING import com.andreihh.algostorm.core.engine.Engine.Status.UNINITIALIZED import java.util.ServiceLoader import kotlin.concurrent.thread import kotlin.system.measureNanoTime /** * An asynchronous engine that runs the game loop on its own private thread. * * All changes to the game state outside of this engine's thread may lead to * inconsistent state and concurrency issues. Thus, the engine state should * remain private to the engine and modified only in the [Handler.onUpdate] and * [Handler.onRelease] methods. * * All the engine methods are thread safe as long as the complete construction * of the engine and initialization of the state happen-before any other method * call. * * @property platform the platform of this engine */ class Engine(private val platform: Platform) { companion object { /** Name of the engine thread. */ const val NAME: String = "ALGOSTORM" } /** The status of an engine. */ enum class Status { UNINITIALIZED, RUNNING, STOPPING, STOPPED, RELEASED } /** The current status of this engine. */ @Volatile var status: Status = UNINITIALIZED private set private val handler = ServiceLoader.load(Handler::class.java).first() private var process: Thread? = null @Throws(Exception::class) private fun run() { handler.onStart() while (status == RUNNING) { val elapsedMillis = measureNanoTime(handler::onUpdate) / 1000000 check(elapsedMillis >= 0) { "Elapsed time can't be negative!" } val updateMillis = handler.millisPerUpdate check(updateMillis > 0) { "Update time must be positive!" } val sleepMillis = updateMillis - elapsedMillis if (sleepMillis > 0) { Thread.sleep(sleepMillis) } } handler.onStop() } fun init(args: Map<String, Any?>) { check(status == UNINITIALIZED) { "Engine already initialized!" } handler.onInit(platform, args) status = STOPPED } /** * Sets the [status] to [Status.RUNNING] and starts the engine thread. * * While this engine is running, at most once every * [Handler.millisPerUpdate] milliseconds, it will invoke the * [Handler.onUpdate] method on the engine thread. * * Time is measured using [measureNanoTime]. If, at any point, the measured * time or [Handler.millisPerUpdate] is negative, the engine thread throws * an [IllegalStateException] and terminates. * * @throws IllegalStateException if the `status` is not `Status.STOPPED` */ fun start() { check(status == STOPPED) { "Engine can't start if not stopped!" } status = RUNNING process = thread(name = NAME) { try { run() } catch (e: Exception) { handler.onError(e) } } } /** * Sets the engine [status] to [Status.STOPPING] and then joins the engine * thread to the current thread, waiting at most [timeoutMillis] * milliseconds. * * If the join succeeds, the `status` will be set to `Status.STOPPED`. * * The timeout must be positive. * * @throws InterruptedException if the current thread is interrupted while * waiting for this engine to stop * @throws IllegalStateException if this engine attempts to stop itself, * because the engine thread can't join itself */ @Throws(InterruptedException::class) fun stop(timeoutMillis: Int) { require(timeoutMillis > 0) { "Timeout must be positive!" } check(status == RUNNING || status == STOPPING) { "Engine can't stop if not running or stopping!" } status = STOPPING check(process != Thread.currentThread()) { "Engine can't stop itself!" } process?.join(timeoutMillis.toLong()) process = null status = STOPPED } /** * Performs clean-up logic and releases this engine's drivers. * * The engine `status` must be `Status.STOPPED`. * * @throws IllegalStateException if this engine is not stopped */ fun release() { check(status == STOPPED) { "Engine can't be released if not stopped!" } handler.onRelease() platform.release() status = RELEASED } }
apache-2.0
lanhuaguizha/Christian
common/src/androidTest/java/com/christian/common/ExampleInstrumentedTest.kt
1
672
package com.christian.common import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.christian.common.test", appContext.packageName) } }
gpl-3.0
nlefler/Glucloser
Glucloser/app/src/main/kotlin/com/nlefler/glucloser/a/dataSource/jsonAdapter/PlaceJsonAdapter.kt
1
1116
package com.nlefler.glucloser.a.dataSource.jsonAdapter import com.nlefler.glucloser.a.models.Place import com.nlefler.glucloser.a.models.PlaceEntity import com.nlefler.glucloser.a.models.json.PlaceJson import com.squareup.moshi.FromJson import com.squareup.moshi.ToJson /** * Created by nathan on 1/31/16. */ public class PlaceJsonAdapter() { companion object { private val LOG_TAG = "PlaceJsonAdapter" } @FromJson fun fromJson(json: PlaceJson): Place { val place = PlaceEntity() place.primaryId = json.primaryId place.name = json.name place.foursquareId = json.foursquareId place.latitude = json.latitude place.longitude = json.longitude place.visitCount = json.visitCount return place } @ToJson fun toJson(place: Place): PlaceJson { return PlaceJson(primaryId = place.primaryId, foursquareId = place.foursquareId, name = place.name, latitude = place.latitude, longitude = place.longitude, visitCount = place.visitCount) } }
gpl-2.0
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/features/decoration/Blocks.kt
2
3840
package com.cout970.magneticraft.features.decoration import com.cout970.magneticraft.misc.CreativeTabMg import com.cout970.magneticraft.misc.RegisterBlocks import com.cout970.magneticraft.misc.resource import com.cout970.magneticraft.misc.vector.createAABBUsing import com.cout970.magneticraft.systems.blocks.* import com.cout970.magneticraft.systems.itemblocks.itemBlockListOf import com.cout970.magneticraft.systems.tilerenderers.PIXEL import net.minecraft.block.Block import net.minecraft.block.material.Material import net.minecraft.block.properties.IProperty import net.minecraft.block.properties.PropertyEnum import net.minecraft.block.state.IBlockState import net.minecraft.item.ItemBlock import net.minecraft.util.IStringSerializable import net.minecraft.util.math.Vec3d /** * Created by cout970 on 2017/06/08. */ @RegisterBlocks object Blocks : IBlockMaker { val PROPERTY_LIMESTONE_KIND = PropertyEnum.create("limestone_kind", LimestoneKind::class.java) val PROPERTY_INVERTED = PropertyEnum.create("inverted", TileInverted::class.java) lateinit var limestone: BlockBase private set lateinit var burnLimestone: BlockBase private set lateinit var tileLimestone: BlockBase private set lateinit var tubeLight: BlockBase private set override fun initBlocks(): List<Pair<Block, ItemBlock>> { val builder = BlockBuilder().apply { material = Material.ROCK creativeTab = CreativeTabMg states = LimestoneKind.values().toList() } limestone = builder.withName("limestone").build() burnLimestone = builder.withName("burnt_limestone").build() tileLimestone = builder.withName("tile_limestone").copy { states = TileInverted.values().toList() }.build() tubeLight = builder.withName("tube_light").copy { states = CommonMethods.Orientation.values().toList() factory = factoryOf(::TileTubeLight) lightEmission = 1f hasCustomModel = true generateDefaultItemBlockModel = false alwaysDropDefault = true customModels = listOf( "model" to resource("models/block/mcx/tube_light.mcx"), "inventory" to resource("models/block/mcx/tube_light.mcx") ) //methods boundingBox = CommonMethods.updateBoundingBoxWithOrientation { listOf(Vec3d(PIXEL * 3, 1.0, 0.0) createAABBUsing Vec3d(1.0 - PIXEL * 3, 1.0 - PIXEL * 4, 1.0)) } onBlockPlaced = CommonMethods::placeWithOrientation pickBlock = CommonMethods::pickDefaultBlock }.build() return itemBlockListOf(limestone, burnLimestone, tileLimestone, tubeLight) } enum class LimestoneKind(override val stateName: String, override val isVisible: Boolean) : IStatesEnum, IStringSerializable { NORMAL("normal", true), BRICK("brick", true), COBBLE("cobble", true); override fun getName() = name.toLowerCase() override val properties: List<IProperty<*>> get() = listOf(PROPERTY_LIMESTONE_KIND) override fun getBlockState(block: Block): IBlockState { return block.defaultState.withProperty(PROPERTY_LIMESTONE_KIND, this) } } enum class TileInverted(override val stateName: String, override val isVisible: Boolean) : IStatesEnum, IStringSerializable { NORMAL("normal", true), INVERTED("inverted", true); override fun getName() = name.toLowerCase() override val properties: List<IProperty<*>> get() = listOf(PROPERTY_INVERTED) override fun getBlockState(block: Block): IBlockState { return block.defaultState.withProperty(PROPERTY_INVERTED, this) } } }
gpl-2.0
rm3l/maoni-github
src/main/kotlin/org/rm3l/maoni/github/android/AndroidBasicAuthorization.kt
2
1637
/* * Copyright (c) 2017 Armel Soro * * 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 org.rm3l.maoni.github.android import khttp.structures.authorization.Authorization import android.util.Base64 data class AndroidBasicAuthorization(val user: String, val password: String) : Authorization { override val header: Pair<String, String> get() { val base64Str = Base64.encode( "${this.user}:${this.password}".toByteArray(), Base64.DEFAULT) .toString(Charsets.UTF_8) return "Authorization" to "Basic $base64Str" } }
mit
cFerg/CloudStorming
ObjectAvoidance/kotlin/src/elite/math/angle/MicroArcSecond.kt
1
1220
package elite.math.angle /** * * @author CFerg (Elite) */ class MicroArcSecond { internal var microSecond: Double = 0.toDouble() /** * */ constructor() { this.microSecond = (1 / 60 / 60 / 1000 / 1000).toDouble() } /** * * @param a */ constructor(a: Degree) { this.microSecond = a.degree / 3600 / 1000 / 1000 } /** * * @param a */ constructor(a: ArcMinute) { this.microSecond = a.minute / 60 / 1000 / 1000 } /** * * @param a */ constructor(a: ArcSecond) { this.microSecond = a.second * 1000 * 1000 } /** * * @param a */ constructor(a: MilliArcSecond) { this.microSecond = a.milliSecond * 1000 } /** * * @return */ fun toDegree(): Degree { return Degree(this) } /** * * @return */ fun toMinute(): ArcMinute { return ArcMinute(this) } /** * * @return */ fun toSecond(): ArcSecond { return ArcSecond(this) } /** * * @return */ fun toMilliSecond(): MilliArcSecond { return MilliArcSecond(this) } }
bsd-3-clause
ReactiveCircus/FlowBinding
flowbinding-android/src/androidTest/java/reactivecircus/flowbinding/android/widget/RatingBarRatingChangeFlowTest.kt
1
2197
package reactivecircus.flowbinding.android.widget import android.widget.RatingBar import androidx.test.filters.LargeTest import androidx.test.internal.runner.junit4.statement.UiThreadStatement.runOnUiThread import com.google.common.truth.Truth.assertThat import org.junit.Test import reactivecircus.flowbinding.android.fixtures.widget.AndroidWidgetFragment import reactivecircus.flowbinding.android.test.R import reactivecircus.flowbinding.testing.FlowRecorder import reactivecircus.flowbinding.testing.launchTest import reactivecircus.flowbinding.testing.recordWith @LargeTest class RatingBarRatingChangeFlowTest { @Test fun ratingBarRatingChanges() { launchTest<AndroidWidgetFragment> { val recorder = FlowRecorder<Float>(testScope) val ratingBar = getViewById<RatingBar>(R.id.ratingBar) ratingBar.ratingChanges().recordWith(recorder) assertThat(recorder.takeValue()) .isEqualTo(0f) recorder.assertNoMoreValues() runOnUiThread { ratingBar.rating = 3f } assertThat(recorder.takeValue()) .isEqualTo(3f) recorder.assertNoMoreValues() runOnUiThread { ratingBar.rating = 5f } assertThat(recorder.takeValue()) .isEqualTo(5f) recorder.assertNoMoreValues() cancelTestScope() runOnUiThread { ratingBar.rating = 0f } recorder.assertNoMoreValues() } } @Test fun ratingBarRatingChanges_skipInitialValue() { launchTest<AndroidWidgetFragment> { val recorder = FlowRecorder<Float>(testScope) val ratingBar = getViewById<RatingBar>(R.id.ratingBar) ratingBar.ratingChanges() .skipInitialValue() .recordWith(recorder) recorder.assertNoMoreValues() runOnUiThread { ratingBar.rating = 3f } assertThat(recorder.takeValue()) .isEqualTo(3f) recorder.assertNoMoreValues() cancelTestScope() runOnUiThread { ratingBar.rating = 5f } recorder.assertNoMoreValues() } } }
apache-2.0
charbgr/CliffHanger
cliffhanger/app/src/test/java/com/github/charbgr/cliffhanger/features/search/arch/SearchRobot.kt
1
679
package com.github.charbgr.cliffhanger.features.search.arch import com.github.charbgr.cliffhanger.feature.search.arch.Presenter import com.github.charbgr.cliffhanger.feature.search.arch.View import io.reactivex.Observable import io.reactivex.subjects.PublishSubject internal class SearchRobot(internal val presenter: Presenter) { private val searchPubSub = PublishSubject.create<CharSequence>() internal val view: View = object : View { override fun searchIntent(): Observable<CharSequence> = searchPubSub.hide() } init { presenter.init(view) presenter.bindIntents() } fun fireSearchIntent(query: CharSequence) { searchPubSub.onNext(query) } }
mit
facebook/litho
codelabs/props/app/src/main/java/com/facebook/litho/codelab/props/RootComponentSpec.kt
1
1325
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.litho.codelab.props import com.facebook.litho.Component import com.facebook.litho.ComponentContext import com.facebook.litho.annotations.LayoutSpec import com.facebook.litho.annotations.OnCreateLayout import com.facebook.litho.annotations.Prop import com.facebook.litho.widget.Text @Suppress("MagicNumber") @LayoutSpec object RootComponentSpec { @OnCreateLayout fun onCreateLayout( c: ComponentContext, @Prop name: String // Creating a prop called 'name' using the '@Prop' annotation ): Component { return Text.create(c) .textSizeSp(20f) .text("Hello $name!") // Using name to set the 'text' prop of the Text component. .build() } }
apache-2.0
ze-pequeno/okhttp
samples/tlssurvey/src/main/kotlin/okhttp3/survey/types/SuiteId.kt
2
842
/* * Copyright (C) 2016 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3.survey.types import okio.ByteString data class SuiteId(val id: ByteString?, val name: String) { fun matches(suiteId: SuiteId): Boolean { return id == suiteId.id || name.substring(4) == suiteId.name.substring(4) } }
apache-2.0
square/leakcanary
leakcanary-object-watcher/src/main/java/leakcanary/Clock.kt
2
732
package leakcanary /** * An interface to abstract the SystemClock.uptimeMillis() Android API in non Android artifacts. * * This is a functional interface with which you can create a [Clock] from a lambda. */ fun interface Clock { /** * On Android VMs, this should return android.os.SystemClock.uptimeMillis(). */ fun uptimeMillis(): Long companion object { /** * Utility function to create a [Clock] from the passed in [block] lambda * instead of using the anonymous `object : Clock` syntax. * * Usage: * * ```kotlin * val clock = Clock { * * } * ``` */ inline operator fun invoke(crossinline block: () -> Long): Clock = Clock { block() } } }
apache-2.0
EyeBody/EyeBody
EyeBody2/app/src/main/java/com/example/android/eyebody/dialog/EnterGalleryDialog.kt
1
2964
package com.example.android.eyebody.dialog import android.app.AlertDialog import android.app.Dialog import android.app.DialogFragment import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.os.Bundle import android.util.Log import android.widget.Button import android.widget.EditText import android.widget.Toast import com.example.android.eyebody.gallery.GalleryActivity import com.example.android.eyebody.R import java.security.MessageDigest /** * Created by YOON on 2017-09-24. */ class EnterGalleryDialog : DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val layoutInflater = activity.layoutInflater val dialogbuilder = AlertDialog.Builder(activity) val view = layoutInflater.inflate(R.layout.dialog_main_enter_gallery_input_pw, null) Log.d("mydbg_enterGallery", "[ enterGallery ๋‹ค์ด์–ผ๋กœ๊ทธ ์ง„์ž… ]") val bt_pwSubmit = view.findViewById<Button>(R.id.Button_enter_gallery_pw_submit) val tv_pwInput = view.findViewById<EditText>(R.id.EditText_enter_gallery_pw_input) val sharedPref: SharedPreferences = activity.getSharedPreferences( getString(R.string.getSharedPreference_initSetting), Context.MODE_PRIVATE) val sharedPref_hashedPW = sharedPref.getString( getString(R.string.sharedPreference_hashedPW), getString(R.string.sharedPreference_default_hashedPW)) // ํ‚ค๋ณด๋“œ-ํ™•์ธ ๋ˆŒ๋ €์„ ๋•Œ ๋ฐ˜์‘ tv_pwInput.setOnEditorActionListener { textView, i, keyEvent -> true Log.d("mydbg_enterGallery", "is ok ????") bt_pwSubmit.callOnClick() } dialogbuilder.setView(view) .setTitle("Input Password") .setMessage("Please type your private password") // button Listener bt_pwSubmit.setOnClickListener { // EditText ์นœ ๋ถ€๋ถ„ MD5 ์•”ํ˜ธํ™” val md5 = MessageDigest.getInstance("MD5") val str_inputPW: String = tv_pwInput.text.toString() val pwByte: ByteArray = str_inputPW.toByteArray(charset("unicode")) md5.update(pwByte) val hashedPW = md5.digest().toString(charset("unicode")) // ๊ณต์œ ๋ณ€์ˆ˜์™€ ์ผ์น˜์—ฌ๋ถ€ ๊ฒ€์ฆ Log.d("mydbg_enterGallery", "prePW : $sharedPref_hashedPW / PW : $hashedPW") if (hashedPW == sharedPref_hashedPW.toString()) { val galleryPage = Intent(activity, GalleryActivity::class.java) startActivity(galleryPage) dismiss() } else { Toast.makeText(activity, "๊ด€๊ณ„์ž ์™ธ ์ถœ์ž…๊ธˆ์ง€~", Toast.LENGTH_LONG).show() } } return dialogbuilder.create() } override fun onStop() { super.onStop() Log.d("mydbg_enterGallery", "๋‹ค์ด์–ผ๋กœ๊ทธ๊ฐ€ ๊ฐ€๋ ค์ง ๋˜๋Š” ์ข…๋ฃŒ๋จ") } }
mit
google/horologist
media-ui/src/main/java/com/google/android/horologist/media/ui/state/PlayerViewModel.kt
1
1701
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:OptIn(ExperimentalHorologistMediaApi::class) package com.google.android.horologist.media.ui.state import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.google.android.horologist.media.ExperimentalHorologistMediaApi import com.google.android.horologist.media.repository.PlayerRepository import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.stateIn @ExperimentalHorologistMediaUiApi public open class PlayerViewModel( playerRepository: PlayerRepository ) : ViewModel() { private val producer = PlayerUiStateProducer(playerRepository) public val playerUiState: StateFlow<PlayerUiState> = producer.playerUiStateFlow.stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(stopTimeoutMillis = 5_000), initialValue = PlayerUiState.NotConnected ) public val playerUiController: PlayerUiController = PlayerUiController(playerRepository) }
apache-2.0
android/trackr
app-compose/src/androidTest/java/com/example/android/trackr/compose/ui/TagGroupTest.kt
1
2191
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.trackr.compose.ui import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithText import androidx.test.ext.junit.runners.AndroidJUnit4 import com.example.android.trackr.data.Tag import com.example.android.trackr.data.TagColor import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class TagGroupTest { @get:Rule val rule = createComposeRule() @Suppress("SameParameterValue") private fun createTags(n: Int): List<Tag> { return (1..n).map { i -> Tag( id = i.toLong(), label = "tag $i", color = TagColor.YELLOW ) } } @Test fun all() { rule.setContent { TrackrTheme { TagGroup( tags = createTags(10) ) } } for (i in 1..10) { rule.onNodeWithText("tag $i").assertIsDisplayed() } } @Test fun limit() { rule.setContent { TrackrTheme { TagGroup( tags = createTags(10), max = 6 ) } } for (i in 1..6) { rule.onNodeWithText("tag $i").assertIsDisplayed() } for (i in 7..10) { rule.onNodeWithText("tag $i").assertDoesNotExist() } rule.onNodeWithText("+4").assertIsDisplayed() } }
apache-2.0
kory33/SignVote
src/main/kotlin/com/github/kory33/signvote/command/subcommand/VoteCommandExecutor.kt
1
3977
package com.github.kory33.signvote.command.subcommand import com.github.kory33.signvote.configurable.JSONConfiguration import com.github.kory33.signvote.constants.MessageConfigNodes import com.github.kory33.signvote.constants.PermissionNodes import com.github.kory33.signvote.core.SignVote import com.github.kory33.signvote.exception.InvalidScoreVotedException import com.github.kory33.signvote.exception.ScoreCountLimitReachedException import com.github.kory33.signvote.exception.VotePointAlreadyVotedException import com.github.kory33.signvote.exception.VoteSessionClosedException import com.github.kory33.signvote.manager.VoteSessionManager import com.github.kory33.signvote.vote.VoteScore import org.bukkit.command.Command import org.bukkit.command.CommandSender import org.bukkit.entity.Player import java.util.* /** * Executor class of "vote" sub-command * @author Kory */ class VoteCommandExecutor(plugin: SignVote) : SubCommandExecutor { private val messageConfiguration: JSONConfiguration = plugin.messagesConfiguration!! private val voteSessionManager: VoteSessionManager = plugin.voteSessionManager!! override val helpString: String get() = this.messageConfiguration.getString(MessageConfigNodes.VOTE_COMMAND_HELP) override fun onCommand(sender: CommandSender, command: Command, args: ArrayList<String>): Boolean { if (sender !is Player) { sender.sendMessage(this.messageConfiguration.getString(MessageConfigNodes.COMMAND_ONLY_FOR_PLAYERS)) return true } if (!sender.hasPermission(PermissionNodes.VOTE)) { sender.sendMessage(this.messageConfiguration.getString(MessageConfigNodes.MISSING_PERMS)) return true } if (args.size != 3) { return false } val player = sender val sessionName = args.removeAt(0) val votePointName = args.removeAt(0) val voteScoreString = args.removeAt(0) val session = this.voteSessionManager.getVoteSession(sessionName) if (session == null) { player.sendMessage(this.messageConfiguration.getString(MessageConfigNodes.SESSION_DOES_NOT_EXIST)) return true } val votePoint = session.getVotePoint(votePointName) if (votePoint == null) { player.sendMessage(this.messageConfiguration.getString(MessageConfigNodes.VOTEPOINT_DOES_NOT_EXIST)) return true } val voteScore: VoteScore try { voteScore = VoteScore(Integer.parseInt(voteScoreString)) } catch (exception: Exception) { player.sendMessage(this.messageConfiguration.getString(MessageConfigNodes.INVALID_VOTE_SCORE)) return true } // if the voter does not have vote score reserved val reservedVotes = session.getReservedVoteCounts(player)[voteScore] if (reservedVotes == null || reservedVotes.isZero) { player.sendMessage(this.messageConfiguration.getString(MessageConfigNodes.INVALID_VOTE_SCORE)) return true } try { session.vote(player, votePoint, voteScore) player.sendMessage(this.messageConfiguration.getString(MessageConfigNodes.VOTED)) } catch (exception: ScoreCountLimitReachedException) { player.sendMessage(this.messageConfiguration.getString(MessageConfigNodes.REACHED_VOTE_SCORE_LIMIT)) } catch (exception: VotePointAlreadyVotedException) { player.sendMessage(this.messageConfiguration.getString(MessageConfigNodes.VOTEPOINT_ALREADY_VOTED)) } catch (exception: InvalidScoreVotedException) { player.sendMessage(this.messageConfiguration.getString(MessageConfigNodes.INVALID_VOTE_SCORE)) } catch (exception: VoteSessionClosedException) { player.sendMessage(this.messageConfiguration.getString(MessageConfigNodes.VOTE_SESSION_CLOSED)) } return true } }
gpl-3.0
AerisG222/maw_photos_android
MaWPhotos/src/main/java/us/mikeandwan/photos/domain/models/SearchRequest.kt
1
124
package us.mikeandwan.photos.domain.models data class SearchRequest( val query: String, val source: SearchSource )
mit
icarumbas/bagel
core/src/ru/icarumbas/bagel/view/renderer/systems/AnimationSystem.kt
1
2471
package ru.icarumbas.bagel.view.renderer.systems import com.badlogic.ashley.core.Entity import com.badlogic.ashley.core.Family import com.badlogic.ashley.systems.IteratingSystem import com.badlogic.gdx.math.MathUtils import ru.icarumbas.bagel.engine.components.other.RoomIdComponent import ru.icarumbas.bagel.engine.components.other.StateComponent import ru.icarumbas.bagel.engine.components.physics.StaticComponent import ru.icarumbas.bagel.engine.entities.EntityState import ru.icarumbas.bagel.engine.world.RoomWorld import ru.icarumbas.bagel.utils.* import ru.icarumbas.bagel.view.renderer.components.AlwaysRenderingMarkerComponent import ru.icarumbas.bagel.view.renderer.components.AnimationComponent class AnimationSystem( private val rm: RoomWorld ) : IteratingSystem(Family.all(AnimationComponent::class.java, StateComponent::class.java) .one(AlwaysRenderingMarkerComponent::class.java, RoomIdComponent::class.java, StaticComponent::class.java).get()) { private fun flip(e: Entity) { texture[e].tex?.let{ if (e.rotatedRight() && it.isFlipX) { it.flip(true, false) } else if (!e.rotatedRight() && !it.isFlipX) { it.flip(true, false) } } } override fun processEntity(e: Entity, deltaTime: Float) { if (e.inView(rm)) { state[e].stateTime += deltaTime if (state[e].currentState == EntityState.ATTACKING) { val frame = if (e.rotatedRight()){ body[weapon[e].entityRight].body.angleInDegrees().div( MathUtils.PI / animation[e].animations[EntityState.ATTACKING]!!.keyFrames.size).toInt() * -1 } else { body[weapon[e].entityLeft].body.angleInDegrees().div( MathUtils.PI / animation[e].animations[EntityState.ATTACKING]!!.keyFrames.size).toInt() } texture[e].tex = animation[e].animations[state[e].currentState]!!.keyFrames.get(frame) } else if (animation[e].animations.containsKey(state[e].currentState)) { texture[e].tex = animation[e]. animations[state[e]. currentState]!!. getKeyFrame(state[e].stateTime) } flip(e) } } }
apache-2.0
AerisG222/maw_photos_android
MaWPhotos/src/main/java/us/mikeandwan/photos/domain/PhotoCategoryRepository.kt
1
4195
package us.mikeandwan.photos.domain import androidx.room.withTransaction import kotlinx.coroutines.flow.* import us.mikeandwan.photos.api.ApiResult import us.mikeandwan.photos.api.PhotoApiClient import us.mikeandwan.photos.database.* import us.mikeandwan.photos.domain.models.ExternalCallStatus import us.mikeandwan.photos.domain.models.Photo import javax.inject.Inject class PhotoCategoryRepository @Inject constructor( private val api: PhotoApiClient, private val db: MawDatabase, private val pcDao: PhotoCategoryDao, private val idDao: ActiveIdDao, private val apiErrorHandler: ApiErrorHandler ) { companion object { const val ERR_MSG_LOAD_CATEGORIES = "Unable to load categories at this time. Please try again later." const val ERR_MSG_LOAD_PHOTOS = "Unable to load photos. Please try again later." } private var _lastCategoryId = -1 private var _lastCategoryPhotos = emptyList<Photo>() fun getYears() = flow { val data = pcDao.getYears() if(data.first().isEmpty()) { emit(emptyList()) loadCategories(-1, ERR_MSG_LOAD_CATEGORIES) .collect { } } emitAll(data) } fun getNewCategories() = flow { val category = pcDao .getMostRecentCategory() .first() // do not show error messages as snackbar for this method as it is called only from // the update categories worker - which will create an error notification on failure val categories = if (category == null) { loadCategories(-1, null) } else { loadCategories(category.id, null) } emitAll(categories) } fun getCategories() = pcDao .getCategoriesForActiveYear() .map { dbList -> dbList.map { dbCat -> dbCat.toDomainPhotoCategory() } } fun getCategory() = pcDao .getActiveCategory() .filter { it != null } .map { cat -> cat!!.toDomainPhotoCategory() } fun getCategory(id: Int) = pcDao .getCategory(id) .filter { it != null } .map { cat -> cat!!.toDomainPhotoCategory() } fun getPhotos(categoryId: Int) = flow { if(categoryId == _lastCategoryId) { emit(ExternalCallStatus.Success(_lastCategoryPhotos)) } else { emit(ExternalCallStatus.Loading) when(val result = api.getPhotos(categoryId)) { is ApiResult.Error -> emit(apiErrorHandler.handleError(result, ERR_MSG_LOAD_PHOTOS)) is ApiResult.Empty -> emit(apiErrorHandler.handleEmpty(result, ERR_MSG_LOAD_PHOTOS)) is ApiResult.Success -> { _lastCategoryPhotos = result.result.items.map { it.toDomainPhoto() } if (_lastCategoryPhotos.isNotEmpty()) { _lastCategoryId = categoryId } emit(ExternalCallStatus.Success(_lastCategoryPhotos)) } } } } private fun loadCategories(mostRecentCategory: Int, errorMessage: String?) = flow { emit(ExternalCallStatus.Loading) when(val result = api.getRecentCategories(mostRecentCategory)) { is ApiResult.Error -> emit(apiErrorHandler.handleError(result, errorMessage)) is ApiResult.Empty -> emit(apiErrorHandler.handleEmpty(result, errorMessage)) is ApiResult.Success -> { val categories = result.result.items if(categories.isEmpty()) { emit(ExternalCallStatus.Success(emptyList())) } else { val dbCategories = categories.map { apiCat -> apiCat.toDatabasePhotoCategory() } val maxYear = dbCategories.maxOf { it.year } db.withTransaction { pcDao.upsert(*dbCategories.toTypedArray()) idDao.setActiveId(ActiveId(ActiveIdType.PhotoCategoryYear, maxYear)) } emit(ExternalCallStatus.Success(dbCategories.map { it.toDomainPhotoCategory() })) } } } } }
mit
reime005/splintersweets
core/src/de/reimerm/splintersweets/abstract/AbstractStretchStage.kt
1
1263
/* * Copyright (c) 2017. Marius Reimer * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.reimerm.splintersweets.abstract import com.badlogic.gdx.graphics.OrthographicCamera import com.badlogic.gdx.scenes.scene2d.Stage import com.badlogic.gdx.utils.Scaling import com.badlogic.gdx.utils.viewport.ScalingViewport import de.reimerm.splintersweets.utils.GameSettings /** * Created by Marius Reimer on 21-Jul-16. */ open class AbstractStretchStage : Stage { constructor() : super(ScalingViewport(Scaling.stretch, GameSettings.WIDTH, GameSettings.HEIGHT, OrthographicCamera(GameSettings.WIDTH, GameSettings.HEIGHT))) { camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0f) camera.update() } }
apache-2.0
Shynixn/BlockBall
blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/business/service/RightclickManageServiceImpl.kt
1
3189
@file:Suppress("UNCHECKED_CAST") package com.github.shynixn.blockball.core.logic.business.service import com.github.shynixn.blockball.api.business.enumeration.ChatColor import com.github.shynixn.blockball.api.business.service.ProxyService import com.github.shynixn.blockball.api.business.service.RightclickManageService import com.google.inject.Inject /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ class RightclickManageServiceImpl @Inject constructor(private val proxyService: ProxyService) : RightclickManageService { private val rightClickListener = HashMap<Any, (Any) -> Unit>() /** * Gets called one time when a location gets rightlicked by [player]. */ override fun <P, L> watchForNextRightClickSign(player: P, f: (L) -> Unit) { require (player is Any) { throw IllegalArgumentException("Player has to be a BukkitPlayer!") } val func = f as (Any) -> Unit rightClickListener[player] = func } /** * Executes the watcher for the given [player] if he has registered one. */ override fun <P, L> executeWatchers(player: P, location: L): Boolean { require (player is Any) { throw IllegalArgumentException("Player has to be a BukkitPlayer!") } if (!rightClickListener.containsKey(player)) { return false } if (proxyService.setSignLines(location, listOf(ChatColor.BOLD.toString() + "BlockBall", ChatColor.GREEN.toString() + "Loading..."))) { rightClickListener[player]!!.invoke(location as Any) rightClickListener.remove(player) } return true } /** * Clears all resources this [player] has allocated from this service. */ override fun <P> cleanResources(player: P) { require (player is Any) { throw IllegalArgumentException("Player has to be a BukkitPlayer!") } if (rightClickListener.containsKey(player)) { rightClickListener.remove(player) } } }
apache-2.0
mrkirby153/KirBot
src/main/kotlin/me/mrkirby153/KirBot/command/control/CommandGuildAccess.kt
1
4179
package me.mrkirby153.KirBot.command.control import me.mrkirby153.KirBot.Bot import me.mrkirby153.KirBot.command.CommandException import me.mrkirby153.KirBot.command.annotations.AdminCommand import me.mrkirby153.KirBot.command.annotations.Command import me.mrkirby153.KirBot.command.args.CommandContext import me.mrkirby153.KirBot.listener.WaitUtils import me.mrkirby153.KirBot.module.ModuleManager import me.mrkirby153.KirBot.modules.AccessModule import me.mrkirby153.KirBot.utils.Context import net.dv8tion.jda.api.sharding.ShardManager import javax.inject.Inject class CommandGuildAccess @Inject constructor(private val accessModule: AccessModule, private val shardManager: ShardManager){ @Command(name = "add", arguments = ["<list:string>", "<guild:snowflake>"], parent = "guild-access") @AdminCommand fun add(context: Context, cmdContext: CommandContext) { val guild = cmdContext.getNotNull<String>("guild") val list = try { AccessModule.WhitelistMode.valueOf(cmdContext.getNotNull<String>("list").toUpperCase()) } catch (e: IllegalArgumentException) { throw CommandException( "Not a valid access list. Valid lists are ${AccessModule.WhitelistMode.values().joinToString( ", ")}") } accessModule.addToList(guild, list) context.send().success("Added `$guild` to the $list list").queue() if (list == AccessModule.WhitelistMode.BLACKLIST) { shardManager.getGuildById(guild)?.leave()?.queue() } } @Command(name = "remove", arguments = ["<list:string>", "<guild:snowflake>"], parent = "guild-access") @AdminCommand fun remove(context: Context, cmdContext: CommandContext) { val guild = cmdContext.getNotNull<String>("guild") val list = try { AccessModule.WhitelistMode.valueOf(cmdContext.getNotNull<String>("list").toUpperCase()) } catch (e: IllegalArgumentException) { throw CommandException( "Not a valid access list. Valid lists are ${AccessModule.WhitelistMode.values().joinToString( ", ")}") } accessModule.removeFromList(guild, list) context.send().success("Removed `$guild` from the $list list").queue() } @Command(name = "list", arguments = ["<list:string>"], parent = "guild-access") @AdminCommand fun list(context: Context, cmdContext: CommandContext) { val list = try { AccessModule.WhitelistMode.valueOf(cmdContext.getNotNull<String>("list").toUpperCase()) } catch (e: IllegalArgumentException) { throw CommandException( "Not a valid access list. Valid lists are ${AccessModule.WhitelistMode.values().joinToString( ", ")}") } val guilds = accessModule.getList(list).map { it -> if (shardManager.getGuildById(it) != null) { val guild = shardManager.getGuildById(it)!! "${guild.name} (`${guild.id}`)" } else { it } } var msg = "List: $list\n" guilds.forEach { val toAdd = " - $it\n" if (msg.length + toAdd.length >= 1990) { context.channel.sendMessage("$msg").queue() msg = "" } else { msg += toAdd } } if (msg != "") context.channel.sendMessage(msg).queue() } @Command(name = "importWhitelist", parent = "guild-access") @AdminCommand fun import(context: Context, cmdContext: CommandContext) { context.channel.sendMessage( "Are you sure you want to import all guilds into the whitelist?").queue { msg -> WaitUtils.confirmYesNo(msg, context.author, { shardManager.guilds.forEach { g -> accessModule.addToList(g.id, AccessModule.WhitelistMode.WHITELIST) } msg.editMessage("Done! Added ${shardManager.guilds.size} to the list").queue() }) } } }
mit