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 |
---|---|---|---|---|---|
helloworld1/FreeOTPPlus | app/src/androidTest/java/org/fedorahosted/freeotp/uitest/MainActivityTest.kt | 1 | 5963 | package org.fedorahosted.freeotp.uitest
import androidx.recyclerview.widget.RecyclerView
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.Espresso.openActionBarOverflowOrOptionsMenu
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.closeSoftKeyboard
import androidx.test.espresso.action.ViewActions.replaceText
import androidx.test.espresso.action.ViewActions.scrollTo
import androidx.test.espresso.action.ViewActions.typeText
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.contrib.RecyclerViewActions.actionOnItemAtPosition
import androidx.test.espresso.matcher.ViewMatchers.hasDescendant
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.rules.activityScenarioRule
import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner
import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation
import kotlinx.coroutines.runBlocking
import org.fedorahosted.freeotp.R
import org.fedorahosted.freeotp.ui.MainActivity
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4ClassRunner::class)
class MainActivityTest {
@get:Rule
var activityRule = activityScenarioRule<MainActivity>()
@Test
fun testListing() {
populateTestData()
onView(withId(R.id.token_list))
.perform(actionOnItemAtPosition<RecyclerView.ViewHolder>(0, scrollTo()))
.check(matches(hasDescendant(withText("github.com"))))
.check(matches(hasDescendant(withText("github account 1"))))
onView(withId(R.id.token_list))
.perform(actionOnItemAtPosition<RecyclerView.ViewHolder>(1, scrollTo()))
.check(matches(hasDescendant(withText("microsoft.com"))))
.check(matches(hasDescendant(withText("microsoft account 1"))))
}
@Test
fun testInsertToken() {
openActionBarOverflowOrOptionsMenu(getInstrumentation().targetContext);
onView(withText(R.string.add_token))
.perform(click())
onView(withId(R.id.issuer))
.perform(typeText("issuer1"), closeSoftKeyboard())
onView(withId(R.id.label))
.perform(typeText("account1"), closeSoftKeyboard())
onView(withId(R.id.secret))
.perform(typeText("abcd5432"))
onView(withId(R.id.add))
.perform(click())
onView(withId(R.id.token_list))
.perform(actionOnItemAtPosition<RecyclerView.ViewHolder>(0, scrollTo()))
.check(matches(hasDescendant(withText("issuer1"))))
.check(matches(hasDescendant(withText("account1"))))
}
@Test
fun testEditToken() {
populateTestData()
onView(withId(R.id.token_list))
.perform(actionOnItemAtPosition<RecyclerView.ViewHolder>(0,
RecyclerViewAction.clickChildViewWithId(R.id.menu)))
onView(withText(R.string.edit))
.perform(click())
onView(withId(R.id.issuer))
.perform(replaceText("new issuer"))
onView(withId(R.id.label))
.perform(replaceText("new account"))
onView(withId(R.id.save))
.perform(click())
onView(withId(R.id.token_list))
.perform(actionOnItemAtPosition<RecyclerView.ViewHolder>(0, scrollTo()))
.check(matches(hasDescendant(withText("new issuer"))))
.check(matches(hasDescendant(withText("new account"))))
}
@Test
fun testDeleteToken() {
populateTestData()
onView(withId(R.id.token_list))
.check(RecyclerViewAssertion.childrenCount(2))
onView(withId(R.id.token_list))
.perform(actionOnItemAtPosition<RecyclerView.ViewHolder>(0,
RecyclerViewAction.clickChildViewWithId(R.id.menu)))
onView(withText(R.string.delete))
.perform(click())
onView(withId(R.id.delete))
.perform(click())
onView(withId(R.id.token_list))
.check(RecyclerViewAssertion.childrenCount(1))
onView(withId(R.id.token_list))
.perform(actionOnItemAtPosition<RecyclerView.ViewHolder>(0, scrollTo()))
.check(matches(hasDescendant(withText("microsoft.com"))))
.check(matches(hasDescendant(withText("microsoft account 1"))))
}
@Test
fun testTokenClickRevealHotp() {
populateTestData()
onView(withId(R.id.token_list))
.perform(actionOnItemAtPosition<RecyclerView.ViewHolder>(0, click()))
onView(withId(R.id.token_list))
.perform(actionOnItemAtPosition<RecyclerView.ViewHolder>(0, scrollTo()))
.check(matches(hasDescendant(withText("github.com"))))
.check(matches(hasDescendant(withText("github account 1"))))
.check(matches(hasDescendant(withText("248759"))))
}
@Test
fun testSearchToken() {
populateTestData()
onView(withId(R.id.search_view))
.perform(click())
onView(withId(R.id.search_view))
.perform(SearchViewAction.typeSearchViewText("Microsoft"))
onView(withId(R.id.token_list))
.perform(actionOnItemAtPosition<RecyclerView.ViewHolder>(0, scrollTo()))
.check(matches(hasDescendant(withText("microsoft.com"))))
.check(matches(hasDescendant(withText("microsoft account 1"))))
onView(withId(R.id.token_list))
.perform(actionOnItemAtPosition<RecyclerView.ViewHolder>(0, click()))
}
private fun populateTestData() {
activityRule.scenario.onActivity { activity ->
runBlocking {
activity.otpTokenDatabase.otpTokenDao().insert(TestData.OTP_HOTP_TOKEN_1)
activity.otpTokenDatabase.otpTokenDao().insert(TestData.OTP_TOTP_TOKEN_2)
}
}
}
} | apache-2.0 |
horie1024/realm-java | examples/kotlinExample/src/main/kotlin/io/realm/examples/kotlin/model/Dog.kt | 1 | 782 | /*
* Copyright 2015 Realm 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 io.realm.examples.kotlin.model
import io.realm.RealmObject
import io.realm.annotations.RealmClass
public open class Dog : RealmObject() {
public open var name: String? = null
}
| apache-2.0 |
eyneill777/SpacePirates | core/src/rustyengine/GeneralSettings.kt | 1 | 1680 | package rustyengine;
import com.badlogic.gdx.Preferences;
object GeneralSettings {
private const val APPID = "rustyice"
var preferences: Preferences? = null
set(value) {
field = value
if(value != null) {
width = value.getInteger("${APPID}.width", width)
height = value.getInteger("${APPID}.height", height)
fullscreen = value.getBoolean("${APPID}.fullscreen", fullscreen)
soundVolume = value.getFloat("${APPID}.soundVolume", soundVolume)
musicVolume = value.getFloat("${APPID}.musicVolume", musicVolume)
vsync = value.getBoolean("${APPID}.vsync", vsync)
}
}
var width: Int = 800
set(value) {
field = value
preferences?.putInteger("${APPID}.width", value)
}
var height: Int = 640
set(value) {
field = value
preferences?.putInteger("${APPID}.width", value)
}
var soundVolume: Float = 1f
set(value) {
field = value
preferences?.putFloat("${APPID}.soundVolume", value)
}
var musicVolume: Float = 1f
set(value) {
field = value
preferences?.putFloat("${APPID}.musicVolume", value)
}
var vsync: Boolean = true
set(value) {
field = value
preferences?.putBoolean("${APPID}.vsync", value)
}
var fullscreen: Boolean = false
set(value) {
field = value
preferences?.putBoolean("${APPID}.fullscreen", value)
}
fun save(){
preferences?.flush()
}
}
| mit |
ktorio/ktor | ktor-network/nix/src/io/ktor/network/selector/WorkerSelectorManager.kt | 1 | 1293 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.network.selector
import kotlinx.coroutines.*
import kotlinx.coroutines.CancellationException
import kotlin.coroutines.*
@OptIn(ExperimentalCoroutinesApi::class)
internal class WorkerSelectorManager : SelectorManager {
private val selectorContext = newSingleThreadContext("WorkerSelectorManager")
private val job = Job()
override val coroutineContext: CoroutineContext = selectorContext + job
private val selector = SelectorHelper()
init {
selector.start(this)
}
override fun notifyClosed(selectable: Selectable) {
selector.notifyClosed(selectable.descriptor)
}
override suspend fun select(
selectable: Selectable,
interest: SelectInterest
) {
return suspendCancellableCoroutine { continuation ->
val selectorState = EventInfo(selectable.descriptor, interest, continuation)
if (!selector.interest(selectorState)) {
continuation.resumeWithException(CancellationException("Selector closed."))
}
}
}
override fun close() {
selector.requestTermination()
selectorContext.close()
}
}
| apache-2.0 |
onnerby/musikcube | src/musikdroid/app/src/main/java/io/casey/musikcube/remote/service/websocket/model/PlayQueueType.kt | 2 | 153 | package io.casey.musikcube.remote.service.websocket.model
enum class PlayQueueType(val rawValue: String) {
Live("live"),
Snapshot("snapshot");
} | bsd-3-clause |
armcha/Ribble | app/src/main/kotlin/io/armcha/ribble/presentation/screen/auth/AuthContract.kt | 1 | 494 | package io.armcha.ribble.presentation.screen.auth
import android.content.Intent
import android.net.Uri
import io.armcha.ribble.presentation.base_mvp.api.ApiContract
/**
* Created by Chatikyan on 10.08.2017.
*/
interface AuthContract {
interface View : ApiContract.View {
fun startOAuthIntent(uri: Uri)
fun openHomeActivity()
}
interface Presenter : ApiContract.Presenter<View> {
fun makeLogin()
fun checkLogin(resultIntent: Intent?)
}
} | apache-2.0 |
Mini-Stren/MultiThemer | multithemer/src/main/java/com/ministren/multithemer/MultiThemeActivity.kt | 1 | 2259 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.ministren.multithemer
import android.content.SharedPreferences
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
/**
* * Activity use {@link MultiThemer} to automatically
* apply app's active theme and restart itself after theme change
* <p>
*
* Created by Mini-Stren on 28.08.2017.
*/
open class MultiThemeActivity : AppCompatActivity(), SharedPreferences.OnSharedPreferenceChangeListener {
private lateinit var mThemeTag: String
override fun onCreate(savedInstanceState: Bundle?) {
MultiThemer.applyThemeTo(this)
mThemeTag = MultiThemer.getSavedThemeTag()
super.onCreate(savedInstanceState)
}
override fun onPause() {
super.onPause()
MultiThemer.getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this)
}
override fun onResume() {
super.onResume()
MultiThemer.getSharedPreferences().registerOnSharedPreferenceChangeListener(this)
val tag = MultiThemer.getSavedThemeTag()
if (mThemeTag != tag) restartActivity()
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
if (key == MultiThemer.PREFERENCE_KEY) restartActivity()
}
private fun restartActivity() {
if (BuildConfig.DEBUG) {
Log.d(MultiThemer.LOG_TAG, "restarting activity '$this'")
}
recreate()
}
}
| apache-2.0 |
code-disaster/lwjgl3 | modules/lwjgl/opengles/src/templates/kotlin/opengles/templates/AMD_program_binary_Z400.kt | 4 | 1614 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengles.templates
import org.lwjgl.generator.*
import opengles.*
val AMD_program_binary_Z400 = "AMDProgramBinaryZ400".nativeClassGLES("AMD_program_binary_Z400", postfix = AMD) {
documentation =
"""
Native bindings to the $registryLink extension.
AMD provides an offline shader compiler as part of its suite of SDK tools for AMD's Z400 family of embedded graphics accelerator IP. This extension
makes available a program binary format, Z400_BINARY_AMD.
The offline shader compiler accepts a pair of OpenGL Shading Language (GLSL) source shaders: one vertex shader and one fragment shader. It outputs a
compiled, optimized, and pre-linked program binary which can then be loaded into a program objects via the ProgramBinaryOES command.
Applications are recommended to use the OES_get_program_binary extension's program binary retrieval mechanism for install-time shader compilation where
applicable. That cross-vendor extension provides the performance benefits of loading pre-compiled program binaries, while providing the portability of
deploying GLSL source shaders with the application rather than vendor- specific binaries. The details of this extension are obviated by the use of that
extension.
Requires ${GLES20.core} and ${OES_get_program_binary.link}.
"""
IntConstant(
"Accepted by the {@code binaryFormat} parameter of ProgramBinaryOES.",
"Z400_BINARY_AMD"..0x8740
)
} | bsd-3-clause |
colriot/talk-kotlin-vs-java | src/singleton/ViktorTsoi.kt | 1 | 523 | package singleton
/**
* @author Sergey Chistyakov <[email protected]>
* 21.06.2017
*/
object ViktorTsoi {
fun sing() {
/*
Красная-красная кровь -
Через час уже просто земля,
Через два на ней цветы и трава,
Через три она снова жива.
И согрета лучами звезды
По имени Солнце.
*/
}
}
fun main(args: Array<String>) {
ViktorTsoi.sing()
}
| apache-2.0 |
neva-dev/javarel-framework | communication/rest/src/main/kotlin/com/neva/javarel/communication/rest/impl/OsgiInjectionResolver.kt | 1 | 802 | package com.neva.javarel.communication.rest.impl
import com.neva.javarel.foundation.api.injection.Osgi
import com.neva.javarel.foundation.api.osgi.OsgiUtils
import org.glassfish.hk2.api.*
import javax.inject.Singleton
@Singleton
class OsgiInjectionResolver : InjectionResolver<Osgi> {
override fun resolve(injectee: Injectee, root: ServiceHandle<*>?): Any? {
val service = OsgiUtils(javaClass).serviceOf<Any>(injectee.requiredType.typeName)
if (service == null && !injectee.isOptional) {
throw MultiException(UnsatisfiedDependencyException(injectee))
}
return service
}
override fun isConstructorParameterIndicator(): Boolean {
return true
}
override fun isMethodParameterIndicator(): Boolean {
return false
}
} | apache-2.0 |
mdanielwork/intellij-community | uast/uast-java/src/org/jetbrains/uast/java/expressions/JavaUCompositeQualifiedExpression.kt | 1 | 1574 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.java
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.ResolveResult
import org.jetbrains.uast.*
class JavaUCompositeQualifiedExpression(
override val psi: PsiElement,
givenParent: UElement?
) : JavaAbstractUExpression(givenParent), UQualifiedReferenceExpression, UMultiResolvable {
internal lateinit var receiverInitializer: () -> UExpression
override val receiver: UExpression by lazy { receiverInitializer() }
override lateinit var selector: UExpression
internal set
override val resolvedName: String?
get() = (resolve() as? PsiNamedElement)?.name
override fun resolve(): PsiElement? = (selector as? UResolvable)?.resolve()
override fun multiResolve(): Iterable<ResolveResult> =
(selector as? UMultiResolvable)?.multiResolve() ?: emptyList()
override val accessType: UastQualifiedExpressionAccessType
get() = UastQualifiedExpressionAccessType.SIMPLE
} | apache-2.0 |
sallySalem/KotlinMvpEspresso | app/src/main/java/com/example/kotlinmvpespresso/ui/details/DetailsView.kt | 1 | 530 | package com.example.kotlinmvpespresso.ui.details
import com.example.kotlinmvpespresso.data.model.OwnerModel
import com.example.kotlinmvpespresso.data.model.RepositoryModel
import com.example.kotlinmvpespresso.ui.base.BaseView
/**
* Created by sally on 7/7/17.
*/
interface DetailsView : BaseView {
fun initRepositoryDetailsView(repositoryModel: RepositoryModel)
fun initOwnerView(ownerInfo: OwnerModel)
fun hideProgressbar()
fun hideEmptyDataView()
fun showEmptyDataView()
fun showErrorMessage()
} | mit |
aerisweather/AerisAndroidSDK | Kotlin/AerisSdkDemo/app/src/main/java/com/example/demoaerisproject/BaseApplication.kt | 1 | 2604 | package com.example.demoaerisproject
import android.app.Application
import android.app.job.JobInfo
import android.app.job.JobScheduler
import android.content.ComponentName
import android.content.Context
import com.aerisweather.aeris.communication.AerisEngine
import com.aerisweather.aeris.logging.Logger
import com.aerisweather.aeris.maps.AerisMapsEngine
import com.example.demoaerisproject.data.preferenceStore.PrefStoreRepository
import com.example.demoaerisproject.service.NotificationJobService
import dagger.hilt.android.HiltAndroidApp
import javax.inject.Inject
@HiltAndroidApp
class BaseApplication : Application() {
@Inject
lateinit var prefStore: PrefStoreRepository
override fun onCreate() {
super.onCreate()
// setting up secret key and client id for oauth to aeris
AerisEngine.initWithKeys(
this.getString(R.string.aerisapi_client_id),
this.getString(R.string.aerisapi_client_secret),
this
)
enableNotificationService(baseContext)
/*
* can override default point parameters programmatically used on the
* map. dt:-1 -> sorts to closest time| -4hours -> 4 hours ago. Limit is
* a required parameter.Can also be done through the xml values in the
* aeris_default_values.xml
*/
AerisMapsEngine.getInstance(this).defaultPointParameters
.setLightningParameters("dt:-1", 500, null, null)
}
companion object {
private const val NOTIFICATION_JOB_ID = 2001
const val PRIMARY_FOREGROUND_NOTIF_SERVICE_ID = 1001
private const val ONE_MIN = 60 * 1000
private val TAG = BaseApplication::class.java.simpleName
fun enableNotificationService(context: Context) {
Logger.d(TAG, "enableNotificationService() - using JobScheduler")
val notificationComponent = ComponentName(
context,
NotificationJobService::class.java
)
val notificationBuilder = JobInfo.Builder(
NOTIFICATION_JOB_ID,
notificationComponent
) // schedule it to run any time between 15-20 minutes
.setMinimumLatency((ONE_MIN * 1).toLong())
.setOverrideDeadline((ONE_MIN * 2).toLong())
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPersisted(true)
val notificationJobScheduler =
context.getSystemService(JOB_SCHEDULER_SERVICE) as JobScheduler
notificationJobScheduler.schedule(notificationBuilder.build())
}
}
} | mit |
ogarcia/ultrasonic | core/subsonic-api/src/integrationTest/kotlin/org/moire/ultrasonic/api/subsonic/SubsonicApiGetArtistTest.kt | 2 | 2183 | package org.moire.ultrasonic.api.subsonic
import org.amshove.kluent.`should be equal to`
import org.amshove.kluent.`should equal`
import org.amshove.kluent.`should not be`
import org.junit.Test
import org.moire.ultrasonic.api.subsonic.models.Album
import org.moire.ultrasonic.api.subsonic.models.Artist
/**
* Integration test for [SubsonicAPIClient] for getArtist call.
*/
class SubsonicApiGetArtistTest : SubsonicAPIClientTest() {
@Test
fun `Should parse error call`() {
val response = checkErrorCallParsed(mockWebServerRule) {
client.api.getArtist("101").execute()
}
response.artist `should not be` null
response.artist `should equal` Artist()
}
@Test
fun `Should pass id param in request`() {
val id = "929"
mockWebServerRule.assertRequestParam(
responseResourceName = "get_artist_ok.json",
expectedParam = "id=$id"
) {
client.api.getArtist(id).execute()
}
}
@Test
fun `Should parse ok response`() {
mockWebServerRule.enqueueResponse("get_artist_ok.json")
val response = client.api.getArtist("100").execute()
assertResponseSuccessful(response)
with(response.body()!!.artist) {
id `should be equal to` "362"
name `should be equal to` "AC/DC"
coverArt `should be equal to` "ar-362"
albumCount `should be equal to` 2
albumsList.size `should be equal to` 2
albumsList[0] `should equal` Album(
id = "618", name = "Black Ice", artist = "AC/DC",
artistId = "362", coverArt = "al-618", songCount = 15, duration = 3331,
created = parseDate("2016-10-23T15:31:22.000Z"),
year = 2008, genre = "Hard Rock"
)
albumsList[1] `should equal` Album(
id = "617", name = "Rock or Bust", artist = "AC/DC",
artistId = "362", coverArt = "al-617", songCount = 11, duration = 2095,
created = parseDate("2016-10-23T15:31:23.000Z"),
year = 2014, genre = "Hard Rock"
)
}
}
}
| gpl-3.0 |
Thelonedevil/TLDMaths | TLDMaths/src/main/kotlin/uk/tldcode/math/tldmaths/Prime.kt | 1 | 602 | package uk.tldcode.math.tldmaths
import sequence.buildSequence
import java.math.BigInteger
object Prime : BigIntegerSequence {
override fun invoke(): Sequence<BigInteger> = buildSequence {
yield(BigInteger("2"))
for (a in OddNaturals().filter { it.isProbablePrime(10) }.filter { firstFactor(it, Prime()) == null }) {
yield(a)
}
}
private fun firstFactor(num: BigInteger, search: Sequence<BigInteger>): BigInteger? {
return search
.takeWhile { i -> i * i <= num }
.find { num % it == BigInteger.ZERO }
}
} | apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/completion/tests/testData/basic/java/Number.kt | 8 | 190 | // FIR_IDENTICAL
// FIR_COMPARISON
fun test(x: java.lang.Integer) {
x.<caret>
}
// EXIST: toByte
// EXIST: toShort
// EXIST: toInt
// EXIST: toLong
// EXIST: toFloat
// EXIST: toDouble
| apache-2.0 |
dahlstrom-g/intellij-community | java/idea-ui/src/com/intellij/jarRepository/settings/repositoryLibrariesReloader.kt | 9 | 1371 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.jarRepository.settings
import com.intellij.ide.JavaUiBundle
import com.intellij.jarRepository.JarRepositoryManager
import com.intellij.jarRepository.RepositoryLibrarySynchronizer
import com.intellij.notification.NotificationType
import com.intellij.notification.Notifications
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import org.jetbrains.concurrency.collectResults
import org.jetbrains.idea.maven.utils.library.RepositoryLibraryProperties
import org.jetbrains.idea.maven.utils.library.RepositoryUtils
fun reloadAllRepositoryLibraries(project: Project) {
val libraries = RepositoryLibrarySynchronizer.collectLibraries(project) {
(it as? LibraryEx)?.properties is RepositoryLibraryProperties
}.filterIsInstance<LibraryEx>()
libraries
.map { RepositoryUtils.reloadDependencies(project, it) }
.collectResults()
.onSuccess {
Notifications.Bus.notify(JarRepositoryManager.GROUP.createNotification(
JavaUiBundle.message("notification.title.repository.library.synchronization"),
JavaUiBundle.message("notification.content.libraries.reloaded", it.size),
NotificationType.INFORMATION), project)
}
} | apache-2.0 |
dahlstrom-g/intellij-community | platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/library/LibraryBridgeImpl.kt | 5 | 7985 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide.impl.legacyBridge.library
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.ProjectModelExternalSource
import com.intellij.openapi.roots.RootProvider
import com.intellij.openapi.roots.RootProvider.RootSetChangedListener
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.roots.impl.libraries.LibraryImpl
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.LibraryProperties
import com.intellij.openapi.roots.libraries.LibraryTable
import com.intellij.openapi.roots.libraries.PersistentLibraryKind
import com.intellij.openapi.util.TraceableDisposable
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.EventDispatcher
import com.intellij.util.containers.ConcurrentFactoryMap
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.findLibraryEntity
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.libraryMap
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots.ModuleLibraryTableBridge
import com.intellij.workspaceModel.storage.CachedValue
import com.intellij.workspaceModel.storage.VersionedEntityStorage
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.api.LibraryId
import com.intellij.workspaceModel.storage.bridgeEntities.api.LibraryRootTypeId
import org.jdom.Element
import org.jetbrains.annotations.ApiStatus
interface LibraryBridge : LibraryEx {
val libraryId: LibraryId
@ApiStatus.Internal
fun getModifiableModel(builder: MutableEntityStorage): LibraryEx.ModifiableModelEx
}
@ApiStatus.Internal
class LibraryBridgeImpl(
var libraryTable: LibraryTable,
val project: Project,
initialId: LibraryId,
initialEntityStorage: VersionedEntityStorage,
private var targetBuilder: MutableEntityStorage?
) : LibraryBridge, RootProvider, TraceableDisposable(true) {
override fun getModule(): Module? = (libraryTable as? ModuleLibraryTableBridge)?.module
var entityStorage: VersionedEntityStorage = initialEntityStorage
set(value) {
ApplicationManager.getApplication().assertWriteAccessAllowed()
field = value
}
var entityId: LibraryId = initialId
private var disposed = false
internal fun cleanCachedValue() {
entityStorage.clearCachedValue(librarySnapshotCached)
}
private val dispatcher = EventDispatcher.create(RootSetChangedListener::class.java)
private val librarySnapshotCached = CachedValue { storage ->
LibraryStateSnapshot(
libraryEntity = storage.findLibraryEntity(this) ?: error("Cannot find entity for library with ID $entityId"),
storage = storage,
libraryTable = libraryTable,
parentDisposable = this
)
}
val librarySnapshot: LibraryStateSnapshot
get() {
checkDisposed()
return entityStorage.cachedValue(librarySnapshotCached)
}
override val libraryId: LibraryId
get() = entityId
override fun getTable(): LibraryTable? = if (libraryTable is ModuleLibraryTableBridge) null else libraryTable
override fun getRootProvider(): RootProvider = this
override fun getPresentableName(): String = LibraryImpl.getPresentableName(this)
override fun toString(): String {
return "Library '$name', roots: ${librarySnapshot.libraryEntity.roots}"
}
override fun getModifiableModel(): LibraryEx.ModifiableModelEx {
return getModifiableModel(MutableEntityStorage.from(librarySnapshot.storage))
}
override fun getModifiableModel(builder: MutableEntityStorage): LibraryEx.ModifiableModelEx {
return LibraryModifiableModelBridgeImpl(this, librarySnapshot, builder, targetBuilder, false)
}
override fun getSource(): Library? = null
override fun getExternalSource(): ProjectModelExternalSource? = librarySnapshot.externalSource
override fun getInvalidRootUrls(type: OrderRootType): List<String> = librarySnapshot.getInvalidRootUrls(type)
override fun getKind(): PersistentLibraryKind<*>? = librarySnapshot.kind
override fun getName(): String? = LibraryNameGenerator.getLegacyLibraryName(entityId)
override fun getUrls(rootType: OrderRootType): Array<String> = librarySnapshot.getUrls(rootType)
override fun getFiles(rootType: OrderRootType): Array<VirtualFile> = librarySnapshot.getFiles(rootType)
override fun getProperties(): LibraryProperties<*>? = librarySnapshot.properties
override fun getExcludedRoots(): Array<VirtualFile> = librarySnapshot.excludedRoots
override fun getExcludedRootUrls(): Array<String> = librarySnapshot.excludedRootUrls
override fun isJarDirectory(url: String): Boolean = librarySnapshot.isJarDirectory(url)
override fun isJarDirectory(url: String, rootType: OrderRootType): Boolean = librarySnapshot.isJarDirectory(url, rootType)
override fun isValid(url: String, rootType: OrderRootType): Boolean = librarySnapshot.isValid(url, rootType)
override fun hasSameContent(library: Library): Boolean {
if (this === library) return true
if (library !is LibraryBridgeImpl) return false
if (name != library.name) return false
if (kind != library.kind) return false
if (properties != library.properties) return false
if (librarySnapshot.libraryEntity.roots != library.librarySnapshot.libraryEntity.roots) return false
if (!excludedRoots.contentEquals(library.excludedRoots)) return false
return true
}
override fun readExternal(element: Element?) = throw NotImplementedError()
override fun writeExternal(element: Element) = throw NotImplementedError()
override fun addRootSetChangedListener(listener: RootSetChangedListener) = dispatcher.addListener(listener)
override fun addRootSetChangedListener(listener: RootSetChangedListener, parentDisposable: Disposable) {
dispatcher.addListener(listener, parentDisposable)
}
override fun removeRootSetChangedListener(listener: RootSetChangedListener) = dispatcher.removeListener(listener)
override fun isDisposed(): Boolean = disposed
override fun dispose() {
checkDisposed()
disposed = true
kill(null)
}
private fun checkDisposed() {
if (isDisposed) {
val libraryEntity = try {
entityStorage.cachedValue(librarySnapshotCached).libraryEntity
}
catch (t: Throwable) {
null
}
val isDisposedGlobally = libraryEntity?.let {
WorkspaceModel.getInstance(project).entityStorage.current.libraryMap.getDataByEntity(it)?.isDisposed
}
val message = """
Library $entityId already disposed:
Library id: $libraryId
Entity: ${libraryEntity.run { "$name, $this" }}
Is disposed in project model: ${isDisposedGlobally != false}
Stack trace: $stackTrace
""".trimIndent()
try {
throwDisposalError(message)
}
catch (e: Exception) {
thisLogger().error(message, e)
throw e
}
}
}
internal fun fireRootSetChanged() {
dispatcher.multicaster.rootSetChanged(this)
}
fun clearTargetBuilder() {
targetBuilder = null
}
companion object {
private val libraryRootTypes = ConcurrentFactoryMap.createMap<String, LibraryRootTypeId> { LibraryRootTypeId(it) }
internal fun OrderRootType.toLibraryRootType(): LibraryRootTypeId = when (this) {
OrderRootType.CLASSES -> LibraryRootTypeId.COMPILED
OrderRootType.SOURCES -> LibraryRootTypeId.SOURCES
else -> libraryRootTypes[name()]!!
}
}
}
| apache-2.0 |
dahlstrom-g/intellij-community | platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/BundledRuntime.kt | 1 | 995 | // 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.intellij.build.impl
import org.jetbrains.intellij.build.JvmArchitecture
import org.jetbrains.intellij.build.OsFamily
import java.nio.file.Path
interface BundledRuntime {
fun getHomeForCurrentOsAndArch(): Path
/**
* contract: returns a directory, where only one subdirectory is available: 'jbr', which contains specified JBR
*/
fun extract(prefix: String, os: OsFamily, arch: JvmArchitecture): Path
fun extractTo(prefix: String, os: OsFamily, destinationDir: Path, arch: JvmArchitecture)
fun archiveName(prefix: String, arch: JvmArchitecture, os: OsFamily, forceVersionWithUnderscores: Boolean = false): String
fun findArchive(prefix: String, os: OsFamily, arch: JvmArchitecture): Path
fun checkExecutablePermissions(distribution: Path, root: String, os: OsFamily)
fun executableFilesPatterns(os: OsFamily): List<String>
}
| apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/j2k/new/tests/testData/copyPastePlainText/InsideIdentifier.expected.kt | 26 | 99 | fun foo() {
bArrayList<String> list = new ArrayList<String>();
// NO_CONVERSION_EXPECTEDar()
}
| apache-2.0 |
paslavsky/spek | spek-core/src/main/kotlin/org/jetbrains/spek/console/WorkflowReporter.kt | 1 | 1300 | package org.jetbrains.spek.console
import kotlin.collections.arrayListOf
import kotlin.collections.map
interface WorkflowReporter {
fun spek(spek: String): ActionStatusReporter
fun given(spek: String, given: String): ActionStatusReporter
fun on(spek: String, given: String, on: String): ActionStatusReporter
fun it(spek: String, given: String, on: String, it: String): ActionStatusReporter
}
class CompositeWorkflowReporter : WorkflowReporter {
private val listeners = arrayListOf<WorkflowReporter>()
fun addListener(l: WorkflowReporter) {
listeners.add(l)
}
override fun spek(spek: String): ActionStatusReporter {
return CompositeActionStatusReporter(listeners.map { it.spek(spek) })
}
override fun given(spek: String, given: String): ActionStatusReporter {
return CompositeActionStatusReporter(listeners.map { it.given(spek, given) })
}
override fun on(spek: String, given: String, on: String): ActionStatusReporter {
return CompositeActionStatusReporter(listeners.map { it.on(spek, given, on) })
}
override fun it(spek: String, given: String, on: String, it: String): ActionStatusReporter {
return CompositeActionStatusReporter(listeners.map { iit -> iit.it(spek, given, on, it) })
}
}
| bsd-3-clause |
dahlstrom-g/intellij-community | plugins/kotlin/jvm-debugger/test/testData/stepping/stepInto/defaultAccessors.kt | 13 | 659 | // FILE: defaultAccessors.kt
package defaultAccessors
fun main(args: Array<String>) {
//Breakpoint!
A().testPublicPropertyInClass()
testPublicPropertyInLibrary()
}
class A: B() {
fun testPublicPropertyInClass() {
prop
prop = 2
}
}
open class B {
public var prop: Int = 1
}
fun testPublicPropertyInLibrary() {
val myClass = customLib.simpleLibFile.B()
myClass.prop
myClass.prop = 2
}
// STEP_INTO: 21
// SKIP_SYNTHETIC_METHODS: true
// SKIP_CONSTRUCTORS: true
// FILE: customLib/simpleLibFile.kt
package customLib.simpleLibFile
public fun foo() {
1 + 1
}
class B {
public var prop: Int = 1
}
| apache-2.0 |
TechzoneMC/SonarPet | api/src/test/kotlin/net/techcable/sonarpet/test/assertions.kt | 1 | 2567 | package net.techcable.sonarpet.test
import org.junit.AssumptionViolatedException
import org.junit.ComparisonFailure
import kotlin.AssertionError
import kotlin.reflect.KClass
fun assertThat(condition: Boolean) = assertThat(condition) { "Assertion failed!" }
inline fun assertThat(condition: Boolean, lazyMessage: () -> String) {
if (!condition) {
fail(lazyMessage())
}
}
fun assertMatches(pattern: Regex, value: String) {
assertMatches(pattern, value) { "'$value' doesn't match $pattern" }
}
inline fun assertMatches(pattern: Regex, value: String, lazyMessage: () -> String) {
assertNotNull(pattern.matchEntire(value), lazyMessage = lazyMessage)
}
fun assertEqual(expected: Any?, actual: Any?) {
assertEqual(expected, actual) { "Expected $expected, but got $actual" }
}
inline fun assertEqual(expected: Any?, actual: Any?, lazyMessage: (actual: Any?) -> String) {
if (expected != actual) {
// NOTE: Only invoke lazyMessage once to avoid code bloat
val message = lazyMessage(actual)
if (expected is String && actual is String) {
throw ComparisonFailure(message, expected, actual)
} else {
throw AssertionError(message)
}
}
}
inline fun <reified T> assertNotNull(value: T?): T {
return assertNotNull(value) {
"${T::class.java.typeName} was null!"
}
}
inline fun <T> assertNotNull(value: T?, lazyMessage: () -> String): T {
if (value == null) {
fail(lazyMessage())
} else {
return value
}
}
fun assumeThat(condition: Boolean) {
assumeThat(condition) { "Assumption violated!" }
}
inline fun assumeThat(condition: Boolean, lazyMessage: () -> String) {
if (!condition) throw AssumptionViolatedException(lazyMessage())
}
inline fun assumeNoErrors(vararg errorTypes: KClass<out Throwable>, block: () -> Unit) {
try {
block()
} catch (e: Throwable) {
val matchedType = errorTypes.find { it.java.isInstance(e) }
if (matchedType != null) {
assumptionViolated("${matchedType.java.simpleName}: ${e.message}")
} else {
// Continue to propagate unexpected exception
throw e
}
}
}
inline fun <reified T: Throwable> assumeNoError(block: () -> Unit) {
assumeNoErrors(T::class, block = block)
}
@Suppress("NOTHING_TO_INLINE")
inline fun fail(message: String): Nothing = throw AssertionError(message)
@Suppress("NOTHING_TO_INLINE")
inline fun assumptionViolated(message: String): Nothing = throw AssumptionViolatedException(message)
| gpl-3.0 |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/actpost/FeaturedTagCache.kt | 1 | 2371 | package jp.juggler.subwaytooter.actpost
import android.os.SystemClock
import jp.juggler.subwaytooter.ActPost
import jp.juggler.subwaytooter.api.ApiTask
import jp.juggler.subwaytooter.api.TootParser
import jp.juggler.subwaytooter.api.entity.TootTag
import jp.juggler.subwaytooter.api.runApiTask
import jp.juggler.util.jsonObject
import jp.juggler.util.launchMain
import jp.juggler.util.toPostRequestBuilder
import jp.juggler.util.wrapWeakReference
class FeaturedTagCache(val list: List<TootTag>, val time: Long)
fun ActPost.updateFeaturedTags() {
val account = account
if (account == null || account.isPseudo) {
return
}
val cache = featuredTagCache[account.acct.ascii]
val now = SystemClock.elapsedRealtime()
if (cache != null && now - cache.time <= 300000L) return
// 同時に実行するタスクは1つまで
if (jobFeaturedTag?.get()?.isActive != true) {
jobFeaturedTag = launchMain {
runApiTask(
account,
progressStyle = ApiTask.PROGRESS_NONE,
) { client ->
if (account.isMisskey) {
client.request(
"/api/hashtags/trend",
jsonObject { }
.toPostRequestBuilder()
)?.also { result ->
val list = TootTag.parseList(
TootParser(this@runApiTask, account),
result.jsonArray
)
featuredTagCache[account.acct.ascii] =
FeaturedTagCache(list, SystemClock.elapsedRealtime())
}
} else {
client.request("/api/v1/featured_tags")?.also { result ->
val list = TootTag.parseList(
TootParser(this@runApiTask, account),
result.jsonArray
)
featuredTagCache[account.acct.ascii] =
FeaturedTagCache(list, SystemClock.elapsedRealtime())
}
}
}
if (isFinishing || isDestroyed) return@launchMain
updateFeaturedTags()
}.wrapWeakReference
}
}
| apache-2.0 |
JetBrains/workshop-jb | src/i_introduction/_2_Named_Arguments/n02NamedArguments.kt | 2 | 834 | package i_introduction._2_Named_Arguments
import i_introduction._1_Java_To_Kotlin_Converter.task1
import util.TODO
import util.doc2
// default values for arguments
fun bar(i: Int, s: String = "", b: Boolean = true) {}
fun usage() {
// named arguments
bar(1, b = false)
}
fun todoTask2(): Nothing = TODO(
"""
Task 2.
Print out the collection contents surrounded by curly braces using the library function 'joinToString'.
Specify only 'prefix' and 'postfix' arguments.
Don't forget to remove the 'todoTask2()' invocation which throws an exception.
""",
documentation = doc2(),
references = { collection: Collection<Int> -> task1(collection); collection.joinToString() })
fun task2(collection: Collection<Int>): String {
todoTask2()
return collection.joinToString()
} | mit |
MGaetan89/ShowsRage | app/src/test/kotlin/com/mgaetan89/showsrage/fragment/AddShowFragment_IsQueryValidTest.kt | 1 | 711 | package com.mgaetan89.showsrage.fragment
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
@RunWith(Parameterized::class)
class AddShowFragment_IsQueryValidTest(val query: String?, val valid: Boolean) {
@Test
fun isQueryValid() {
assertThat(AddShowFragment.isQueryValid(this.query)).isEqualTo(this.valid)
}
companion object {
@JvmStatic
@Parameterized.Parameters
fun data(): Collection<Array<Any?>> {
return listOf(
arrayOf<Any?>(null, false),
arrayOf<Any?>("", false),
arrayOf<Any?>(" ", false),
arrayOf<Any?>(" ", false),
arrayOf<Any?>(" some query ", true)
)
}
}
}
| apache-2.0 |
zbeboy/ISY | src/main/java/top/zbeboy/isy/web/util/weixin/PKCS7Encoder.kt | 1 | 1839 | package top.zbeboy.isy.web.util.weixin
import java.nio.charset.Charset
import java.util.*
/**
* Created by zbeboy 2017-11-20 .
**/
class PKCS7Encoder {
companion object {
@JvmField
val CHARSET = Charset.forName("utf-8")
/**
* 获得对明文进行补位填充的字节.
*
* @param count 需要进行填充补位操作的明文字节个数
* @return 补齐用的字节数组
*/
@JvmStatic
fun encode(count: Int): ByteArray {
// 计算需要填充的位数
val BLOCK_SIZE = 32
var amountToPad = BLOCK_SIZE - count % BLOCK_SIZE
if (amountToPad == 0) {
amountToPad = BLOCK_SIZE
}
// 获得补位所用的字符
val padChr = chr(amountToPad)
var tmp = ""
for (index in 0 until amountToPad) {
tmp += padChr
}
return tmp.toByteArray(CHARSET)
}
/**
* 删除解密后明文的补位字符
*
* @param decrypted 解密后的明文
* @return 删除补位字符后的明文
*/
@JvmStatic
fun decode(decrypted: ByteArray): ByteArray {
var pad = decrypted[decrypted.size - 1].toInt()
if (pad < 1 || pad > 32) {
pad = 0
}
return Arrays.copyOfRange(decrypted, 0, decrypted.size - pad)
}
/**
* 将数字转化成ASCII码对应的字符,用于对明文进行补码
*
* @param a 需要转化的数字
* @return 转化得到的字符
*/
@JvmStatic
private fun chr(a: Int): Char {
val target = (a and 0xFF).toByte()
return target.toChar()
}
}
} | mit |
paplorinc/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/ProjectConfigurationFilesProcessorImpl.kt | 1 | 5610 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs
import com.intellij.ide.highlighter.ModuleFileType
import com.intellij.ide.highlighter.ProjectFileType
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.components.*
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.changes.ChangeListListener
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.changes.ChangeListManagerEx
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.project.getProjectStoreDirectory
import com.intellij.project.isDirectoryBased
import com.intellij.util.containers.ContainerUtil
import com.intellij.vcsUtil.VcsImplUtil
private val LOG = Logger.getInstance(ProjectConfigurationFilesProcessorImpl::class.java)
private val configurationFilesExtensionsOutsideStoreDirectory =
ContainerUtil.newHashSet(ProjectFileType.DEFAULT_EXTENSION, ModuleFileType.DEFAULT_EXTENSION)
private const val SHARE_PROJECT_CONFIGURATION_FILES_PROPERTY = "SHARE_PROJECT_CONFIGURATION_FILES"
private const val ASKED_SHARE_PROJECT_CONFIGURATION_FILES_PROPERTY = "ASKED_SHARE_PROJECT_CONFIGURATION_FILES"
class ProjectConfigurationFilesProcessorImpl(project: Project,
parentDisposable: Disposable,
private val vcsName: String,
private val addChosenFiles: (Collection<VirtualFile>) -> Unit)
: FilesProcessorWithNotificationImpl(project, parentDisposable), FilesProcessor, ChangeListListener {
private val fileSystem = LocalFileSystem.getInstance()
private val projectConfigurationFilesStore = getProjectConfigurationFilesStore(project)
private val changeListManager = ChangeListManager.getInstance(project) as ChangeListManagerEx
init {
runReadAction {
if (!project.isDisposed) {
changeListManager.addChangeListListener(this, parentDisposable)
}
}
}
override fun changeListUpdateDone() {
if (!projectProperties.getBoolean(SHARE_PROJECT_CONFIGURATION_FILES_PROPERTY, false) && VcsImplUtil.isProjectSharedInVcs(project)) {
projectProperties.setValue(SHARE_PROJECT_CONFIGURATION_FILES_PROPERTY, true)
}
}
override fun doFilterFiles(files: Collection<VirtualFile>): Collection<VirtualFile> {
val projectBasePath = project.basePath ?: return files
val projectBaseDir = fileSystem.findFileByPath(projectBasePath) ?: return files
val storeDir = getProjectStoreDirectory(projectBaseDir)
if (project.isDirectoryBased && storeDir == null) {
LOG.warn("Cannot find store directory for project in directory ${projectBaseDir.path}")
return files
}
val filteredFiles = files.filter {
configurationFilesExtensionsOutsideStoreDirectory.contains(it.extension) || isProjectConfigurationFile(storeDir, it)
}
val previouslyStoredFiles = projectConfigurationFilesStore.cleanupAndGetValidFiles()
projectConfigurationFilesStore.addAll(filteredFiles)
return filteredFiles + previouslyStoredFiles
}
override fun doActionOnChosenFiles(files: Collection<VirtualFile>) {
addChosenFiles(files)
projectConfigurationFilesStore.removeAll(files)
}
override val askedBeforeProperty = ASKED_SHARE_PROJECT_CONFIGURATION_FILES_PROPERTY
override val doForCurrentProjectProperty = SHARE_PROJECT_CONFIGURATION_FILES_PROPERTY
override fun notificationTitle() = ""
override fun notificationMessage(): String = VcsBundle.message("project.configuration.files.add.notification.message", vcsName)
override val showActionText: String = VcsBundle.getString("project.configuration.files.add.notification.action.view")
override val forCurrentProjectActionText: String = VcsBundle.getString("project.configuration.files.add.notification.action.add")
override val forAllProjectsActionText: String? = null
override val muteActionText: String = VcsBundle.getString("project.configuration.files.add.notification.action.mute")
override fun rememberForAllProjects() {}
private fun isProjectConfigurationFile(storeDir: VirtualFile?, file: VirtualFile) =
storeDir != null && VfsUtilCore.isAncestor(storeDir, file, true)
}
@State(name = "ProjectConfigurationFiles", storages = [Storage(StoragePathMacros.WORKSPACE_FILE)])
class ProjectConfigurationFilesStoreState : PersistentStateComponent<ProjectConfigurationFilesStoreState.State> {
private val fileSystem = LocalFileSystem.getInstance()
data class State(var files: MutableList<String> = mutableListOf())
var myState = State()
fun cleanupAndGetValidFiles(): List<VirtualFile> {
val validFiles = state.files.mapNotNull { fileSystem.findFileByPath(it)}
state.files.retainAll(validFiles.map { it.path })
return validFiles
}
fun addAll(files: Collection<VirtualFile>) =
state.files.addAll(files.map(VirtualFile::getPath))
fun removeAll(files: Collection<VirtualFile>) =
state.files.removeAll(files.map(VirtualFile::getPath))
override fun getState() = myState
override fun loadState(state: State) {
myState = state
}
}
fun getProjectConfigurationFilesStore(project: Project): ProjectConfigurationFilesStoreState =
ServiceManager.getService(project, ProjectConfigurationFilesStoreState::class.java)
| apache-2.0 |
georocket/georocket | src/test/kotlin/io/georocket/output/xml/XMLMergerTest.kt | 1 | 6464 | package io.georocket.output.xml
import io.georocket.coVerify
import io.georocket.storage.GenericXmlChunkMeta
import io.georocket.storage.XmlChunkMeta
import io.georocket.util.XMLStartElement
import io.georocket.util.io.BufferWriteStream
import io.vertx.core.Vertx
import io.vertx.core.buffer.Buffer
import io.vertx.junit5.VertxExtension
import io.vertx.junit5.VertxTestContext
import io.vertx.kotlin.coroutines.dispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
/**
* Test [XMLMerger]
* @author Michel Kraemer
*/
@ExtendWith(VertxExtension::class)
class XMLMergerTest {
companion object {
private const val XMLHEADER = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>${"\n"}"""
private const val XSI = "xsi"
private const val SCHEMA_LOCATION = "schemaLocation"
private const val NS_CITYGML_1_0 = "http://www.opengis.net/citygml/1.0"
private const val NS_CITYGML_1_0_BUILDING = "http://www.opengis.net/citygml/building/1.0"
private const val NS_CITYGML_1_0_BUILDING_URL = "http://schemas.opengis.net/citygml/building/1.0/building.xsd"
private const val NS_CITYGML_1_0_BUILDING_SCHEMA_LOCATION = "$NS_CITYGML_1_0_BUILDING $NS_CITYGML_1_0_BUILDING_URL"
private const val NS_CITYGML_1_0_GENERICS = "http://www.opengis.net/citygml/generics/1.0"
private const val NS_CITYGML_1_0_GENERICS_URL = "http://schemas.opengis.net/citygml/generics/1.0/generics.xsd"
private const val NS_CITYGML_1_0_GENERICS_SCHEMA_LOCATION = "$NS_CITYGML_1_0_GENERICS $NS_CITYGML_1_0_GENERICS_URL"
private const val NS_GML = "http://www.opengis.net/gml"
private const val NS_SCHEMA_INSTANCE = "http://www.w3.org/2001/XMLSchema-instance"
}
private fun doMerge(
vertx: Vertx,
ctx: VertxTestContext,
chunks: List<Buffer>,
metas: List<XmlChunkMeta>,
xmlContents: String,
optimistic: Boolean,
expected: Class<out Throwable>? = null
) {
val m = XMLMerger(optimistic)
val bws = BufferWriteStream()
if (!optimistic) {
for (meta in metas) {
m.init(meta)
}
}
CoroutineScope(vertx.dispatcher()).launch {
ctx.coVerify {
try {
for ((meta, chunk) in metas.zip(chunks)) {
m.merge(chunk, meta, bws)
}
m.finish(bws)
assertThat(bws.buffer.toString("utf-8")).isEqualTo("""$XMLHEADER$xmlContents""")
if (expected != null) {
ctx.failNow(IllegalStateException("Excepted $expected to be thrown"))
}
} catch (t: Throwable) {
if (expected == null || t::class.java != expected) {
ctx.failNow(t)
}
}
}
ctx.completeNow()
}
}
/**
* Test if simple chunks can be merged
*/
@Test
fun simple(vertx: Vertx, ctx: VertxTestContext) {
val chunk1 = Buffer.buffer("""<test chunk="1"></test>""")
val chunk2 = Buffer.buffer("""<test chunk="2"></test>""")
val cm = GenericXmlChunkMeta(listOf(XMLStartElement(localName = "root")))
doMerge(
vertx,
ctx,
listOf(chunk1, chunk2),
listOf(cm, cm),
"""<root><test chunk="1"></test><test chunk="2"></test></root>""",
false
)
}
private fun mergeNamespaces(
vertx: Vertx, ctx: VertxTestContext, optimistic: Boolean, expected: Class<out Throwable>?
) {
val root1 = XMLStartElement(
null,
"CityModel",
listOf(null, "gml", "gen", XSI),
listOf(NS_CITYGML_1_0, NS_GML, NS_CITYGML_1_0_GENERICS, NS_SCHEMA_INSTANCE),
listOf(XSI),
listOf(SCHEMA_LOCATION),
listOf(NS_CITYGML_1_0_GENERICS_SCHEMA_LOCATION)
)
val root2 = XMLStartElement(
null,
"CityModel",
listOf(null, "gml", "bldg", XSI),
listOf(NS_CITYGML_1_0, NS_GML, NS_CITYGML_1_0_BUILDING, NS_SCHEMA_INSTANCE),
listOf(XSI),
listOf(SCHEMA_LOCATION),
listOf(NS_CITYGML_1_0_BUILDING_SCHEMA_LOCATION)
)
val contents1 = "<cityObjectMember><gen:GenericCityObject></gen:GenericCityObject></cityObjectMember>"
val chunk1 = Buffer.buffer(contents1)
val contents2 = "<cityObjectMember><bldg:Building></bldg:Building></cityObjectMember>"
val chunk2 = Buffer.buffer(contents2)
val cm1 = GenericXmlChunkMeta(listOf(root1))
val cm2 = GenericXmlChunkMeta(listOf(root2))
val expectedRoot = XMLStartElement(
null,
"CityModel",
listOf(null, "gml", "gen", XSI, "bldg"),
listOf(NS_CITYGML_1_0, NS_GML, NS_CITYGML_1_0_GENERICS, NS_SCHEMA_INSTANCE, NS_CITYGML_1_0_BUILDING),
listOf(XSI),
listOf(SCHEMA_LOCATION),
listOf("""$NS_CITYGML_1_0_GENERICS_SCHEMA_LOCATION $NS_CITYGML_1_0_BUILDING_SCHEMA_LOCATION""")
)
doMerge(
vertx,
ctx,
listOf(chunk1, chunk2),
listOf(cm1, cm2),
"""$expectedRoot$contents1$contents2</${expectedRoot.name}>""",
optimistic,
expected
)
}
/**
* Test if chunks with different namespaces can be merged
*/
@Test
fun mergeNamespaces(vertx: Vertx, ctx: VertxTestContext) {
mergeNamespaces(vertx, ctx, false, null)
}
/**
* Make sure chunks with different namespaces cannot be merged in
* optimistic mode
*/
@Test
fun mergeNamespacesOptimistic(vertx: Vertx, ctx: VertxTestContext) {
mergeNamespaces(vertx, ctx, true, IllegalStateException::class.java)
}
/**
* Test if chunks with the same namespaces can be merged in optimistic mode
*/
@Test
fun mergeOptimistic(vertx: Vertx, ctx: VertxTestContext) {
val root1 = XMLStartElement(
null,
"CityModel",
listOf(null, "gml", "gen", XSI),
listOf(NS_CITYGML_1_0, NS_GML, NS_CITYGML_1_0_GENERICS, NS_SCHEMA_INSTANCE),
listOf(XSI),
listOf(SCHEMA_LOCATION),
listOf(NS_CITYGML_1_0_GENERICS_SCHEMA_LOCATION)
)
val contents1 = "<cityObjectMember><gen:GenericCityObject></gen:GenericCityObject></cityObjectMember>"
val chunk1 = Buffer.buffer(contents1)
val contents2 = "<cityObjectMember><gen:Building></gen:Building></cityObjectMember>"
val chunk2 = Buffer.buffer(contents2)
val cm1 = GenericXmlChunkMeta(listOf(root1))
val cm2 = GenericXmlChunkMeta(listOf(root1))
doMerge(
vertx, ctx, listOf(chunk1, chunk2), listOf(cm1, cm2), """$root1$contents1$contents2</${root1.name}>""", true
)
}
}
| apache-2.0 |
paplorinc/intellij-community | plugins/stream-debugger/test/com/intellij/debugger/streams/exec/LibraryTraceExecutionTestCase.kt | 6 | 2275 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.debugger.streams.exec
import com.intellij.debugger.streams.test.TraceExecutionTestCase
import com.intellij.execution.configurations.JavaParameters
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PluginPathManager
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess
import com.intellij.testFramework.PsiTestUtil
import java.io.File
import java.nio.file.Paths
/**
* @author Vitaliy.Bibaev
*/
abstract class LibraryTraceExecutionTestCase(jarName: String) : TraceExecutionTestCase() {
private val libraryDirectory = File(PluginPathManager.getPluginHomePath("stream-debugger") + "/lib").absolutePath
private val jarPath = Paths.get(libraryDirectory, jarName).toAbsolutePath().toString()
private companion object {
fun String.replaceLibraryPath(libraryPath: String): String {
val caseSensitive = SystemInfo.isFileSystemCaseSensitive
val result = StringUtil.replace(this, FileUtil.toSystemDependentName(libraryPath), "!LIBRARY_JAR!", !caseSensitive)
return StringUtil.replace(result, FileUtil.toSystemIndependentName(libraryPath), "!LIBRARY_JAR!", !caseSensitive)
}
}
override fun setUpModule() {
super.setUpModule()
ApplicationManager.getApplication().runWriteAction {
VfsRootAccess.allowRootAccess(testRootDisposable, libraryDirectory)
PsiTestUtil.addLibrary(myModule, jarPath)
}
}
override fun replaceAdditionalInOutput(str: String): String {
return super.replaceAdditionalInOutput(str).replaceLibraryPath(jarPath)
}
override fun createJavaParameters(mainClass: String?): JavaParameters {
val parameters = super.createJavaParameters(mainClass)
parameters.classPath.add(jarPath)
return parameters
}
final override fun getTestAppPath(): String {
return File(PluginPathManager.getPluginHomePath("stream-debugger") + "/testData/${getTestAppRelativePath()}").absolutePath
}
abstract fun getTestAppRelativePath(): String
} | apache-2.0 |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/update/ConfigurePluginUpdatesForm.kt | 1 | 760 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.update
import com.intellij.util.ui.AsyncProcessIcon
import javax.swing.JButton
import javax.swing.JComboBox
import javax.swing.JLabel
import javax.swing.JPanel
class ConfigurePluginUpdatesForm {
lateinit var channelBox: JComboBox<String>
lateinit var checkForUpdatesNowButton: JButton
lateinit var panel: JPanel
lateinit var updateCheckInProgressIcon: AsyncProcessIcon
lateinit var updateStatusLabel: JLabel
lateinit var installButton: JButton
private fun createUIComponents() {
updateCheckInProgressIcon = AsyncProcessIcon("Plugin update check in progress")
}
}
| mit |
BreakOutEvent/breakout-backend | src/main/java/backend/model/challenges/ChallengeProofProjection.kt | 1 | 218 | package backend.model.challenges
import org.javamoney.moneta.Money
interface ChallengeProofProjection {
fun getId(): Long
fun getStatus(): String
fun getAmount(): Money
fun getDescription(): String
}
| agpl-3.0 |
paplorinc/intellij-community | plugins/settings-repository/src/git/commit.kt | 2 | 3216 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.settingsRepository.git
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.util.PathUtilRt
import com.intellij.util.SmartList
import org.eclipse.jgit.lib.IndexDiff
import org.eclipse.jgit.lib.ProgressMonitor
import org.eclipse.jgit.lib.Repository
import org.jetbrains.settingsRepository.LOG
import org.jetbrains.settingsRepository.PROJECTS_DIR_NAME
fun commit(repository: Repository, indicator: ProgressIndicator?, commitMessageFormatter: CommitMessageFormatter = IdeaCommitMessageFormatter()): Boolean {
indicator?.checkCanceled()
val diff = repository.computeIndexDiff()
val changed = diff.diff(indicator?.asProgressMonitor(), ProgressMonitor.UNKNOWN, ProgressMonitor.UNKNOWN, "Commit")
// don't worry about untracked/modified only in the FS files
if (!changed || (diff.added.isEmpty() && diff.changed.isEmpty() && diff.removed.isEmpty())) {
if (diff.modified.isEmpty() && diff.missing.isEmpty()) {
LOG.debug("Nothing to commit")
return false
}
var edits: MutableList<PathEdit>? = null
for (path in diff.modified) {
if (!path.startsWith(PROJECTS_DIR_NAME)) {
if (edits == null) {
edits = SmartList()
}
edits.add(AddFile(path))
}
}
for (path in diff.missing) {
if (edits == null) {
edits = SmartList()
}
edits.add(DeleteFile(path))
}
if (edits != null) {
repository.edit(edits)
}
}
LOG.debug { indexDiffToString(diff) }
indicator?.checkCanceled()
val builder = commitMessageFormatter.prependMessage()
// we use Github (edit via web UI) terms here
builder.appendCompactList("Update", diff.changed)
builder.appendCompactList("Create", diff.added)
builder.appendCompactList("Delete", diff.removed)
repository.commit(builder.toString())
return true
}
private fun indexDiffToString(diff: IndexDiff): String {
val builder = StringBuilder()
builder.append("To commit:")
builder.addList("Added", diff.added)
builder.addList("Changed", diff.changed)
builder.addList("Deleted", diff.removed)
builder.addList("Modified on disk relative to the index", diff.modified)
builder.addList("Untracked files", diff.untracked)
builder.addList("Untracked folders", diff.untrackedFolders)
builder.addList("Missing", diff.missing)
return builder.toString()
}
private fun StringBuilder.appendCompactList(name: String, list: Collection<String>) {
addList(name, list, true)
}
private fun StringBuilder.addList(name: String, list: Collection<String>, compact: Boolean = false) {
if (list.isEmpty()) {
return
}
if (compact) {
if (length != 0 && this[length - 1] != ' ') {
append('\t')
}
append(name)
}
else {
append('\t').append(name).append(':')
}
append(' ')
var isNotFirst = false
for (path in list) {
if (isNotFirst) {
append(',').append(' ')
}
else {
isNotFirst = true
}
append(if (compact) PathUtilRt.getFileName(path) else path)
}
}
| apache-2.0 |
apache/isis | incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/snapshots/simpleapp1_16_0/ACTIONS_DOWNLOAD_LAYOUTS.kt | 2 | 2717 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.causeway.client.kroviz.snapshots.simpleapp1_16_0
import org.apache.causeway.client.kroviz.snapshots.Response
object ACTIONS_DOWNLOAD_LAYOUTS : Response() {
override val url = "http://localhost:8080/restful/services/causewayApplib.LayoutServiceMenu/actions/downloadLayouts"
override val str = """{
"id" : "downloadLayouts",
"memberType" : "action",
"links" : [ {
"rel" : "self",
"href" : "http://localhost:8080/restful/services/causewayApplib.LayoutServiceMenu/actions/downloadLayouts",
"method" : "GET",
"type" : "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\""
}, {
"rel" : "up",
"href" : "http://localhost:8080/restful/services/causewayApplib.LayoutServiceMenu",
"method" : "GET",
"type" : "application/json;profile=\"urn:org.restfulobjects:repr-types/object\"",
"title" : "Prototyping"
}, {
"rel" : "urn:org.restfulobjects:rels/invoke;action=\"downloadLayouts\"",
"href" : "http://localhost:8080/restful/services/causewayApplib.LayoutServiceMenu/actions/downloadLayouts/invoke",
"method" : "GET",
"type" : "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"",
"arguments" : {
"style" : {
"value" : null
}
}
}, {
"rel" : "describedby",
"href" : "http://localhost:8080/restful/domain-types/causewayApplib.LayoutServiceMenu/actions/downloadLayouts",
"method" : "GET",
"type" : "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\""
} ],
"extensions" : {
"actionType" : "prototype",
"actionSemantics" : "safe"
},
"parameters" : {
"style" : {
"num" : 0,
"id" : "style",
"name" : "Style",
"description" : "",
"choices" : [ "Current", "Complete", "Normalized", "Minimal" ],
"default" : "Normalized"
}
}
}
"""
}
| apache-2.0 |
google/intellij-community | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/quickfix/fixes/AddAccessorsFactories.kt | 2 | 1466 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix.fixes
import org.jetbrains.kotlin.analysis.api.fir.diagnostics.KtFirDiagnostic
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.KotlinApplicatorInput
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.fixes.KotlinApplicatorBasedQuickFix
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.fixes.diagnosticFixFactories
import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.AddAccessorApplicator
import org.jetbrains.kotlin.psi.KtProperty
object AddAccessorsFactories {
val addAccessorsToUninitializedProperty =
diagnosticFixFactories(
KtFirDiagnostic.MustBeInitialized::class,
KtFirDiagnostic.MustBeInitializedOrBeAbstract::class
) { diagnostic ->
val property: KtProperty = diagnostic.psi
val addGetter = property.getter == null
val addSetter = property.isVar && property.setter == null
if (!addGetter && !addSetter) return@diagnosticFixFactories emptyList()
listOf(
KotlinApplicatorBasedQuickFix(
property,
KotlinApplicatorInput.Empty,
AddAccessorApplicator.applicator(addGetter, addSetter),
)
)
}
} | apache-2.0 |
Virtlink/aesi | aesi/src/main/kotlin/com/virtlink/editorservices/Offset.kt | 1 | 60 | package com.virtlink.editorservices
typealias Offset = Long | apache-2.0 |
google/intellij-community | java/java-impl/src/com/intellij/codeInsight/hints/AnnotationInlayProvider.kt | 5 | 10328 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.codeInsight.hints
import com.intellij.codeInsight.ExternalAnnotationsManager
import com.intellij.codeInsight.InferredAnnotationsManager
import com.intellij.codeInsight.MakeInferredAnnotationExplicit
import com.intellij.codeInsight.hints.presentation.InlayPresentation
import com.intellij.codeInsight.hints.presentation.MenuOnClickPresentation
import com.intellij.codeInsight.hints.presentation.PresentationFactory
import com.intellij.codeInsight.hints.presentation.SequencePresentation
import com.intellij.codeInsight.javadoc.JavaDocInfoGenerator
import com.intellij.java.JavaBundle
import com.intellij.lang.java.JavaLanguage
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.BlockInlayPriority
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ex.util.EditorUtil
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.NlsActions
import com.intellij.psi.*
import com.intellij.ui.layout.*
import com.intellij.util.SmartList
import javax.swing.JComponent
import kotlin.reflect.KMutableProperty0
class AnnotationInlayProvider : InlayHintsProvider<AnnotationInlayProvider.Settings> {
override val group: InlayGroup
get() = InlayGroup.ANNOTATIONS_GROUP
override fun getCollectorFor(file: PsiFile,
editor: Editor,
settings: Settings,
sink: InlayHintsSink): InlayHintsCollector {
val project = file.project
val document = PsiDocumentManager.getInstance(project).getDocument(file)
return object : FactoryInlayHintsCollector(editor) {
override fun collect(element: PsiElement, editor: Editor, sink: InlayHintsSink): Boolean {
if (file.project.service<DumbService>().isDumb) return false
if (file.project.isDefault) return false
val presentations = SmartList<InlayPresentation>()
if (element is PsiModifierListOwner) {
var annotations = emptySequence<PsiAnnotation>()
if (settings.showExternal) {
annotations += ExternalAnnotationsManager.getInstance(project).findExternalAnnotations(element).orEmpty()
}
if (settings.showInferred) {
annotations += InferredAnnotationsManager.getInstance(project).findInferredAnnotations(element)
}
val previewAnnotation = PREVIEW_ANNOTATION_KEY.get(element)
if (previewAnnotation != null) {
annotations += previewAnnotation
}
val shownAnnotations = mutableSetOf<String>()
annotations.forEach {
val nameReferenceElement = it.nameReferenceElement
if (nameReferenceElement != null && element.modifierList != null &&
(shownAnnotations.add(nameReferenceElement.qualifiedName) || JavaDocInfoGenerator.isRepeatableAnnotationType(it))) {
presentations.add(createPresentation(it, element))
}
}
val modifierList = element.modifierList
if (modifierList != null) {
val textRange = modifierList.textRange ?: return true
val offset = textRange.startOffset
if (presentations.isNotEmpty()) {
val presentation = SequencePresentation(presentations)
val prevSibling = element.prevSibling
when {
// element is first in line
prevSibling is PsiWhiteSpace && element !is PsiParameter && prevSibling.textContains('\n') && document != null -> {
val width = EditorUtil.getPlainSpaceWidth(editor)
val line = document.getLineNumber(offset)
val startOffset = document.getLineStartOffset(line)
val column = offset - startOffset
val shifted = factory.inset(presentation, left = column * width)
sink.addBlockElement(offset, true, true, BlockInlayPriority.ANNOTATIONS, shifted)
}
else -> {
sink.addInlineElement(offset, false, factory.inset(presentation, left = 1, right = 1), false)
}
}
}
}
}
return true
}
private fun createPresentation(
annotation: PsiAnnotation,
element: PsiModifierListOwner
): MenuOnClickPresentation {
val presentation = annotationPresentation(annotation)
return MenuOnClickPresentation(presentation, project) {
val makeExplicit = InsertAnnotationAction(project, file, element)
listOf(
makeExplicit,
ToggleSettingsAction(JavaBundle.message("settings.inlay.java.turn.off.external.annotations"), settings::showExternal, settings),
ToggleSettingsAction(JavaBundle.message("settings.inlay.java.turn.off.inferred.annotations"), settings::showInferred, settings)
)
}
}
private fun annotationPresentation(annotation: PsiAnnotation): InlayPresentation = with(factory) {
val nameReferenceElement = annotation.nameReferenceElement
val parameterList = annotation.parameterList
val presentations = mutableListOf(
smallText("@"),
psiSingleReference(smallText(nameReferenceElement?.referenceName ?: "")) { nameReferenceElement?.resolve() }
)
parametersPresentation(parameterList)?.let {
presentations.add(it)
}
roundWithBackground(SequencePresentation(presentations))
}
private fun parametersPresentation(parameterList: PsiAnnotationParameterList) = with(factory) {
val attributes = parameterList.attributes
when {
attributes.isEmpty() -> null
else -> insideParametersPresentation(attributes, collapsed = parameterList.textLength > 60)
}
}
private fun insideParametersPresentation(attributes: Array<PsiNameValuePair>, collapsed: Boolean) = with(factory) {
collapsible(
smallText("("),
smallText("..."),
{
join(
presentations = attributes.map { pairPresentation(it) },
separator = { smallText(", ") }
)
},
smallText(")"),
collapsed
)
}
private fun pairPresentation(attribute: PsiNameValuePair) = with(factory) {
when (val attrName = attribute.name) {
null -> attrValuePresentation(attribute)
else -> seq(
psiSingleReference(smallText(attrName), resolve = { attribute.reference?.resolve() }),
smallText(" = "),
attrValuePresentation(attribute)
)
}
}
private fun PresentationFactory.attrValuePresentation(attribute: PsiNameValuePair) =
smallText(attribute.value?.text ?: "")
}
}
override fun createSettings(): Settings = Settings()
override val name: String
get() = JavaBundle.message("settings.inlay.java.annotations")
override val key: SettingsKey<Settings>
get() = ourKey
override fun getCaseDescription(case: ImmediateConfigurable.Case): String? {
when (case.id) {
"inferred.annotations" -> return JavaBundle.message("inlay.annotation.hints.inferred.annotations")
"external.annotations" -> return JavaBundle.message("inlay.annotation.hints.external.annotations")
}
return null
}
override val previewText: String? = null
private val PREVIEW_ANNOTATION_KEY = Key.create<PsiAnnotation>("preview.annotation.key")
override fun preparePreview(editor: Editor, file: PsiFile, settings: Settings) {
val psiMethod = (file as PsiJavaFile).classes[0].methods[0]
val factory = PsiElementFactory.getInstance(file.project)
if (psiMethod.parameterList.isEmpty) {
PREVIEW_ANNOTATION_KEY.set(psiMethod, factory.createAnnotationFromText("@Deprecated", psiMethod))
}
else
PREVIEW_ANNOTATION_KEY.set(psiMethod.parameterList.getParameter(0), factory.createAnnotationFromText("@NotNull", psiMethod))
}
override fun createConfigurable(settings: Settings): ImmediateConfigurable {
return object : ImmediateConfigurable {
override fun createComponent(listener: ChangeListener): JComponent = panel {}
override val mainCheckboxText: String
get() = JavaBundle.message("settings.inlay.java.show.hints.for")
override val cases: List<ImmediateConfigurable.Case>
get() = listOf(
ImmediateConfigurable.Case(JavaBundle.message("settings.inlay.java.inferred.annotations"), "inferred.annotations", settings::showInferred),
ImmediateConfigurable.Case(JavaBundle.message("settings.inlay.java.external.annotations"), "external.annotations", settings::showExternal)
)
}
}
companion object {
val ourKey: SettingsKey<Settings> = SettingsKey("annotation.hints")
}
data class Settings(var showInferred: Boolean = false, var showExternal: Boolean = true)
class ToggleSettingsAction(@NlsActions.ActionText val text: String, val prop: KMutableProperty0<Boolean>, val settings: Settings) : AnAction() {
override fun update(e: AnActionEvent) {
val presentation = e.presentation
presentation.text = text
}
override fun actionPerformed(e: AnActionEvent) {
prop.set(!prop.get())
val storage = InlayHintsSettings.instance()
storage.storeSettings(ourKey, JavaLanguage.INSTANCE, settings)
InlayHintsPassFactory.forceHintsUpdateOnNextPass()
}
}
}
class InsertAnnotationAction(
private val project: Project,
private val file: PsiFile,
private val element: PsiModifierListOwner
) : AnAction() {
override fun update(e: AnActionEvent) {
e.presentation.text = JavaBundle.message("settings.inlay.java.insert.annotation")
}
override fun actionPerformed(e: AnActionEvent) {
val intention = MakeInferredAnnotationExplicit()
if (intention.isAvailable(file, element)) {
intention.makeAnnotationsExplicit(project, file, element)
}
}
}
| apache-2.0 |
denzelby/telegram-bot-bumblebee | telegram-bot-bumblebee-core/src/main/kotlin/com/github/bumblebee/command/currency/CurrencyActualExchangeRateCommand.kt | 1 | 1878 | package com.github.bumblebee.command.currency
import com.github.bumblebee.command.SingleArgumentCommand
import com.github.bumblebee.command.currency.domain.SupportedCurrency
import com.github.bumblebee.command.currency.service.BYRExchangeRateRetrieveService
import com.github.bumblebee.service.RandomPhraseService
import com.github.bumblebee.util.logger
import com.github.telegram.api.BotApi
import com.github.telegram.domain.Update
import org.springframework.stereotype.Component
import java.text.MessageFormat
@Component
class CurrencyActualExchangeRateCommand(
private val botApi: BotApi,
private val randomPhrase: RandomPhraseService,
private val exchangeRateRetrieveService: BYRExchangeRateRetrieveService) : SingleArgumentCommand() {
override fun handleCommand(update: Update, chatId: Long, argument: String?) {
val currencyName = getCurrencyNameOrDefault(argument, SupportedCurrency.USD)
try {
val rate = exchangeRateRetrieveService.getCurrentExchangeRate(currencyName)
if (rate != null) {
val message = MessageFormat.format("BYR/{0}: {1}", currencyName, rate)
botApi.sendMessage(chatId, message)
} else {
botApi.sendMessage(chatId, "NBRB doesn't know.", update.message!!.messageId)
}
} catch (e: Exception) {
log.error("Currency retrieve failed for $currencyName", e)
botApi.sendMessage(chatId, randomPhrase.no(), update.message!!.messageId)
}
}
private fun getCurrencyNameOrDefault(argument: String?, defaultCurrency: SupportedCurrency): String {
return if (!argument.isNullOrEmpty()) argument.trim { it <= ' ' }.toUpperCase()
else defaultCurrency.name
}
companion object {
private val log = logger<CurrencyActualExchangeRateCommand>()
}
}
| mit |
google/iosched | mobile/src/main/java/com/google/samples/apps/iosched/widget/BottomSheetBehavior.kt | 1 | 31994 | /*
* Copyright 2018 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.widget
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.os.Parcel
import android.os.Parcelable
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.VelocityTracker
import android.view.View
import android.view.ViewConfiguration
import android.view.ViewGroup
import androidx.annotation.IntDef
import androidx.annotation.VisibleForTesting
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.coordinatorlayout.widget.CoordinatorLayout.Behavior
import androidx.core.view.ViewCompat
import androidx.customview.view.AbsSavedState
import androidx.customview.widget.ViewDragHelper
import com.google.samples.apps.iosched.R
import com.google.samples.apps.iosched.shared.util.readBooleanUsingCompat
import com.google.samples.apps.iosched.shared.util.writeBooleanUsingCompat
import java.lang.ref.WeakReference
import kotlin.math.absoluteValue
/**
* Copy of material lib's BottomSheetBehavior that includes some bug fixes.
*/
// TODO remove when a fixed version in material lib is released.
class BottomSheetBehavior<V : View> : Behavior<V> {
companion object {
/** The bottom sheet is dragging. */
const val STATE_DRAGGING = 1
/** The bottom sheet is settling. */
const val STATE_SETTLING = 2
/** The bottom sheet is expanded. */
const val STATE_EXPANDED = 3
/** The bottom sheet is collapsed. */
const val STATE_COLLAPSED = 4
/** The bottom sheet is hidden. */
const val STATE_HIDDEN = 5
/** The bottom sheet is half-expanded (used when behavior_fitToContents is false). */
const val STATE_HALF_EXPANDED = 6
/**
* Peek at the 16:9 ratio keyline of its parent. This can be used as a parameter for
* [setPeekHeight(Int)]. [getPeekHeight()] will return this when the value is set.
*/
const val PEEK_HEIGHT_AUTO = -1
private const val HIDE_THRESHOLD = 0.5f
private const val HIDE_FRICTION = 0.1f
@IntDef(
value = [
STATE_DRAGGING,
STATE_SETTLING,
STATE_EXPANDED,
STATE_COLLAPSED,
STATE_HIDDEN,
STATE_HALF_EXPANDED
]
)
@Retention(AnnotationRetention.SOURCE)
annotation class State
/** Utility to get the [BottomSheetBehavior] from a [view]. */
@JvmStatic
fun from(view: View): BottomSheetBehavior<*> {
val lp = view.layoutParams as? CoordinatorLayout.LayoutParams
?: throw IllegalArgumentException("view is not a child of CoordinatorLayout")
return lp.behavior as? BottomSheetBehavior
?: throw IllegalArgumentException("view not associated with this behavior")
}
}
/** Callback for monitoring events about bottom sheets. */
interface BottomSheetCallback {
/**
* Called when the bottom sheet changes its state.
*
* @param bottomSheet The bottom sheet view.
* @param newState The new state. This will be one of link [STATE_DRAGGING],
* [STATE_SETTLING], [STATE_EXPANDED], [STATE_COLLAPSED], [STATE_HIDDEN], or
* [STATE_HALF_EXPANDED].
*/
fun onStateChanged(bottomSheet: View, newState: Int) {}
/**
* Called when the bottom sheet is being dragged.
*
* @param bottomSheet The bottom sheet view.
* @param slideOffset The new offset of this bottom sheet within [-1,1] range. Offset
* increases as this bottom sheet is moving upward. From 0 to 1 the sheet is between
* collapsed and expanded states and from -1 to 0 it is between hidden and collapsed states.
*/
fun onSlide(bottomSheet: View, slideOffset: Float) {}
}
/** The current state of the bottom sheet, backing property */
private var _state = STATE_COLLAPSED
/** The current state of the bottom sheet */
@State
var state
get() = _state
set(@State value) {
if (_state == value) {
return
}
if (viewRef == null) {
// Child is not laid out yet. Set our state and let onLayoutChild() handle it later.
if (value == STATE_COLLAPSED ||
value == STATE_EXPANDED ||
value == STATE_HALF_EXPANDED ||
(isHideable && value == STATE_HIDDEN)
) {
_state = value
}
return
}
viewRef?.get()?.apply {
// Start the animation; wait until a pending layout if there is one.
if (parent != null && parent.isLayoutRequested && isAttachedToWindow) {
post {
startSettlingAnimation(this, value)
}
} else {
startSettlingAnimation(this, value)
}
}
}
/** Whether to fit to contents. If false, the behavior will include [STATE_HALF_EXPANDED]. */
var isFitToContents = true
set(value) {
if (field != value) {
field = value
// If sheet is already laid out, recalculate the collapsed offset.
// Otherwise onLayoutChild will handle this later.
if (viewRef != null) {
collapsedOffset = calculateCollapsedOffset()
}
// Fix incorrect expanded settings.
setStateInternal(
if (field && state == STATE_HALF_EXPANDED) STATE_EXPANDED else state
)
}
}
/** Real peek height in pixels */
private var _peekHeight = 0
/** Peek height in pixels, or [PEEK_HEIGHT_AUTO] */
var peekHeight
get() = if (peekHeightAuto) PEEK_HEIGHT_AUTO else _peekHeight
set(value) {
var needLayout = false
if (value == PEEK_HEIGHT_AUTO) {
if (!peekHeightAuto) {
peekHeightAuto = true
needLayout = true
}
} else if (peekHeightAuto || _peekHeight != value) {
peekHeightAuto = false
_peekHeight = Math.max(0, value)
collapsedOffset = parentHeight - value
needLayout = true
}
if (needLayout && (state == STATE_COLLAPSED || state == STATE_HIDDEN)) {
viewRef?.get()?.requestLayout()
}
}
/** Whether the bottom sheet can be hidden. */
var isHideable = false
set(value) {
if (field != value) {
field = value
if (!value && state == STATE_HIDDEN) {
// Fix invalid state by moving to collapsed
state = STATE_COLLAPSED
}
}
}
/** Whether the bottom sheet can be dragged or not. */
var isDraggable = true
/** Whether the bottom sheet should skip collapsed state after being expanded once. */
var skipCollapsed = false
/** Whether animations should be disabled, to be used from UI tests. */
@VisibleForTesting
var isAnimationDisabled = false
/** Whether or not to use automatic peek height */
private var peekHeightAuto = false
/** Minimum peek height allowed */
private var peekHeightMin = 0
/** The last peek height calculated in onLayoutChild */
private var lastPeekHeight = 0
private var parentHeight = 0
/** Bottom sheet's top offset in [STATE_EXPANDED] state. */
private var fitToContentsOffset = 0
/** Bottom sheet's top offset in [STATE_HALF_EXPANDED] state. */
private var halfExpandedOffset = 0
/** Bottom sheet's top offset in [STATE_COLLAPSED] state. */
private var collapsedOffset = 0
/** Keeps reference to the bottom sheet outside of Behavior callbacks */
private var viewRef: WeakReference<View>? = null
/** Controls movement of the bottom sheet */
private lateinit var dragHelper: ViewDragHelper
// Touch event handling, etc
private var lastTouchX = 0
private var lastTouchY = 0
private var initialTouchY = 0
private var activePointerId = MotionEvent.INVALID_POINTER_ID
private var acceptTouches = true
private var minimumVelocity = 0
private var maximumVelocity = 0
private var velocityTracker: VelocityTracker? = null
private var nestedScrolled = false
private var nestedScrollingChildRef: WeakReference<View>? = null
private val callbacks: MutableSet<BottomSheetCallback> = mutableSetOf()
constructor() : super()
@SuppressLint("PrivateResource")
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
// Re-use BottomSheetBehavior's attrs
val a = context.obtainStyledAttributes(attrs, R.styleable.BottomSheetBehavior_Layout)
val value = a.peekValue(R.styleable.BottomSheetBehavior_Layout_behavior_peekHeight)
peekHeight = if (value != null && value.data == PEEK_HEIGHT_AUTO) {
value.data
} else {
a.getDimensionPixelSize(
R.styleable.BottomSheetBehavior_Layout_behavior_peekHeight, PEEK_HEIGHT_AUTO
)
}
isHideable = a.getBoolean(R.styleable.BottomSheetBehavior_Layout_behavior_hideable, false)
isFitToContents =
a.getBoolean(R.styleable.BottomSheetBehavior_Layout_behavior_fitToContents, true)
skipCollapsed =
a.getBoolean(R.styleable.BottomSheetBehavior_Layout_behavior_skipCollapsed, false)
a.recycle()
val configuration = ViewConfiguration.get(context)
minimumVelocity = configuration.scaledMinimumFlingVelocity
maximumVelocity = configuration.scaledMaximumFlingVelocity
}
override fun onSaveInstanceState(parent: CoordinatorLayout, child: V): Parcelable {
return SavedState(
super.onSaveInstanceState(parent, child) ?: Bundle.EMPTY,
state,
peekHeight,
isFitToContents,
isHideable,
skipCollapsed,
isDraggable
)
}
override fun onRestoreInstanceState(parent: CoordinatorLayout, child: V, state: Parcelable) {
val ss = state as SavedState
super.onRestoreInstanceState(parent, child, ss.superState ?: Bundle.EMPTY)
isDraggable = ss.isDraggable
peekHeight = ss.peekHeight
isFitToContents = ss.isFitToContents
isHideable = ss.isHideable
skipCollapsed = ss.skipCollapsed
// Set state last. Intermediate states are restored as collapsed state.
_state = if (ss.state == STATE_DRAGGING || ss.state == STATE_SETTLING) {
STATE_COLLAPSED
} else {
ss.state
}
}
fun addBottomSheetCallback(callback: BottomSheetCallback) {
callbacks.add(callback)
}
fun removeBottomSheetCallback(callback: BottomSheetCallback) {
callbacks.remove(callback)
}
private fun setStateInternal(@State state: Int) {
if (_state != state) {
_state = state
viewRef?.get()?.let { view ->
callbacks.forEach { callback ->
callback.onStateChanged(view, state)
}
}
}
}
// -- Layout
override fun onLayoutChild(
parent: CoordinatorLayout,
child: V,
layoutDirection: Int
): Boolean {
if (parent.fitsSystemWindows && !child.fitsSystemWindows) {
child.fitsSystemWindows = true
}
val savedTop = child.top
// First let the parent lay it out
parent.onLayoutChild(child, layoutDirection)
parentHeight = parent.height
// Calculate peek and offsets
if (peekHeightAuto) {
if (peekHeightMin == 0) {
// init peekHeightMin
@SuppressLint("PrivateResource")
peekHeightMin = parent.resources.getDimensionPixelSize(
R.dimen.design_bottom_sheet_peek_height_min
)
}
lastPeekHeight = Math.max(peekHeightMin, parentHeight - parent.width * 9 / 16)
} else {
lastPeekHeight = _peekHeight
}
fitToContentsOffset = Math.max(0, parentHeight - child.height)
halfExpandedOffset = parentHeight / 2
collapsedOffset = calculateCollapsedOffset()
// Offset the bottom sheet
when (state) {
STATE_EXPANDED -> ViewCompat.offsetTopAndBottom(child, getExpandedOffset())
STATE_HALF_EXPANDED -> ViewCompat.offsetTopAndBottom(child, halfExpandedOffset)
STATE_HIDDEN -> ViewCompat.offsetTopAndBottom(child, parentHeight)
STATE_COLLAPSED -> ViewCompat.offsetTopAndBottom(child, collapsedOffset)
STATE_DRAGGING, STATE_SETTLING -> ViewCompat.offsetTopAndBottom(
child, savedTop - child.top
)
}
// Init these for later
viewRef = WeakReference(child)
if (!::dragHelper.isInitialized) {
dragHelper = ViewDragHelper.create(parent, dragCallback)
}
return true
}
private fun calculateCollapsedOffset(): Int {
return if (isFitToContents) {
Math.max(parentHeight - lastPeekHeight, fitToContentsOffset)
} else {
parentHeight - lastPeekHeight
}
}
private fun getExpandedOffset() = if (isFitToContents) fitToContentsOffset else 0
// -- Touch events and scrolling
override fun onInterceptTouchEvent(
parent: CoordinatorLayout,
child: V,
event: MotionEvent
): Boolean {
if (!isDraggable || !child.isShown) {
acceptTouches = false
return false
}
val action = event.actionMasked
lastTouchX = event.x.toInt()
lastTouchY = event.y.toInt()
// Record velocity
if (action == MotionEvent.ACTION_DOWN) {
resetVelocityTracker()
}
if (velocityTracker == null) {
velocityTracker = VelocityTracker.obtain()
}
velocityTracker?.addMovement(event)
when (action) {
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
activePointerId = MotionEvent.INVALID_POINTER_ID
if (!acceptTouches) {
acceptTouches = true
return false
}
}
MotionEvent.ACTION_DOWN -> {
activePointerId = event.getPointerId(event.actionIndex)
initialTouchY = event.y.toInt()
clearNestedScroll()
if (!parent.isPointInChildBounds(child, lastTouchX, initialTouchY)) {
// Not touching the sheet
acceptTouches = false
}
}
}
return acceptTouches &&
// CoordinatorLayout can call us before the view is laid out. >_<
::dragHelper.isInitialized &&
dragHelper.shouldInterceptTouchEvent(event)
}
override fun onTouchEvent(
parent: CoordinatorLayout,
child: V,
event: MotionEvent
): Boolean {
if (!isDraggable || !child.isShown) {
return false
}
val action = event.actionMasked
if (action == MotionEvent.ACTION_DOWN && state == STATE_DRAGGING) {
return true
}
lastTouchX = event.x.toInt()
lastTouchY = event.y.toInt()
// Record velocity
if (action == MotionEvent.ACTION_DOWN) {
resetVelocityTracker()
}
if (velocityTracker == null) {
velocityTracker = VelocityTracker.obtain()
}
velocityTracker?.addMovement(event)
// CoordinatorLayout can call us before the view is laid out. >_<
if (::dragHelper.isInitialized) {
dragHelper.processTouchEvent(event)
}
if (acceptTouches &&
action == MotionEvent.ACTION_MOVE &&
exceedsTouchSlop(initialTouchY, lastTouchY)
) {
// Manually capture the sheet since nothing beneath us is scrolling.
dragHelper.captureChildView(child, event.getPointerId(event.actionIndex))
}
return acceptTouches
}
private fun resetVelocityTracker() {
activePointerId = MotionEvent.INVALID_POINTER_ID
velocityTracker?.recycle()
velocityTracker = null
}
private fun exceedsTouchSlop(p1: Int, p2: Int) = Math.abs(p1 - p2) >= dragHelper.touchSlop
// Nested scrolling
override fun onStartNestedScroll(
coordinatorLayout: CoordinatorLayout,
child: V,
directTargetChild: View,
target: View,
axes: Int,
type: Int
): Boolean {
nestedScrolled = false
if (isDraggable &&
viewRef?.get() == directTargetChild &&
(axes and ViewCompat.SCROLL_AXIS_VERTICAL) != 0
) {
// Scrolling view is a descendent of the sheet and scrolling vertically.
// Let's follow along!
nestedScrollingChildRef = WeakReference(target)
return true
}
return false
}
override fun onNestedPreScroll(
coordinatorLayout: CoordinatorLayout,
child: V,
target: View,
dx: Int,
dy: Int,
consumed: IntArray,
type: Int
) {
if (type == ViewCompat.TYPE_NON_TOUCH) {
return // Ignore fling here
}
if (target != nestedScrollingChildRef?.get()) {
return
}
val currentTop = child.top
val newTop = currentTop - dy
if (dy > 0) { // Upward
if (newTop < getExpandedOffset()) {
consumed[1] = currentTop - getExpandedOffset()
ViewCompat.offsetTopAndBottom(child, -consumed[1])
setStateInternal(STATE_EXPANDED)
} else {
consumed[1] = dy
ViewCompat.offsetTopAndBottom(child, -dy)
setStateInternal(STATE_DRAGGING)
}
} else if (dy < 0) { // Downward
if (!target.canScrollVertically(-1)) {
if (newTop <= collapsedOffset || isHideable) {
consumed[1] = dy
ViewCompat.offsetTopAndBottom(child, -dy)
setStateInternal(STATE_DRAGGING)
} else {
consumed[1] = currentTop - collapsedOffset
ViewCompat.offsetTopAndBottom(child, -consumed[1])
setStateInternal(STATE_COLLAPSED)
}
}
}
dispatchOnSlide(child.top)
nestedScrolled = true
}
override fun onStopNestedScroll(
coordinatorLayout: CoordinatorLayout,
child: V,
target: View,
type: Int
) {
if (child.top == getExpandedOffset()) {
setStateInternal(STATE_EXPANDED)
return
}
if (target != nestedScrollingChildRef?.get() || !nestedScrolled) {
return
}
settleBottomSheet(child, getYVelocity(), true)
clearNestedScroll()
}
override fun onNestedPreFling(
coordinatorLayout: CoordinatorLayout,
child: V,
target: View,
velocityX: Float,
velocityY: Float
): Boolean {
return isDraggable &&
target == nestedScrollingChildRef?.get() &&
(
state != STATE_EXPANDED || super.onNestedPreFling(
coordinatorLayout, child, target, velocityX, velocityY
)
)
}
private fun clearNestedScroll() {
nestedScrolled = false
nestedScrollingChildRef = null
}
// Settling
private fun getYVelocity(): Float {
return velocityTracker?.run {
computeCurrentVelocity(1000, maximumVelocity.toFloat())
getYVelocity(activePointerId)
} ?: 0f
}
private fun settleBottomSheet(sheet: View, yVelocity: Float, isNestedScroll: Boolean) {
val top: Int
@State val targetState: Int
val flinging = yVelocity.absoluteValue > minimumVelocity
if (flinging && yVelocity < 0) { // Moving up
if (isFitToContents) {
top = fitToContentsOffset
targetState = STATE_EXPANDED
} else {
if (sheet.top > halfExpandedOffset) {
top = halfExpandedOffset
targetState = STATE_HALF_EXPANDED
} else {
top = 0
targetState = STATE_EXPANDED
}
}
} else if (isHideable && shouldHide(sheet, yVelocity)) {
top = parentHeight
targetState = STATE_HIDDEN
} else if (flinging && yVelocity > 0) { // Moving down
top = collapsedOffset
targetState = STATE_COLLAPSED
} else {
val currentTop = sheet.top
if (isFitToContents) {
if (Math.abs(currentTop - fitToContentsOffset)
< Math.abs(currentTop - collapsedOffset)
) {
top = fitToContentsOffset
targetState = STATE_EXPANDED
} else {
top = collapsedOffset
targetState = STATE_COLLAPSED
}
} else {
if (currentTop < halfExpandedOffset) {
if (currentTop < Math.abs(currentTop - collapsedOffset)) {
top = 0
targetState = STATE_EXPANDED
} else {
top = halfExpandedOffset
targetState = STATE_HALF_EXPANDED
}
} else {
if (Math.abs(currentTop - halfExpandedOffset)
< Math.abs(currentTop - collapsedOffset)
) {
top = halfExpandedOffset
targetState = STATE_HALF_EXPANDED
} else {
top = collapsedOffset
targetState = STATE_COLLAPSED
}
}
}
}
val startedSettling = if (isNestedScroll) {
dragHelper.smoothSlideViewTo(sheet, sheet.left, top)
} else {
dragHelper.settleCapturedViewAt(sheet.left, top)
}
if (startedSettling) {
setStateInternal(STATE_SETTLING)
ViewCompat.postOnAnimation(sheet, SettleRunnable(sheet, targetState))
} else {
setStateInternal(targetState)
}
}
private fun shouldHide(child: View, yVelocity: Float): Boolean {
if (skipCollapsed) {
return true
}
if (child.top < collapsedOffset) {
return false // it should not hide, but collapse.
}
val newTop = child.top + yVelocity * HIDE_FRICTION
return Math.abs(newTop - collapsedOffset) / _peekHeight.toFloat() > HIDE_THRESHOLD
}
private fun startSettlingAnimation(child: View, state: Int) {
var top: Int
var finalState = state
when {
state == STATE_COLLAPSED -> top = collapsedOffset
state == STATE_EXPANDED -> top = getExpandedOffset()
state == STATE_HALF_EXPANDED -> {
top = halfExpandedOffset
// Skip to expanded state if we would scroll past the height of the contents.
if (isFitToContents && top <= fitToContentsOffset) {
finalState = STATE_EXPANDED
top = fitToContentsOffset
}
}
state == STATE_HIDDEN && isHideable -> top = parentHeight
else -> throw IllegalArgumentException("Invalid state: " + state)
}
if (isAnimationDisabled) {
// Prevent animations
ViewCompat.offsetTopAndBottom(child, top - child.top)
}
if (dragHelper.smoothSlideViewTo(child, child.left, top)) {
setStateInternal(STATE_SETTLING)
ViewCompat.postOnAnimation(child, SettleRunnable(child, finalState))
} else {
setStateInternal(finalState)
}
}
private fun dispatchOnSlide(top: Int) {
viewRef?.get()?.let { sheet ->
val denom = if (top > collapsedOffset) {
parentHeight - collapsedOffset
} else {
collapsedOffset - getExpandedOffset()
}
callbacks.forEach { callback ->
callback.onSlide(sheet, (collapsedOffset - top).toFloat() / denom)
}
}
}
private inner class SettleRunnable(
private val view: View,
@State private val state: Int
) : Runnable {
override fun run() {
if (dragHelper.continueSettling(true)) {
view.postOnAnimation(this)
} else {
setStateInternal(state)
}
}
}
private val dragCallback: ViewDragHelper.Callback = object : ViewDragHelper.Callback() {
override fun tryCaptureView(child: View, pointerId: Int): Boolean {
when {
// Sanity check
state == STATE_DRAGGING -> return false
// recapture a settling sheet
dragHelper.viewDragState == ViewDragHelper.STATE_SETTLING -> return true
// let nested scroll handle this
nestedScrollingChildRef?.get() != null -> return false
}
val dy = lastTouchY - initialTouchY
if (dy == 0) {
// ViewDragHelper tries to capture in onTouch for the ACTION_DOWN event, but there's
// really no way to check for a scrolling child without a direction, so wait.
return false
}
if (state == STATE_COLLAPSED) {
if (isHideable) {
// Any drag should capture in order to expand or hide the sheet
return true
}
if (dy < 0) {
// Expand on upward movement, even if there's scrolling content underneath
return true
}
}
// Check for scrolling content underneath the touch point that can scroll in the
// appropriate direction.
val scrollingChild = findScrollingChildUnder(child, lastTouchX, lastTouchY, -dy)
return scrollingChild == null
}
private fun findScrollingChildUnder(view: View, x: Int, y: Int, direction: Int): View? {
if (view.visibility == View.VISIBLE && dragHelper.isViewUnder(view, x, y)) {
if (view.canScrollVertically(direction)) {
return view
}
if (view is ViewGroup) {
// TODO this doesn't account for elevation or child drawing order.
for (i in (view.childCount - 1) downTo 0) {
val child = view.getChildAt(i)
val found =
findScrollingChildUnder(child, x - child.left, y - child.top, direction)
if (found != null) {
return found
}
}
}
}
return null
}
override fun getViewVerticalDragRange(child: View): Int {
return if (isHideable) parentHeight else collapsedOffset
}
override fun clampViewPositionVertical(child: View, top: Int, dy: Int): Int {
val maxOffset = if (isHideable) parentHeight else collapsedOffset
return top.coerceIn(getExpandedOffset(), maxOffset)
}
override fun clampViewPositionHorizontal(child: View, left: Int, dx: Int) = child.left
override fun onViewDragStateChanged(state: Int) {
if (state == ViewDragHelper.STATE_DRAGGING) {
setStateInternal(STATE_DRAGGING)
}
}
override fun onViewPositionChanged(child: View, left: Int, top: Int, dx: Int, dy: Int) {
dispatchOnSlide(top)
}
override fun onViewReleased(releasedChild: View, xvel: Float, yvel: Float) {
settleBottomSheet(releasedChild, yvel, false)
}
}
/** SavedState implementation */
internal class SavedState : AbsSavedState {
@State internal val state: Int
internal val peekHeight: Int
internal val isFitToContents: Boolean
internal val isHideable: Boolean
internal val skipCollapsed: Boolean
internal val isDraggable: Boolean
constructor(source: Parcel) : this(source, null)
constructor(source: Parcel, loader: ClassLoader?) : super(source, loader) {
state = source.readInt()
peekHeight = source.readInt()
isFitToContents = source.readBooleanUsingCompat()
isHideable = source.readBooleanUsingCompat()
skipCollapsed = source.readBooleanUsingCompat()
isDraggable = source.readBooleanUsingCompat()
}
constructor(
superState: Parcelable,
@State state: Int,
peekHeight: Int,
isFitToContents: Boolean,
isHideable: Boolean,
skipCollapsed: Boolean,
isDraggable: Boolean
) : super(superState) {
this.state = state
this.peekHeight = peekHeight
this.isFitToContents = isFitToContents
this.isHideable = isHideable
this.skipCollapsed = skipCollapsed
this.isDraggable = isDraggable
}
override fun writeToParcel(dest: Parcel, flags: Int) {
super.writeToParcel(dest, flags)
dest.apply {
writeInt(state)
writeInt(peekHeight)
writeBooleanUsingCompat(isFitToContents)
writeBooleanUsingCompat(isHideable)
writeBooleanUsingCompat(skipCollapsed)
writeBooleanUsingCompat(isDraggable)
}
}
companion object {
@JvmField
val CREATOR: Parcelable.Creator<SavedState> =
object : Parcelable.ClassLoaderCreator<SavedState> {
override fun createFromParcel(source: Parcel): SavedState {
return SavedState(source, null)
}
override fun createFromParcel(source: Parcel, loader: ClassLoader): SavedState {
return SavedState(source, loader)
}
override fun newArray(size: Int): Array<SavedState?> {
return arrayOfNulls(size)
}
}
}
}
}
| apache-2.0 |
apollographql/apollo-android | apollo-gradle-plugin/src/test/kotlin/com/apollographql/apollo3/gradle/test/MultiServicesTests.kt | 1 | 2640 | package com.apollographql.apollo3.gradle.test
import com.apollographql.apollo3.gradle.util.TestUtils
import com.apollographql.apollo3.gradle.util.TestUtils.withProject
import com.apollographql.apollo3.gradle.util.generatedChild
import org.gradle.testkit.runner.UnexpectedBuildFailure
import org.hamcrest.CoreMatchers.containsString
import org.hamcrest.MatcherAssert
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.Test
import java.io.File
class MultiServicesTests {
private fun withMultipleServicesProject(apolloConfiguration: String, block: (File) -> Unit) {
withProject(usesKotlinDsl = false,
plugins = listOf(TestUtils.kotlinJvmPlugin, TestUtils.apolloPlugin),
apolloConfiguration = apolloConfiguration) { dir ->
val source = TestUtils.fixturesDirectory()
val target = File(dir, "src/main/graphql/githunt")
File(source, "githunt").copyRecursively(target = target, overwrite = true)
File(dir, "src/main/graphql/com").copyRecursively(target = File(dir, "src/main/graphql/starwars"), overwrite = true)
File(dir, "src/main/graphql/com").deleteRecursively()
block(dir)
}
}
@Test
fun `multiple schema files in different folders throw an error`() {
val apolloConfiguration = """
apollo {
packageNamesFromFilePaths()
}
""".trimIndent()
withMultipleServicesProject(apolloConfiguration) { dir ->
try {
TestUtils.executeTask("generateApolloSources", dir)
fail("expected to fail")
} catch (e: UnexpectedBuildFailure) {
MatcherAssert.assertThat(
e.message,
containsString("Multiple schemas found")
)
}
}
}
@Test
fun `can specify services explicitly`() {
val apolloConfiguration = """
apollo {
service("starwars") {
packageName.set("starwars")
srcDir("src/main/graphql/starwars")
}
service("githunt") {
packageName.set("githunt")
srcDir("src/main/graphql/githunt")
}
}
""".trimIndent()
withMultipleServicesProject(apolloConfiguration) { dir ->
TestUtils.executeTask("build", dir)
assertTrue(dir.generatedChild("starwars/starwars/DroidDetailsQuery.kt").isFile)
assertTrue(dir.generatedChild("starwars/starwars/FilmsQuery.kt").isFile)
assertTrue(dir.generatedChild("starwars/starwars/fragment/SpeciesInformation.kt").isFile)
assertTrue(dir.generatedChild("githunt/githunt/FeedQuery.kt").isFile)
assertTrue(dir.generatedChild("githunt/githunt/fragment/RepositoryFragment.kt").isFile)
}
}
}
| mit |
JetBrains/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/repl/AbstractIdeReplCompletionTest.kt | 1 | 3438 | // 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.repl
import com.intellij.codeInsight.completion.CompletionType
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.util.Ref
import com.intellij.psi.PsiDocumentManager
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.util.ThrowableRunnable
import org.jetbrains.kotlin.console.KotlinConsoleKeeper
import org.jetbrains.kotlin.console.KotlinConsoleRunner
import org.jetbrains.kotlin.idea.completion.test.KotlinFixtureCompletionBaseTestCase
import org.jetbrains.kotlin.idea.completion.test.testCompletion
import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.jetbrains.kotlin.idea.test.runAll
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.idea.test.KotlinTestUtils.allowProjectRootAccess
import org.jetbrains.kotlin.idea.test.KotlinTestUtils.disposeVfsRootAccess
import java.io.File
abstract class AbstractIdeReplCompletionTest : KotlinFixtureCompletionBaseTestCase() {
private var vfsDisposable: Ref<Disposable>? = null
private var consoleRunner: KotlinConsoleRunner? = null
override fun setUp() {
super.setUp()
vfsDisposable = allowProjectRootAccess(this)
consoleRunner = KotlinConsoleKeeper.getInstance(project).run(module)!!
ScriptConfigurationManager.updateScriptDependenciesSynchronously(consoleRunner!!.consoleFile)
}
override fun tearDown() {
runAll(
ThrowableRunnable { disposeVfsRootAccess(vfsDisposable) },
ThrowableRunnable {
consoleRunner?.dispose()
consoleRunner = null
},
ThrowableRunnable { super.tearDown() }
)
}
override fun getPlatform() = JvmPlatforms.unspecifiedJvmPlatform
override fun defaultCompletionType() = CompletionType.BASIC
override fun doTest(testPath: String) {
val runner = consoleRunner!!
val file = File(testPath)
val lines = file.readLines()
lines.prefixedWith(">> ").forEach { runner.successfulLine(it) } // not actually executing anything, only simulating
val codeSample = lines.prefixedWith("-- ").joinToString("\n")
runWriteAction {
val editor = runner.consoleView.editorDocument
editor.setText(codeSample)
FileDocumentManager.getInstance().saveDocument(runner.consoleView.editorDocument)
PsiDocumentManager.getInstance(project).commitAllDocuments()
}
myFixture.configureFromExistingVirtualFile(runner.consoleFile.virtualFile)
myFixture.editor.caretModel.moveToOffset(myFixture.editor.document.getLineEndOffset(0))
testCompletion(file.readText(), getPlatform(), { completionType, count -> myFixture.complete(completionType, count) })
}
private fun List<String>.prefixedWith(prefix: String) = filter { it.startsWith(prefix) }.map { it.removePrefix(prefix) }
override fun getProjectDescriptor(): LightProjectDescriptor = KotlinWithJdkAndRuntimeLightProjectDescriptor.getInstanceFullJdk()
} | apache-2.0 |
allotria/intellij-community | uast/uast-java/src/org/jetbrains/uast/java/declarations/JavaUImportStatement.kt | 4 | 1539 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.java
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiImportStatementBase
import com.intellij.psi.ResolveResult
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UImportStatement
import org.jetbrains.uast.UMultiResolvable
class JavaUImportStatement(
override val sourcePsi: PsiImportStatementBase,
uastParent: UElement?
) : JavaAbstractUElement(uastParent), UImportStatement, UMultiResolvable {
override val isOnDemand: Boolean
get() = sourcePsi.isOnDemand
override val importReference: JavaDumbUElement? by lz { sourcePsi.importReference?.let { JavaDumbUElement(it, this, it.qualifiedName) } }
override fun resolve(): PsiElement? = sourcePsi.resolve()
override fun multiResolve(): Iterable<ResolveResult> =
sourcePsi.importReference?.multiResolve(false)?.asIterable() ?: emptyList()
@Suppress("OverridingDeprecatedMember")
override val psi get() = sourcePsi
} | apache-2.0 |
lomza/screenlookcount | app/src/main/java/com/totemsoft/screenlookcount/fragment/about/AboutPresenter.kt | 1 | 777 | package com.totemsoft.screenlookcount.fragment.about
import android.content.Context
import android.content.Intent
import android.net.Uri
import com.totemsoft.screenlookcount.BasePresenter
import com.totemsoft.screenlookcount.R
/**
* Presenter for About fragment
*
* @author Antonina
*/
class AboutPresenter : BasePresenter<AboutContract.View>(), AboutContract.Presenter {
override fun contactMe(context: Context) {
val contactIntent = Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", context.getString(R.string.about_email_to), null))
contactIntent.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.about_email_subject))
context.startActivity(Intent.createChooser(contactIntent, context.getString(R.string.email_chooser)))
}
} | gpl-3.0 |
ursjoss/sipamato | public/public-web/src/integration-test/kotlin/ch/difty/scipamato/publ/config/ScipamatoPropertiesIntegrationTest.kt | 2 | 1053 | package ch.difty.scipamato.publ.config
import ch.difty.scipamato.publ.AbstractIntegrationTest
import org.amshove.kluent.shouldBeEqualTo
import org.amshove.kluent.shouldBeFalse
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
internal class ScipamatoPropertiesIntegrationTest : AbstractIntegrationTest() {
@Autowired
private lateinit var sp: ScipamatoProperties
@Test
fun brand_hasDefaultValue() {
sp.brand shouldBeEqualTo "SciPaMaTo"
}
@Test
fun defaultLocalization_hasDefaultEnglish() {
sp.defaultLocalization shouldBeEqualTo "de"
}
@Test
fun pubmedBaseUrl_hasDefaultValue() {
sp.pubmedBaseUrl shouldBeEqualTo "https://www.ncbi.nlm.nih.gov/pubmed/"
}
@Test
fun responsiveIFrameSupport_isDisabled() {
sp.responsiveIframeSupportEnabled.shouldBeFalse()
}
@Test
fun multiSelectBoxActionBoxWithMoreEntriesThan_hasDefault4() {
sp.multiSelectBoxActionBoxWithMoreEntriesThan shouldBeEqualTo 4
}
}
| gpl-3.0 |
android/wear-os-samples | ComposeStarter/app/src/main/java/com/example/android/wearable/composestarter/presentation/theme/WearAppTheme.kt | 1 | 1124 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.wearable.composestarter.presentation.theme
import androidx.compose.runtime.Composable
import androidx.wear.compose.material.MaterialTheme
@Composable
fun WearAppTheme(
content: @Composable () -> Unit
) {
MaterialTheme(
colors = wearColorPalette,
typography = Typography,
// For shapes, we generally recommend using the default Material Wear shapes which are
// optimized for round and non-round devices.
content = content
)
}
| apache-2.0 |
deadpixelsociety/roto-ld34 | core/src/com/thedeadpixelsociety/ld34/Extensions.kt | 1 | 537 | package com.thedeadpixelsociety.ld34
import com.badlogic.ashley.core.Component
import com.badlogic.ashley.core.Entity
import com.badlogic.gdx.physics.box2d.Shape
import com.badlogic.gdx.utils.Disposable
fun <T : Disposable> T.using(func: (T) -> Unit) {
try {
func(this)
} finally {
dispose()
}
}
fun <T : Shape> T.using(func: (T) -> Unit) {
try {
func(this)
} finally {
dispose()
}
}
fun <C : Component> Entity.has(componentType: Class<C>) = getComponent(componentType) != null | mit |
matrix-org/matrix-android-sdk | matrix-sdk-crypto/src/main/java/org/matrix/androidsdk/crypto/interfaces/CryptoEventListener.kt | 1 | 795 | /*
* Copyright 2018 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.matrix.androidsdk.crypto.interfaces
interface CryptoEventListener {
fun onToDeviceEvent(event: CryptoEvent)
fun onLiveEvent(event: CryptoEvent, roomState: CryptoRoomState)
}
| apache-2.0 |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/common/src/internal/LockFreeTaskQueue.kt | 1 | 13602 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.internal
import kotlinx.atomicfu.*
import kotlinx.coroutines.*
import kotlin.jvm.*
private typealias Core<E> = LockFreeTaskQueueCore<E>
/**
* Lock-free Multiply-Producer xxx-Consumer Queue for task scheduling purposes.
*
* **Note 1: This queue is NOT linearizable. It provides only quiescent consistency for its operations.**
* However, this guarantee is strong enough for task-scheduling purposes.
* In particular, the following execution is permitted for this queue, but is not permitted for a linearizable queue:
*
* ```
* Thread 1: addLast(1) = true, removeFirstOrNull() = null
* Thread 2: addLast(2) = 2 // this operation is concurrent with both operations in the first thread
* ```
*
* **Note 2: When this queue is used with multiple consumers (`singleConsumer == false`) this it is NOT lock-free.**
* In particular, consumer spins until producer finishes its operation in the case of near-empty queue.
* It is a very short window that could manifest itself rarely and only under specific load conditions,
* but it still deprives this algorithm of its lock-freedom.
*/
internal open class LockFreeTaskQueue<E : Any>(
singleConsumer: Boolean // true when there is only a single consumer (slightly faster & lock-free)
) {
private val _cur = atomic(Core<E>(Core.INITIAL_CAPACITY, singleConsumer))
// Note: it is not atomic w.r.t. remove operation (remove can transiently fail when isEmpty is false)
val isEmpty: Boolean get() = _cur.value.isEmpty
val size: Int get() = _cur.value.size
fun close() {
_cur.loop { cur ->
if (cur.close()) return // closed this copy
_cur.compareAndSet(cur, cur.next()) // move to next
}
}
fun addLast(element: E): Boolean {
_cur.loop { cur ->
when (cur.addLast(element)) {
Core.ADD_SUCCESS -> return true
Core.ADD_CLOSED -> return false
Core.ADD_FROZEN -> _cur.compareAndSet(cur, cur.next()) // move to next
}
}
}
@Suppress("UNCHECKED_CAST")
fun removeFirstOrNull(): E? {
_cur.loop { cur ->
val result = cur.removeFirstOrNull()
if (result !== Core.REMOVE_FROZEN) return result as E?
_cur.compareAndSet(cur, cur.next())
}
}
// Used for validation in tests only
fun <R> map(transform: (E) -> R): List<R> = _cur.value.map(transform)
// Used for validation in tests only
fun isClosed(): Boolean = _cur.value.isClosed()
}
/**
* Lock-free Multiply-Producer xxx-Consumer Queue core.
* @see LockFreeTaskQueue
*/
internal class LockFreeTaskQueueCore<E : Any>(
private val capacity: Int,
private val singleConsumer: Boolean // true when there is only a single consumer (slightly faster)
) {
private val mask = capacity - 1
private val _next = atomic<Core<E>?>(null)
private val _state = atomic(0L)
private val array = atomicArrayOfNulls<Any?>(capacity)
init {
check(mask <= MAX_CAPACITY_MASK)
check(capacity and mask == 0)
}
// Note: it is not atomic w.r.t. remove operation (remove can transiently fail when isEmpty is false)
val isEmpty: Boolean get() = _state.value.withState { head, tail -> head == tail }
val size: Int get() = _state.value.withState { head, tail -> (tail - head) and MAX_CAPACITY_MASK }
fun close(): Boolean {
_state.update { state ->
if (state and CLOSED_MASK != 0L) return true // ok - already closed
if (state and FROZEN_MASK != 0L) return false // frozen -- try next
state or CLOSED_MASK // try set closed bit
}
return true
}
// ADD_CLOSED | ADD_FROZEN | ADD_SUCCESS
fun addLast(element: E): Int {
_state.loop { state ->
if (state and (FROZEN_MASK or CLOSED_MASK) != 0L) return state.addFailReason() // cannot add
state.withState { head, tail ->
val mask = this.mask // manually move instance field to local for performance
// If queue is Single-Consumer then there could be one element beyond head that we cannot overwrite,
// so we check for full queue with an extra margin of one element
if ((tail + 2) and mask == head and mask) return ADD_FROZEN // overfull, so do freeze & copy
// If queue is Multi-Consumer then the consumer could still have not cleared element
// despite the above check for one free slot.
if (!singleConsumer && array[tail and mask].value != null) {
// There are two options in this situation
// 1. Spin-wait until consumer clears the slot
// 2. Freeze & resize to avoid spinning
// We use heuristic here to avoid memory-overallocation
// Freeze & reallocate when queue is small or more than half of the queue is used
if (capacity < MIN_ADD_SPIN_CAPACITY || (tail - head) and MAX_CAPACITY_MASK > capacity shr 1) {
return ADD_FROZEN
}
// otherwise spin
return@loop
}
val newTail = (tail + 1) and MAX_CAPACITY_MASK
if (_state.compareAndSet(state, state.updateTail(newTail))) {
// successfully added
array[tail and mask].value = element
// could have been frozen & copied before this item was set -- correct it by filling placeholder
var cur = this
while(true) {
if (cur._state.value and FROZEN_MASK == 0L) break // all fine -- not frozen yet
cur = cur.next().fillPlaceholder(tail, element) ?: break
}
return ADD_SUCCESS // added successfully
}
}
}
}
private fun fillPlaceholder(index: Int, element: E): Core<E>? {
val old = array[index and mask].value
/*
* addLast actions:
* 1) Commit tail slot
* 2) Write element to array slot
* 3) Check for array copy
*
* If copy happened between 2 and 3 then the consumer might have consumed our element,
* then another producer might have written its placeholder in our slot, so we should
* perform *unique* check that current placeholder is our to avoid overwriting another producer placeholder
*/
if (old is Placeholder && old.index == index) {
array[index and mask].value = element
// we've corrected missing element, should check if that propagated to further copies, just in case
return this
}
// it is Ok, no need for further action
return null
}
// REMOVE_FROZEN | null (EMPTY) | E (SUCCESS)
fun removeFirstOrNull(): Any? {
_state.loop { state ->
if (state and FROZEN_MASK != 0L) return REMOVE_FROZEN // frozen -- cannot modify
state.withState { head, tail ->
if ((tail and mask) == (head and mask)) return null // empty
val element = array[head and mask].value
if (element == null) {
// If queue is Single-Consumer, then element == null only when add has not finished yet
if (singleConsumer) return null // consider it not added yet
// retry (spin) until consumer adds it
return@loop
}
// element == Placeholder can only be when add has not finished yet
if (element is Placeholder) return null // consider it not added yet
// we cannot put null into array here, because copying thread could replace it with Placeholder and that is a disaster
val newHead = (head + 1) and MAX_CAPACITY_MASK
if (_state.compareAndSet(state, state.updateHead(newHead))) {
// Array could have been copied by another thread and it is perfectly fine, since only elements
// between head and tail were copied and there are no extra steps we should take here
array[head and mask].value = null // now can safely put null (state was updated)
return element // successfully removed in fast-path
}
// Multi-Consumer queue must retry this loop on CAS failure (another consumer might have removed element)
if (!singleConsumer) return@loop
// Single-consumer queue goes to slow-path for remove in case of interference
var cur = this
while (true) {
@Suppress("UNUSED_VALUE")
cur = cur.removeSlowPath(head, newHead) ?: return element
}
}
}
}
private fun removeSlowPath(oldHead: Int, newHead: Int): Core<E>? {
_state.loop { state ->
state.withState { head, _ ->
assert { head == oldHead } // "This queue can have only one consumer"
if (state and FROZEN_MASK != 0L) {
// state was already frozen, so removed element was copied to next
return next() // continue to correct head in next
}
if (_state.compareAndSet(state, state.updateHead(newHead))) {
array[head and mask].value = null // now can safely put null (state was updated)
return null
}
}
}
}
fun next(): LockFreeTaskQueueCore<E> = allocateOrGetNextCopy(markFrozen())
private fun markFrozen(): Long =
_state.updateAndGet { state ->
if (state and FROZEN_MASK != 0L) return state // already marked
state or FROZEN_MASK
}
private fun allocateOrGetNextCopy(state: Long): Core<E> {
_next.loop { next ->
if (next != null) return next // already allocated & copied
_next.compareAndSet(null, allocateNextCopy(state))
}
}
private fun allocateNextCopy(state: Long): Core<E> {
val next = LockFreeTaskQueueCore<E>(capacity * 2, singleConsumer)
state.withState { head, tail ->
var index = head
while (index and mask != tail and mask) {
// replace nulls with placeholders on copy
val value = array[index and mask].value ?: Placeholder(index)
next.array[index and next.mask].value = value
index++
}
next._state.value = state wo FROZEN_MASK
}
return next
}
// Used for validation in tests only
fun <R> map(transform: (E) -> R): List<R> {
val res = ArrayList<R>(capacity)
_state.value.withState { head, tail ->
var index = head
while (index and mask != tail and mask) {
// replace nulls with placeholders on copy
val element = array[index and mask].value
@Suppress("UNCHECKED_CAST")
if (element != null && element !is Placeholder) res.add(transform(element as E))
index++
}
}
return res
}
// Used for validation in tests only
fun isClosed(): Boolean = _state.value and CLOSED_MASK != 0L
// Instance of this class is placed into array when we have to copy array, but addLast is in progress --
// it had already reserved a slot in the array (with null) and have not yet put its value there.
// Placeholder keeps the actual index (not masked) to distinguish placeholders on different wraparounds of array
// Internal because of inlining
internal class Placeholder(@JvmField val index: Int)
@Suppress("PrivatePropertyName", "MemberVisibilityCanBePrivate")
internal companion object {
const val INITIAL_CAPACITY = 8
const val CAPACITY_BITS = 30
const val MAX_CAPACITY_MASK = (1 shl CAPACITY_BITS) - 1
const val HEAD_SHIFT = 0
const val HEAD_MASK = MAX_CAPACITY_MASK.toLong() shl HEAD_SHIFT
const val TAIL_SHIFT = HEAD_SHIFT + CAPACITY_BITS
const val TAIL_MASK = MAX_CAPACITY_MASK.toLong() shl TAIL_SHIFT
const val FROZEN_SHIFT = TAIL_SHIFT + CAPACITY_BITS
const val FROZEN_MASK = 1L shl FROZEN_SHIFT
const val CLOSED_SHIFT = FROZEN_SHIFT + 1
const val CLOSED_MASK = 1L shl CLOSED_SHIFT
const val MIN_ADD_SPIN_CAPACITY = 1024
@JvmField val REMOVE_FROZEN = Symbol("REMOVE_FROZEN")
const val ADD_SUCCESS = 0
const val ADD_FROZEN = 1
const val ADD_CLOSED = 2
infix fun Long.wo(other: Long) = this and other.inv()
fun Long.updateHead(newHead: Int) = (this wo HEAD_MASK) or (newHead.toLong() shl HEAD_SHIFT)
fun Long.updateTail(newTail: Int) = (this wo TAIL_MASK) or (newTail.toLong() shl TAIL_SHIFT)
inline fun <T> Long.withState(block: (head: Int, tail: Int) -> T): T {
val head = ((this and HEAD_MASK) shr HEAD_SHIFT).toInt()
val tail = ((this and TAIL_MASK) shr TAIL_SHIFT).toInt()
return block(head, tail)
}
// FROZEN | CLOSED
fun Long.addFailReason(): Int = if (this and CLOSED_MASK != 0L) ADD_CLOSED else ADD_FROZEN
}
}
| apache-2.0 |
SmokSmog/smoksmog-android | app/src/main/kotlin/com/antyzero/smoksmog/job/SmokSmogJobService.kt | 1 | 597 | package com.antyzero.smoksmog.job
import com.antyzero.smoksmog.dsl.appComponent
import com.antyzero.smoksmog.ui.widget.StationWidgetService
import com.firebase.jobdispatcher.JobParameters
import com.firebase.jobdispatcher.JobService
class SmokSmogJobService : JobService() {
override fun onCreate() {
super.onCreate()
appComponent().inject(this)
}
override fun onStartJob(job: JobParameters?): Boolean {
StationWidgetService.updateAll(this)
return false
}
override fun onStopJob(job: JobParameters?): Boolean {
return false
}
}
| gpl-3.0 |
agoda-com/Kakao | kakao/src/main/kotlin/com/agoda/kakao/progress/KSeekBar.kt | 1 | 723 | @file:Suppress("unused")
package com.agoda.kakao.progress
import android.view.View
import androidx.test.espresso.DataInteraction
import com.agoda.kakao.common.builders.ViewBuilder
import com.agoda.kakao.common.views.KBaseView
import org.hamcrest.Matcher
/**
* View with SeekBarActions and ProgressBarAssertions
*
* @see SeekBarActions
* @see ProgressBarAssertions
*/
class KSeekBar : KBaseView<KSeekBar>, SeekBarActions, ProgressBarAssertions {
constructor(function: ViewBuilder.() -> Unit) : super(function)
constructor(parent: Matcher<View>, function: ViewBuilder.() -> Unit) : super(parent, function)
constructor(parent: DataInteraction, function: ViewBuilder.() -> Unit) : super(parent, function)
}
| apache-2.0 |
leafclick/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/GHLoadingModel.kt | 1 | 583 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.ui
import java.util.*
interface GHLoadingModel {
val loading: Boolean
val resultAvailable: Boolean
val error: Throwable?
fun addStateChangeListener(listener: StateChangeListener)
fun removeStateChangeListener(listener: StateChangeListener)
interface StateChangeListener : EventListener {
fun onLoadingStarted() {}
fun onLoadingCompleted() {}
fun onReset() {}
}
} | apache-2.0 |
bitsydarel/DBWeather | dbweatherdata/src/main/java/com/dbeginc/dbweatherdata/proxies/remote/lives/RemoteIpTvLive.kt | 1 | 824 | /*
* Copyright (C) 2017 Darel Bitsy
* 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.dbeginc.dbweatherdata.proxies.remote.lives
data class RemoteIpTvLive(
var channelLogo: String? = "",
var channelName: String = "",
var url: String = "",
val playlistId: String
) | gpl-3.0 |
JuliusKunze/kotlin-native | backend.native/tests/external/stdlib/coroutines/SequenceBuilderTest/testYieldAllCollection.kt | 2 | 265 | import kotlin.test.*
import kotlin.coroutines.experimental.buildSequence
import kotlin.coroutines.experimental.buildIterator
fun box() {
val result = buildSequence {
yieldAll(listOf(1, 2, 3))
}
assertEquals(listOf(1, 2, 3), result.toList())
}
| apache-2.0 |
nrkv/HypeAPI | src/main/kotlin/io/nrkv/HypeAPI/task/service/TaskService.kt | 1 | 439 | package io.nrkv.HypeAPI.task.service
import io.nrkv.HypeAPI.task.model.TaskRequest
import io.nrkv.HypeAPI.task.model.TaskResponse
/**
* Created by Ivan Nyrkov on 08/06/17.
*/
interface TaskService {
fun create(task: TaskRequest): TaskResponse
fun getById(taskId: String): TaskResponse?
fun getAll(): List<TaskResponse>
fun update(taskId: String, updatedTask: TaskRequest): TaskResponse?
fun delete(taskId: String)
} | mit |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/ranges/forInIndices/kt13241_CharSequence.kt | 2 | 282 | // WITH_RUNTIME
import kotlin.test.assertEquals
fun test(x: Any): Int {
var sum = 0
if (x is String) {
for (i in x.indices) {
sum = sum * 10 + i
}
}
return sum
}
fun box(): String {
assertEquals(123, test("0000"))
return "OK"
} | apache-2.0 |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/enum/sortEnumEntries.kt | 2 | 318 | // WITH_RUNTIME
import Game.*
enum class Game {
ROCK,
PAPER,
SCISSORS,
LIZARD,
SPOCK
}
fun box(): String {
val a = arrayOf(LIZARD, SCISSORS, SPOCK, ROCK, PAPER)
a.sort()
val str = a.joinToString(" ")
return if (str == "ROCK PAPER SCISSORS LIZARD SPOCK") "OK" else "Fail: $str"
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createFunction/call/kt10983.kt | 4 | 1386 | // "Create function" "false"
// ACTION: Create extension function 'Collection<List<String>>.firstOrNull'
// ACTION: Create extension function 'Unit.equals'
// ACTION: Create local variable 'maximumSizeOfGroup'
// ACTION: Create object 'maximumSizeOfGroup'
// ACTION: Create parameter 'maximumSizeOfGroup'
// ACTION: Create property 'maximumSizeOfGroup'
// ACTION: Introduce local variable
// ACTION: Rename reference
// ACTION: Expand boolean expression to 'if else'
// ERROR: A 'return' expression required in a function with a block body ('{...}')
// ERROR: The expression cannot be a selector (occur after a dot)
// ERROR: Type inference failed: inline fun <T> Iterable<T>.firstOrNull(predicate: (T) -> Boolean): T?<br>cannot be applied to<br>receiver: Collection<List<String>> arguments: ((List<String>) -> () -> Boolean)<br>
// ERROR: Type mismatch: inferred type is (List<String>) -> () -> Boolean but (List<String>) -> Boolean was expected
// ERROR: Unresolved reference: maximumSizeOfGroup
// COMPILER_ARGUMENTS: -XXLanguage:-NewInference
fun doSomethingStrangeWithCollection(collection: Collection<String>): Collection<String>? {
val groupsByLength = collection.groupBy { s -> { s.length } }
val maximumSizeOfGroup = groupsByLength.values.maxByOrNull { it.size }.
return groupsByLength.values.firstOrNull { group -> {group.size == <caret>maximumSizeOfGroup} }
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/safeDelete/deleteTypeParameter/kotlinTypeParameter/subclass1.kt | 13 | 60 | open class A<<caret>X, Y, Z>
class B<T, U>: A<T, String, U> | apache-2.0 |
smmribeiro/intellij-community | python/src/com/jetbrains/python/testing/PyTestsShared.kt | 1 | 37787 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.testing
import com.intellij.execution.*
import com.intellij.execution.actions.ConfigurationContext
import com.intellij.execution.actions.ConfigurationFromContext
import com.intellij.execution.configurations.*
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.execution.testframework.AbstractTestProxy
import com.intellij.execution.testframework.sm.runner.SMRunnerConsolePropertiesProvider
import com.intellij.execution.testframework.sm.runner.SMTRunnerConsoleProperties
import com.intellij.execution.testframework.sm.runner.SMTestLocator
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.module.impl.scopes.ModuleWithDependenciesScope
import com.intellij.openapi.options.SettingsEditor
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.util.JDOMExternalizerUtil.readField
import com.intellij.openapi.util.JDOMExternalizerUtil.writeField
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.Ref
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFileSystemItem
import com.intellij.psi.PsiManager
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.QualifiedName
import com.intellij.refactoring.listeners.RefactoringElementListener
import com.intellij.remote.PathMappingProvider
import com.intellij.remote.RemoteSdkAdditionalData
import com.intellij.util.ThreeState
import com.jetbrains.extensions.*
import com.jetbrains.python.PyBundle
import com.jetbrains.python.packaging.PyPackageManager
import com.jetbrains.python.psi.PyFile
import com.jetbrains.python.psi.PyFunction
import com.jetbrains.python.psi.PyQualifiedNameOwner
import com.jetbrains.python.psi.types.TypeEvalContext
import com.jetbrains.python.run.*
import com.jetbrains.python.run.targetBasedConfiguration.PyRunTargetVariant
import com.jetbrains.python.run.targetBasedConfiguration.TargetWithVariant
import com.jetbrains.python.run.targetBasedConfiguration.createRefactoringListenerIfPossible
import com.jetbrains.python.run.targetBasedConfiguration.targetAsPsiElement
import com.jetbrains.python.sdk.PythonSdkUtil
import com.jetbrains.reflection.DelegationProperty
import com.jetbrains.reflection.Properties
import com.jetbrains.reflection.Property
import com.jetbrains.reflection.getProperties
import jetbrains.buildServer.messages.serviceMessages.ServiceMessage
import jetbrains.buildServer.messages.serviceMessages.TestStdErr
import jetbrains.buildServer.messages.serviceMessages.TestStdOut
import org.jetbrains.annotations.PropertyKey
import org.jetbrains.jps.model.java.JavaSourceRootType
import java.util.regex.Matcher
fun getFactoryById(id: String): PyAbstractTestFactory<*>? =
// user may have "pytest" because it was used instead of py.test (old id) for some time
PythonTestConfigurationType.getInstance().typedFactories.toTypedArray().firstOrNull { it.id == if (id == "pytest") PyTestFactory.id else id }
fun getFactoryByIdOrDefault(id: String): PyAbstractTestFactory<*> = getFactoryById(id)
?: PythonTestConfigurationType.getInstance().autoDetectFactory
/**
* Accepts text that may be wrapped in TC message. Unwraps it and removes TC escape code.
* Regular text is unchanged
*/
fun processTCMessage(text: String): String {
val parsedMessage = ServiceMessage.parse(text.trim()) ?: return text // Not a TC message
return when (parsedMessage) {
is TestStdOut -> parsedMessage.stdOut // TC with stdout
is TestStdErr -> parsedMessage.stdErr // TC with stderr
else -> "" // TC with out of any output
}
}
internal fun getAdditionalArgumentsProperty() = PyAbstractTestConfiguration::additionalArguments
/**
* Checks if element could be test target
* @param testCaseClassRequired see [PythonUnitTestDetectorsBasedOnSettings] docs
*/
fun isTestElement(element: PsiElement, testCaseClassRequired: ThreeState, typeEvalContext: TypeEvalContext): Boolean = when (element) {
is PyFile -> PythonUnitTestDetectorsBasedOnSettings.isTestFile(element, testCaseClassRequired, typeEvalContext)
is PsiDirectory -> isTestFolder(element, testCaseClassRequired, typeEvalContext)
is PyFunction -> PythonUnitTestDetectorsBasedOnSettings.isTestFunction(element,
testCaseClassRequired, typeEvalContext)
is com.jetbrains.python.psi.PyClass -> {
PythonUnitTestDetectorsBasedOnSettings.isTestClass(element, testCaseClassRequired, typeEvalContext)
}
else -> false
}
/**
* If element is a subelement of the folder excplicitly marked as test root -- use it
*/
private fun getExplicitlyConfiguredTestRoot(element: PsiFileSystemItem): VirtualFile? {
val vfDirectory = element.virtualFile
val module = ModuleUtil.findModuleForPsiElement(element) ?: return null
return ModuleRootManager.getInstance(module).getSourceRoots(JavaSourceRootType.TEST_SOURCE).firstOrNull {
VfsUtil.isAncestor(it, vfDirectory, false)
}
}
private fun isTestFolder(element: PsiDirectory,
testCaseClassRequired: ThreeState,
typeEvalContext: TypeEvalContext): Boolean {
return (getExplicitlyConfiguredTestRoot(element) != null) || element.name.contains("test", true) || element.children.any {
it is PyFile && PythonUnitTestDetectorsBasedOnSettings.isTestFile(it, testCaseClassRequired, typeEvalContext)
}
}
/**
* Since runners report names of tests as qualified name, no need to convert it to PSI and back to string.
* We just save its name and provide it again to rerun
* @param metainfo additional info provided by test runner, in case of pytest it is test name with parameters (if test is parametrized)
*/
private class PyTargetBasedPsiLocation(val target: ConfigurationTarget,
element: PsiElement,
val metainfo: String?) : PsiLocation<PsiElement>(element) {
override fun equals(other: Any?): Boolean {
if (other is PyTargetBasedPsiLocation) {
return target == other.target && metainfo == other.metainfo
}
return false
}
override fun hashCode(): Int {
return target.hashCode()
}
}
/**
* @return factory chosen by user in "test runner" settings
*/
private fun findConfigurationFactoryFromSettings(module: Module): ConfigurationFactory =
TestRunnerService.getInstance(module).selectedFactory
// folder provided by python side. Resolve test names versus it
private val PATH_URL = java.util.regex.Pattern.compile("^python<([^<>]+)>$")
private fun Sdk.getMapping(project: Project) = (sdkAdditionalData as? RemoteSdkAdditionalData<*>)?.let { data ->
PathMappingProvider.getSuitableMappingProviders(data).flatMap { it.getPathMappingSettings(project, data).pathMappings }
} ?: emptyList()
private fun getFolderFromMatcher(matcher: Matcher, module: Module): String? {
if (!matcher.matches()) {
return null
}
val folder = matcher.group(1)
val sdk = module.getSdk()
if (sdk != null && PythonSdkUtil.isRemote(sdk)) {
return sdk.getMapping(module.project).find { it.canReplaceRemote(folder) }?.mapToLocal(folder)
}
else {
return folder
}
}
private fun getElementByUrl(protocol: String,
path: String,
module: Module,
evalContext: TypeEvalContext,
matcher: Matcher = PATH_URL.matcher(protocol),
metainfo: String? = null): Location<out PsiElement>? = runReadAction {
val folder = getFolderFromMatcher(matcher, module)?.let { LocalFileSystem.getInstance().findFileByPath(it) }
val qualifiedName = QualifiedName.fromDottedString(path)
// Assume qname id good and resolve it directly
val element = qualifiedName.resolveToElement(QNameResolveContext(ModuleBasedContextAnchor(module),
evalContext = evalContext,
folderToStart = folder,
allowInaccurateResult = true))
if (element != null) {
// Path is qualified name of python test according to runners protocol
// Parentheses are part of generators / parametrized tests
// Until https://github.com/JetBrains/teamcity-messages/issues/121 they are disabled,
// so we cut them out of path not to provide unsupported targets to runners
val pathNoParentheses = QualifiedName.fromComponents(
qualifiedName.components.filter { !it.contains('(') }).toString()
PyTargetBasedPsiLocation(ConfigurationTarget(pathNoParentheses, PyRunTargetVariant.PYTHON), element, metainfo)
}
else {
null
}
}
object PyTestsLocator : SMTestLocator {
override fun getLocation(protocol: String,
path: String,
metainfo: String?,
project: Project,
scope: GlobalSearchScope): List<Location<out PsiElement>> = getLocationInternal(protocol, path, project,
metainfo, scope)
override fun getLocation(protocol: String, path: String, project: Project, scope: GlobalSearchScope): List<Location<out PsiElement>> {
return getLocationInternal(protocol, path, project, null, scope)
}
private fun getLocationInternal(protocol: String,
path: String,
project: Project,
metainfo: String?,
scope: GlobalSearchScope): List<Location<out PsiElement>> {
if (scope !is ModuleWithDependenciesScope) {
return listOf()
}
val matcher = PATH_URL.matcher(protocol)
if (!matcher.matches()) {
// special case: setup.py runner uses unittest configuration but different (old) protocol
// delegate to old protocol locator until setup.py moved to separate configuration
val oldLocation = PythonUnitTestTestIdUrlProvider.INSTANCE.getLocation(protocol, path, project, scope)
if (oldLocation.isNotEmpty()) {
return oldLocation
}
}
return getElementByUrl(protocol, path, scope.module, TypeEvalContext.codeAnalysis(project, null), matcher, metainfo)?.let {
listOf(it)
} ?: listOf()
}
}
abstract class PyTestExecutionEnvironment<T : PyAbstractTestConfiguration>(configuration: T,
environment: ExecutionEnvironment)
: PythonTestCommandLineStateBase<T>(configuration, environment) {
override fun getTestLocator(): SMTestLocator = PyTestsLocator
override fun getTestSpecs(): MutableList<String> = java.util.ArrayList(configuration.getTestSpec())
override fun generateCommandLine(): GeneralCommandLine {
val line = super.generateCommandLine()
line.workDirectory = java.io.File(configuration.workingDirectorySafe)
return line
}
}
abstract class PyAbstractTestSettingsEditor(private val sharedForm: PyTestSharedForm)
: SettingsEditor<PyAbstractTestConfiguration>() {
override fun resetEditorFrom(s: PyAbstractTestConfiguration) {
// usePojoProperties is true because we know that Form is java-based
AbstractPythonRunConfiguration.copyParams(s, sharedForm.optionsForm)
s.copyTo(getProperties(sharedForm, usePojoProperties = true))
}
override fun applyEditorTo(s: PyAbstractTestConfiguration) {
AbstractPythonRunConfiguration.copyParams(sharedForm.optionsForm, s)
s.copyFrom(getProperties(sharedForm, usePojoProperties = true))
}
override fun createEditor(): javax.swing.JComponent = sharedForm.panel
}
/**
* Default target path (run all tests ion project folder)
*/
private const val DEFAULT_PATH = ""
/**
* Target depends on target type. It could be path to file/folder or python target
*/
data class ConfigurationTarget(@ConfigField("runcfg.python_tests.config.target") override var target: String,
@ConfigField(
"runcfg.python_tests.config.targetType") override var targetType: PyRunTargetVariant) : TargetWithVariant {
fun copyTo(dst: ConfigurationTarget) {
// TODO: do we have such method it in Kotlin?
dst.target = target
dst.targetType = targetType
}
/**
* Validates configuration and throws exception if target is invalid
*/
fun checkValid() {
if (targetType != PyRunTargetVariant.CUSTOM && target.isEmpty()) {
throw RuntimeConfigurationWarning(PyBundle.message("python.testing.target.not.provided"))
}
if (targetType == PyRunTargetVariant.PYTHON && !isWellFormed()) {
throw RuntimeConfigurationError(PyBundle.message("python.testing.provide.qualified.name"))
}
}
fun asPsiElement(configuration: PyAbstractTestConfiguration): PsiElement? =
asPsiElement(configuration, configuration.getWorkingDirectoryAsVirtual())
fun generateArgumentsLine(configuration: PyAbstractTestConfiguration): List<String> =
when (targetType) {
PyRunTargetVariant.CUSTOM -> emptyList()
PyRunTargetVariant.PYTHON -> getArgumentsForPythonTarget(configuration)
PyRunTargetVariant.PATH -> listOf("--path", target.trim())
}
private fun getArgumentsForPythonTarget(configuration: PyAbstractTestConfiguration): List<String> = runReadAction ra@{
val element = asPsiElement(configuration) ?: throw ExecutionException(PyBundle.message("python.testing.cant.resolve", target))
if (element is PsiDirectory) {
// Directory is special case: we can't run it as package for now, so we run it as path
return@ra listOf("--path", element.virtualFile.path)
}
val context = TypeEvalContext.userInitiated(configuration.project, null)
val qNameResolveContext = QNameResolveContext(
contextAnchor = ModuleBasedContextAnchor(configuration.module!!),
evalContext = context,
folderToStart = LocalFileSystem.getInstance().findFileByPath(configuration.workingDirectorySafe),
allowInaccurateResult = true
)
val qualifiedNameParts = QualifiedName.fromDottedString(target.trim()).tryResolveAndSplit(qNameResolveContext)
?: throw ExecutionException(PyBundle.message("python.testing.cant.find.where.declared", target))
// We can't provide element qname here: it may point to parent class in case of inherited functions,
// so we make fix file part, but obey element(symbol) part of qname
if (!configuration.shouldSeparateTargetPath()) {
// Here generate qname instead of file/path::element_name
// Try to set path relative to work dir (better than path from closest root)
// If we can resolve element by this path relative to working directory then use it
val qNameInsideOfDirectory = qualifiedNameParts.getElementNamePrependingFile()
val elementAndName = qNameInsideOfDirectory.getElementAndResolvableName(qNameResolveContext.copy(allowInaccurateResult = false))
if (elementAndName != null) {
// qNameInsideOfDirectory may contain redundant elements like subtests so we use name that was really resolved
// element.qname can't be used because inherited test resolves to parent
return@ra generatePythonTarget(elementAndName.name.toString(), configuration)
}
// Use "full" (path from closest root) otherwise
val name = (element.containingFile as? PyFile)?.getQName()?.append(qualifiedNameParts.elementName) ?: throw ExecutionException(
PyBundle.message("python.testing.cant.get.importable.name", element.containingFile))
return@ra generatePythonTarget(name.toString(), configuration)
}
else {
// Here generate file/path::element_name
val pyTarget = qualifiedNameParts.elementName
val elementFile = element.containingFile.virtualFile
val workingDir = elementFile.fileSystem.findFileByPath(configuration.workingDirectorySafe)
val fileSystemPartOfTarget = (if (workingDir != null) VfsUtil.getRelativePath(elementFile, workingDir)
else null)
?: elementFile.path
if (pyTarget.componentCount == 0) {
// If python part is empty we are launching file. To prevent junk like "foo.py::" we run it as file instead
return@ra listOf("--path", fileSystemPartOfTarget)
}
return@ra generatePythonTarget("$fileSystemPartOfTarget::$pyTarget", configuration)
}
}
private fun generatePythonTarget(target: String, configuration: PyAbstractTestConfiguration) =
listOf("--target", target + configuration.pythonTargetAdditionalParams)
/**
* @return directory which target is situated
*/
fun getElementDirectory(configuration: PyAbstractTestConfiguration): VirtualFile? {
if (target == DEFAULT_PATH) {
//This means "current directory", so we do not know where is it
// getting vitualfile for it may return PyCharm working directory which is not what we want
return null
}
val fileOrDir = asVirtualFile() ?: asPsiElement(configuration)?.containingFile?.virtualFile ?: return null
return if (fileOrDir.isDirectory) fileOrDir else fileOrDir.parent
}
}
/**
* To prevent legacy configuration options from clashing with new names, we add prefix
* to use for writing/reading xml
*/
private val Property.prefixedName: String
get() = "_new_" + this.getName()
/**
* "Custom symbol" is mode when test runner uses [PyRunTargetVariant.CUSTOM] and has
* [PyAbstractTestConfiguration.additionalArguments] that points to some symbol inside of file i.e.:
* ``/foo/bar.py::SomeTest.some_method``
*
* This mode is framework-specific.
* It is used for cases like ``PY-25586``
*/
internal interface PyTestConfigurationWithCustomSymbol {
/**
* Separates file part and symbol
*/
val fileSymbolSeparator: String
/**
* Separates parts of symbol name
*/
val symbolSymbolSeparator: String
fun createAdditionalArguments(parts: QualifiedNameParts) = with(parts) {
file.virtualFile.path + fileSymbolSeparator + elementName.components.joinToString(symbolSymbolSeparator)
}
}
/**
* Parent of all new test configurations.
* All config-specific fields are implemented as properties. They are saved/restored automatically and passed to GUI form.
*
*/
abstract class PyAbstractTestConfiguration(project: Project,
private val testFactory: PyAbstractTestFactory<*>)
: AbstractPythonTestRunConfiguration<PyAbstractTestConfiguration>(project, testFactory, testFactory.packageRequired), PyRerunAwareConfiguration,
RefactoringListenerProvider, SMRunnerConsolePropertiesProvider {
override fun createTestConsoleProperties(executor: Executor): SMTRunnerConsoleProperties =
PythonTRunnerConsoleProperties(this, executor, true, PyTestsLocator).also { properties ->
if (isIdTestBased) properties.makeIdTestBased()
}
/**
* Additional parameters added to the test name for parametrized tests
*/
open val pythonTargetAdditionalParams: String = ""
/**
* Args after it passed to test runner itself
*/
protected val rawArgumentsSeparator = "--"
@DelegationProperty
val target: ConfigurationTarget = ConfigurationTarget(DEFAULT_PATH, PyRunTargetVariant.PATH)
@ConfigField("runcfg.python_tests.config.additionalArguments")
var additionalArguments: String = ""
val testFrameworkName: String = testFactory.name
fun isTestClassRequired(): ThreeState {
val sdk = sdk ?: return ThreeState.UNSURE
return if (testFactory.onlyClassesAreSupported(sdk)) {
ThreeState.YES
}
else {
ThreeState.NO
}
}
/**
* For real launch use [getWorkingDirectorySafe] instead
*/
internal fun getWorkingDirectoryAsVirtual(): VirtualFile? {
if (!workingDirectory.isNullOrEmpty()) {
return LocalFileSystem.getInstance().findFileByPath(workingDirectory)
}
return null
}
override fun getWorkingDirectorySafe(): String {
val dirProvidedByUser = super.getWorkingDirectory()
if (!dirProvidedByUser.isNullOrEmpty()) {
return dirProvidedByUser
}
return ApplicationManager.getApplication().runReadAction<String> {
target.getElementDirectory(this)?.path ?: super.getWorkingDirectorySafe()
}
}
override fun getRefactoringElementListener(element: PsiElement?): RefactoringElementListener? {
if (element == null) return null
var renamer = CompositeRefactoringElementListener(PyWorkingDirectoryRenamer(getWorkingDirectoryAsVirtual(), this))
createRefactoringListenerIfPossible(element, target.asPsiElement(this), target.asVirtualFile(), { target.target = it })?.let {
renamer = renamer.plus(it)
}
return renamer
}
override fun checkConfiguration() {
super.checkConfiguration()
target.checkValid()
}
override fun isIdTestBased(): Boolean = true
private fun getPythonTestSpecByLocation(location: Location<*>): List<String> {
if (location is PyTargetBasedPsiLocation) {
return location.target.generateArgumentsLine(this)
}
if (location !is PsiLocation) {
return emptyList()
}
if (location.psiElement !is PyQualifiedNameOwner) {
return emptyList()
}
val qualifiedName = (location.psiElement as PyQualifiedNameOwner).qualifiedName ?: return emptyList()
// Resolve name as python qname as last resort
return ConfigurationTarget(qualifiedName, PyRunTargetVariant.PYTHON).generateArgumentsLine(this)
}
final override fun getTestSpec(location: Location<*>,
failedTest: AbstractTestProxy): String? {
val list = getPythonTestSpecByLocation(location)
if (list.isEmpty()) {
return null
}
else {
return list.joinToString(" ")
}
}
override fun getTestSpecsForRerun(scope: com.intellij.psi.search.GlobalSearchScope,
locations: MutableList<Pair<Location<*>, AbstractTestProxy>>): List<String> {
val result = java.util.ArrayList<String>()
// Set used to remove duplicate targets
locations.map { it.first }.distinctBy { it.psiElement }.map { getPythonTestSpecByLocation(it) }.forEach {
result.addAll(it)
}
return result + generateRawArguments(true)
}
fun getTestSpec(): List<String> = target.generateArgumentsLine(this) + generateRawArguments()
/**
* raw arguments to be added after "--" and passed to runner directly
*/
private fun generateRawArguments(forRerun: Boolean = false): List<String> {
val rawArguments = additionalArguments + " " + getCustomRawArgumentsString(forRerun)
if (rawArguments.isNotBlank()) {
return listOf(rawArgumentsSeparator) + com.intellij.util.execution.ParametersListUtil.parse(rawArguments, false, true)
}
return emptyList()
}
/**
* If true, then framework name must be used as part of the run configuration name i.e "pytest: spam.eggs"
*/
protected open val useFrameworkNameInConfiguration = true
override fun suggestedName(): String {
val testFrameworkName = if (useFrameworkNameInConfiguration) testFrameworkName else PyBundle.message("runcfg.test.display_name")
return when (target.targetType) {
PyRunTargetVariant.PATH -> {
val name = target.asVirtualFile()?.name
PyBundle.message("runcfg.test.suggest.name.in.path", testFrameworkName, (name ?: target.target))
}
PyRunTargetVariant.PYTHON -> {
PyBundle.message("runcfg.test.suggest.name.in.python", testFrameworkName, target.target)
}
else -> {
testFrameworkName
}
}
}
/**
* @return configuration-specific arguments
*/
protected open fun getCustomRawArgumentsString(forRerun: Boolean = false): String = ""
fun reset() {
target.target = DEFAULT_PATH
target.targetType = PyRunTargetVariant.PATH
additionalArguments = ""
}
fun copyFrom(src: Properties) {
src.copyTo(getConfigFields())
}
fun copyTo(dst: Properties) {
getConfigFields().copyTo(dst)
}
override fun writeExternal(element: org.jdom.Element) {
super.writeExternal(element)
val gson = com.google.gson.Gson()
getConfigFields().properties.forEach {
val value = it.get()
if (value != null) {
// No need to write null since null is default value
writeField(element, it.prefixedName, gson.toJson(value))
}
}
}
override fun readExternal(element: org.jdom.Element) {
super.readExternal(element)
val gson = com.google.gson.Gson()
getConfigFields().properties.forEach {
val fromJson: Any? = gson.fromJson(readField(element, it.prefixedName), it.getType())
if (fromJson != null) {
it.set(fromJson)
}
}
}
private fun getConfigFields() = getProperties(this, ConfigField::class.java)
/**
* Checks if element could be test target for this config.
* Function is used to create tests by context.
*
* If yes, and element is [PsiElement] then it is [PyRunTargetVariant.PYTHON].
* If file then [PyRunTargetVariant.PATH]
*/
fun couldBeTestTarget(element: PsiElement): Boolean {
// TODO: PythonUnitTestUtil logic is weak. We should give user ability to launch test on symbol since user knows better if folder
// contains tests etc
val context = TypeEvalContext.userInitiated(element.project, element.containingFile)
return isTestElement(element, isTestClassRequired(), context)
}
/**
* There are 2 ways to provide target to runner:
* * As full qname (package1.module1.Class1.test_foo)
* * As filesystem path (package1/module1.py::Class1.test_foo) full or relative to working directory
*
* Second approach is prefered if this flag is set. It is generally better because filesystem path does not need __init__.py
*/
internal open fun shouldSeparateTargetPath(): Boolean = true
/**
* @param metaInfo String "metainfo" field provided by test runner.
* Pytest reports test name with parameters here
*/
open fun setMetaInfo(metaInfo: String) {
}
/**
* @return Boolean if metainfo and target produces same configuration
*/
open fun isSameAsLocation(target: ConfigurationTarget, metainfo: String?): Boolean = target == this.target
}
abstract class PyAbstractTestFactory<out CONF_T : PyAbstractTestConfiguration>(type: PythonTestConfigurationType)
: PythonConfigurationFactoryBase(type) {
abstract override fun createTemplateConfiguration(project: Project): CONF_T
// Several insances of the same class point to the same factory
override fun equals(other: Any?): Boolean = ((other as? PyAbstractTestFactory<*>))?.id == id
override fun hashCode(): Int = id.hashCode()
/**
* Only UnitTest inheritors are supported
*/
abstract fun onlyClassesAreSupported(sdk: Sdk): Boolean
/**
* Test framework needs package to be installed
*/
open val packageRequired: String? = null
open fun isFrameworkInstalled(sdk: Sdk): Boolean {
val requiredPackage = packageRequired ?: return true // No package required
return PyPackageManager.getInstance(sdk).packages?.firstOrNull { it.name == requiredPackage } != null
}
}
internal sealed class PyTestTargetForConfig(val configurationTarget: ConfigurationTarget,
val workingDirectory: VirtualFile) {
class PyTestPathTarget(target: String, workingDirectory: VirtualFile) :
PyTestTargetForConfig(ConfigurationTarget(target, PyRunTargetVariant.PATH), workingDirectory)
class PyTestPythonTarget(target: String, workingDirectory: VirtualFile, val namePaths: QualifiedNameParts) :
PyTestTargetForConfig(ConfigurationTarget(target, PyRunTargetVariant.PYTHON), workingDirectory)
}
/**
* Only one producer is registered with EP, but it uses factory configured by user to produce different configs
*/
internal class PyTestsConfigurationProducer : AbstractPythonTestConfigurationProducer<PyAbstractTestConfiguration>() {
companion object {
/**
* Creates [ConfigurationTarget] to make configuration work with provided element.
* Also reports working dir what should be set to configuration to work correctly
* @return [target, workingDirectory]
*/
internal fun getTargetForConfig(configuration: PyAbstractTestConfiguration,
baseElement: PsiElement): PyTestTargetForConfig? {
var element = baseElement
// Go up until we reach top of the file
// asking configuration about each element if it is supported or not
// If element is supported -- set it as configuration target
do {
if (configuration.couldBeTestTarget(element)) {
when (element) {
is PyQualifiedNameOwner -> { // Function, class, method
val module = configuration.module ?: return null
val elementFile = element.containingFile as? PyFile ?: return null
val workingDirectory = getDirectoryForFileToBeImportedFrom(elementFile) ?: return null
val context = QNameResolveContext(ModuleBasedContextAnchor(module),
evalContext = TypeEvalContext.userInitiated(configuration.project,
null),
folderToStart = workingDirectory.virtualFile)
val parts = element.tryResolveAndSplit(context) ?: return null
val qualifiedName = parts.getElementNamePrependingFile(workingDirectory)
return PyTestTargetForConfig.PyTestPythonTarget(qualifiedName.toString(), workingDirectory.virtualFile, parts)
}
is PsiFileSystemItem -> {
val virtualFile = element.virtualFile
val workingDirectory: VirtualFile = when (element) {
is PyFile -> getDirectoryForFileToBeImportedFrom(element)?.virtualFile
is PsiDirectory -> virtualFile
else -> return null
} ?: return null
return PyTestTargetForConfig.PyTestPathTarget(virtualFile.path, workingDirectory)
}
}
}
element = element.parent ?: break
}
while (element !is PsiDirectory) // if parent is folder, then we are at file level
return null
}
/**
* Returns test root for this file. Either it is specified explicitly or calculated using following strategy:
* Inspect file relative imports, find farthest and return folder with imported file
*/
private fun getDirectoryForFileToBeImportedFrom(file: PyFile): PsiDirectory? {
getExplicitlyConfiguredTestRoot(file)?.let {
return PsiManager.getInstance(file.project).findDirectory(it)
}
val maxRelativeLevel = file.fromImports.map { it.relativeLevel }.maxOrNull() ?: 0
var elementFolder = file.parent ?: return null
for (i in 1..maxRelativeLevel) {
elementFolder = elementFolder.parent ?: return null
}
return elementFolder
}
}
override fun getConfigurationFactory() = PythonTestConfigurationType.getInstance().configurationFactories[0]
override val configurationClass: Class<PyAbstractTestConfiguration> = PyAbstractTestConfiguration::class.java
override fun createLightConfiguration(context: ConfigurationContext): RunConfiguration? {
val module = context.module ?: return null
val project = context.project ?: return null
val configuration =
findConfigurationFactoryFromSettings(module).createTemplateConfiguration(project) as? PyAbstractTestConfiguration
?: return null
if (!setupConfigurationFromContext(configuration, context, Ref(context.psiLocation))) return null
return configuration
}
override fun cloneTemplateConfiguration(context: ConfigurationContext): RunnerAndConfigurationSettings {
return cloneTemplateConfigurationStatic(context, findConfigurationFactoryFromSettings(context.module))
}
override fun createConfigurationFromContext(context: ConfigurationContext): ConfigurationFromContext? {
// Since we need module, no need to even try to create config with out of it
context.module ?: return null
return super.createConfigurationFromContext(context)
}
// test configuration is always prefered over regular one
override fun shouldReplace(self: ConfigurationFromContext,
other: ConfigurationFromContext): Boolean = other.configuration is PythonRunConfiguration
override fun isPreferredConfiguration(self: ConfigurationFromContext?,
other: ConfigurationFromContext): Boolean = other.configuration is PythonRunConfiguration
override fun setupConfigurationFromContext(configuration: PyAbstractTestConfiguration,
context: ConfigurationContext,
sourceElement: Ref<PsiElement>): Boolean {
val element = sourceElement.get() ?: return false
if (element.containingFile !is PyFile && element !is PsiDirectory) {
return false
}
val location = context.location
configuration.module = context.module
configuration.isUseModuleSdk = true
if (location is PyTargetBasedPsiLocation) {
location.target.copyTo(configuration.target)
location.metainfo?.let { configuration.setMetaInfo(it) }
}
else {
val targetForConfig = getTargetForConfig(configuration, element) ?: return false
targetForConfig.configurationTarget.copyTo(configuration.target)
// Directory may be set in Default configuration. In that case no need to rewrite it.
if (configuration.workingDirectory.isNullOrEmpty()) {
configuration.workingDirectory = targetForConfig.workingDirectory.path
}
else {
// Template has working directory set
if (targetForConfig is PyTestTargetForConfig.PyTestPythonTarget) {
configuration.target.asPsiElement(configuration)?.containingFile?.let { file ->
val namePaths = targetForConfig.namePaths
//This working directory affects resolving process making it point to different file
if (file != namePaths.file && configuration is PyTestConfigurationWithCustomSymbol) {
/***
* Use "Custom symbol" ([PyTestConfigurationWithCustomSymbol]) mode
*/
configuration.target.target = ""
configuration.target.targetType = PyRunTargetVariant.CUSTOM
configuration.additionalArguments = configuration.createAdditionalArguments(namePaths)
}
}
}
}
}
configuration.setGeneratedName()
return true
}
override fun isConfigurationFromContext(configuration: PyAbstractTestConfiguration, context: ConfigurationContext): Boolean {
if (PyTestConfigurationSelector.EP.extensionList.find { it.isFromContext(configuration, context) } != null) {
return true
}
val location = context.location
if (location is PyTargetBasedPsiLocation) {
// With derived classes several configurations for same element may exist
return configuration.isSameAsLocation(location.target, location.metainfo)
}
val psiElement = context.psiLocation ?: return false
val configurationFromContext = createConfigurationFromContext(context)?.configuration as? PyAbstractTestConfiguration ?: return false
if (configuration.target != configurationFromContext.target) {
return false
}
if (configuration.target.targetType == PyRunTargetVariant.CUSTOM) {
/**
* Two "custom symbol" ([PyTestConfigurationWithCustomSymbol]) configurations are same when additional args are same
*/
return (configuration is PyTestConfigurationWithCustomSymbol
&& configuration.additionalArguments == configurationFromContext.additionalArguments
&& configuration.fileSymbolSeparator in configuration.additionalArguments)
}
//Even of both configurations have same targets, it could be that both have same qname which is resolved
// to different elements due to different working folders.
// Resolve them and check files
if (configuration.target.targetType != PyRunTargetVariant.PYTHON) return true
val targetPsi = targetAsPsiElement(configuration.target.targetType, configuration.target.target, configuration,
configuration.getWorkingDirectoryAsVirtual()) ?: return true
return targetPsi.containingFile == psiElement.containingFile
}
}
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.PROPERTY)
/**
* Mark run configuration field with it to enable saving, restoring and form iteraction
*/
annotation class ConfigField(@param:PropertyKey(resourceBundle = PyBundle.BUNDLE) val localizedName: String)
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/compiler/asJava/lightClasses/AnnotatedPropertyWithSites.kt | 7 | 638 | // Test
annotation class MyAnnotation
annotation class MyAnnotation2
annotation class MyAnnotation3
annotation class MyAnnotation4
annotation class MyAnnotation5
annotation class MyAnnotation6
@Target(AnnotationTarget.VALUE_PARAMETER)
@Retention(AnnotationRetention.RUNTIME)
annotation class MyAnnotation7
class Test(@get:MyAnnotation @set:MyAnnotation2 @setparam:MyAnnotation3 @property:MyAnnotation4 @field:MyAnnotation5 @param:MyAnnotation6 var bar: String) {
fun @receiver:MyAnnotation7 Int.fooF() = Unit
var @receiver:MyAnnotation7 Int.fooP
get() = Unit
set(value) {}
}
// SKIP_SANITY_TEST
// FIR_COMPARISON | apache-2.0 |
smmribeiro/intellij-community | platform/platform-tests/testSrc/com/intellij/ui/dsl/builder/TextFieldTest.kt | 1 | 1357 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.dsl.builder
import com.intellij.ui.dsl.generateLongString
import com.intellij.ui.layout.*
import org.junit.Test
import java.util.*
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class TextFieldTest {
var property = ""
@Test
fun testBindingInitialization() {
property = UUID.randomUUID().toString()
panel {
row {
val textField = textField()
.bindText(::property)
assertEquals(textField.component.text, property)
}
}
var localProperty = UUID.randomUUID().toString()
panel {
row {
val textField = textField()
.bindText({ localProperty }, { localProperty = it })
assertEquals(textField.component.text, localProperty)
}
}
panel {
row {
val textField = textField()
.bindText(PropertyBinding({ localProperty }, { localProperty = it }))
assertEquals(textField.component.text, localProperty)
}
}
}
@Test
fun testPreferredSize() {
val panel = panel {
row("Label:") {
textField()
.text(generateLongString())
}
}
assertTrue(panel.preferredSize.width < 300)
}
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveTopLevelDeclarations/misc/nonCodeUsagesWithJavaFacadeMethod/before/code/test.kt | 13 | 127 | package code
fun <caret>MyTest() {}
fun main(args: Array<String>) {
// MyTest
// code.MyTest
// code.TestKt.MyTest
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/whenWithOnlyElse/subjectVariable/blockElse/noReference.kt | 9 | 202 | // WITH_STDLIB
fun test() {
when<caret> (val a = create()) {
else -> {
use("")
foo()
}
}
}
fun create(): String = ""
fun use(s: String) {}
fun foo() {} | apache-2.0 |
smmribeiro/intellij-community | platform/statistics/src/com/intellij/internal/statistic/collectors/fus/PluginInfoValidationRule.kt | 4 | 912 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic.collectors.fus
import com.intellij.internal.statistic.eventLog.validator.ValidationResultType
import com.intellij.internal.statistic.eventLog.validator.rules.EventContext
import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule
class PluginInfoValidationRule : CustomValidationRule() {
override fun acceptRuleId(ruleId: String?) = ruleId in acceptedRules
override fun doValidate(data: String, context: EventContext): ValidationResultType {
return acceptWhenReportedByPluginFromPluginRepository(context)
}
companion object {
private val acceptedRules = hashSetOf("plugin_info", "project_type", "framework", "gutter_icon", "editor_notification_panel_key", "plugin_version")
}
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/hierarchy/class/super/JetList/main.kt | 13 | 29 | val a: List<caret><String>
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/j2k/old/tests/testData/fileOrElement/newClassExpression/newAnonymousClass.kt | 26 | 27 | Runnable { println("Run") } | apache-2.0 |
smmribeiro/intellij-community | plugins/github/src/org/jetbrains/plugins/github/ui/component/GHHtmlErrorPanel.kt | 10 | 4771 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.ui.component
import com.intellij.ide.BrowserUtil
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.text.HtmlBuilder
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.ui.BrowserHyperlinkListener
import com.intellij.ui.HyperlinkAdapter
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.Nls
import org.jetbrains.plugins.github.exceptions.GithubStatusCodeException
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.ui.util.HtmlEditorPane
import org.jetbrains.plugins.github.ui.util.getName
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import java.awt.event.KeyEvent
import javax.swing.Action
import javax.swing.JComponent
import javax.swing.KeyStroke
import javax.swing.SwingConstants
import javax.swing.event.HyperlinkEvent
object GHHtmlErrorPanel {
private const val ERROR_ACTION_HREF = "ERROR_ACTION"
fun create(errorPrefix: String, error: Throwable,
errorAction: Action? = null,
horizontalAlignment: Int = SwingConstants.CENTER): JComponent {
val model = GHImmutableErrorPanelModel(errorPrefix, error, errorAction)
return create(model, horizontalAlignment)
}
fun create(model: GHErrorPanelModel, horizontalAlignment: Int = SwingConstants.CENTER): JComponent {
val pane = HtmlEditorPane().apply {
foreground = UIUtil.getErrorForeground()
isFocusable = true
removeHyperlinkListener(BrowserHyperlinkListener.INSTANCE)
addHyperlinkListener(object : HyperlinkAdapter() {
override fun hyperlinkActivated(e: HyperlinkEvent) {
if (e.description == ERROR_ACTION_HREF) {
model.errorAction?.actionPerformed(ActionEvent(this@apply, ActionEvent.ACTION_PERFORMED, "perform"))
}
else {
BrowserUtil.browse(e.description)
}
}
})
registerKeyboardAction(ActionListener {
model.errorAction?.actionPerformed(it)
}, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_FOCUSED)
}
Controller(model, pane, horizontalAlignment)
return pane
}
private class Controller(private val model: GHErrorPanelModel,
private val pane: HtmlEditorPane,
horizontalAlignment: Int) {
private val alignmentText = when (horizontalAlignment) {
SwingConstants.LEFT -> "left"
SwingConstants.RIGHT -> "right"
else -> "center"
}
init {
model.addAndInvokeChangeEventListener(::update)
}
private fun update() {
val error = model.error
if (error != null) {
pane.isVisible = true
val errorTextBuilder = HtmlBuilder()
.appendP(model.errorPrefix)
.appendP(getLoadingErrorText(error))
val errorAction = model.errorAction
if (errorAction != null) {
errorTextBuilder.br()
.appendP(HtmlChunk.link(ERROR_ACTION_HREF, errorAction.getName()))
}
pane.setBody(errorTextBuilder.toString())
}
else {
pane.isVisible = false
pane.setBody("")
}
// JDK bug - need to force height recalculation (see JBR-2256)
pane.setSize(Int.MAX_VALUE / 2, Int.MAX_VALUE / 2)
}
private fun HtmlBuilder.appendP(chunk: HtmlChunk): HtmlBuilder = append(HtmlChunk.p().attr("align", alignmentText).child(chunk))
private fun HtmlBuilder.appendP(@Nls text: String): HtmlBuilder = appendP(HtmlChunk.text(text))
}
@Nls
private fun getLoadingErrorText(error: Throwable): String {
if (error is GithubStatusCodeException && error.error != null && error.error!!.message != null) {
val githubError = error.error!!
val message = githubError.message!!.removePrefix("[").removeSuffix("]")
val builder = HtmlBuilder().append(message)
if (message.startsWith("Could not resolve to a Repository", true)) {
@NlsSafe
val explanation = " Either repository doesn't exist or you don't have access. The most probable cause is that OAuth App access restrictions are enabled in organization."
builder.append(explanation)
}
val errors = githubError.errors?.map { e ->
HtmlChunk.text(e.message ?: GithubBundle.message("gql.error.in.field", e.code, e.resource, e.field.orEmpty()))
}
if (!errors.isNullOrEmpty()) builder.append(": ").append(HtmlChunk.br()).appendWithSeparators(HtmlChunk.br(), errors)
return builder.toString()
}
return error.message ?: GithubBundle.message("unknown.loading.error")
}
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/GradleKotlinFrameworkSupportProviderUtils.kt | 5 | 2418 | // 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.gradleJava.configuration
import com.intellij.openapi.module.Module
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import java.io.File
import java.io.Writer
/**
* create parent directories and file
* @return null if file already exists
*/
internal fun getNewFileWriter(
module: Module,
relativeDir: String,
fileName: String
): Writer? {
val contentEntryPath = module.gradleModuleBuilder?.contentEntryPath ?: return null
if (contentEntryPath.isEmpty()) return null
val contentRootDir = File(contentEntryPath)
val modelContentRootDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(contentRootDir) ?: return null
val dir = VfsUtil.createDirectoryIfMissing(modelContentRootDir, relativeDir) ?: return null
if (dir.findChild(fileName) != null) return null
val file = dir.createChildData(null, fileName)
return file.getOutputStream(null).writer()
}
internal fun addBrowserSupport(module: Module) {
getNewFileWriter(module, "src/main/resources", "index.html")?.use {
it.write(
"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>${module.name}</title>
<script src="${module.name}.js"></script>
</head>
<body>
</body>
</html>
""".trimIndent().trim()
)
}
getNewFileWriter(module, "src/main/kotlin", "main.kt")?.use {
it.write(
"""
import kotlinx.browser.document
fun main() {
document.write("Hello, world!")
}
""".trimIndent().trim()
)
}
}
internal fun browserConfiguration(): String {
return """
webpackTask {
cssSupport.enabled = true
}
runTask {
cssSupport.enabled = true
}
testTask {
useKarma {
useChromeHeadless()
webpackConfig.cssSupport.enabled = true
}
}
""".trimIndent()
} | apache-2.0 |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/openapi/application/CustomConfigMigrationOption.kt | 4 | 4253 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.application
import com.google.common.annotations.VisibleForTesting
import com.intellij.openapi.diagnostic.logger
import com.intellij.util.io.delete
import com.intellij.util.io.exists
import com.intellij.util.io.systemIndependentPath
import com.intellij.util.io.write
import java.nio.file.Files
import java.nio.file.Path
private val log = logger<CustomConfigMigrationOption>()
/**
* [A marker file](com.intellij.openapi.application.ConfigImportHelper.CUSTOM_MARKER_FILE_NAME) is created in the config directory
* if we need to perform some custom migration on the next startup. The format of the file is defined below.
*
* - If we need to start with a clean config ("Restore Default Settings" action), the file is empty.
* - If we need to import config from the given place ("Import Settings" action), the format is `import <path>`.
* - If the import has already been performed, but the IDE was restarted (because custom vmoptions were added or removed),
* and we need to restore some values of system properties indicating the first start after importing the config,
* then the format is `properties <system properties separated by space`, e.g.
* ```
* properties intellij.first.ide.session intellij.config.imported.in.current.session
* ```
*/
sealed class CustomConfigMigrationOption {
fun writeConfigMarkerFile() {
val markerFile = getCustomConfigMarkerFilePath(PathManager.getConfigDir())
if (markerFile.exists()) {
log.error("Marker file $markerFile shouldn't exist")
}
markerFile.write(getStringPresentation())
}
abstract fun getStringPresentation(): String
override fun toString(): String = getStringPresentation()
object StartWithCleanConfig : CustomConfigMigrationOption() {
override fun getStringPresentation(): String = ""
override fun toString(): String = "Start with clean config"
}
class MigrateFromCustomPlace(val location: Path) : CustomConfigMigrationOption() {
override fun getStringPresentation(): String = IMPORT_PREFIX + location.systemIndependentPath
}
class SetProperties(val properties: List<String>) : CustomConfigMigrationOption() {
override fun getStringPresentation(): String = PROPERTIES_PREFIX + properties.joinToString(separator = " ")
}
companion object {
private const val IMPORT_PREFIX = "import "
private const val PROPERTIES_PREFIX = "properties "
@JvmStatic
fun readCustomConfigMigrationOptionAndRemoveMarkerFile(configDir: Path): CustomConfigMigrationOption? {
val markerFile = getCustomConfigMarkerFilePath(configDir)
if (!markerFile.exists()) return null
try {
val lines = Files.readAllLines(markerFile)
if (lines.isEmpty()) return StartWithCleanConfig
val line = lines.first()
when {
line.isEmpty() -> return StartWithCleanConfig
line.startsWith(IMPORT_PREFIX) -> {
val path = markerFile.fileSystem.getPath(line.removePrefix(IMPORT_PREFIX))
if (!path.exists()) {
log.warn("$markerFile points to non-existent config: [$lines]")
return null
}
return MigrateFromCustomPlace(path)
}
line.startsWith(PROPERTIES_PREFIX) -> {
val properties = line.removePrefix(PROPERTIES_PREFIX).split(' ')
return SetProperties(properties)
}
else -> {
log.error("Invalid format of $markerFile: $lines")
return null
}
}
}
catch (e: Exception) {
log.warn("Couldn't load content of $markerFile")
return null
}
finally {
removeMarkerFile(markerFile)
}
}
private fun removeMarkerFile(markerFile: Path) {
try {
markerFile.delete()
}
catch (e: Exception) {
log.warn("Couldn't delete the custom config migration file $markerFile", e)
}
}
@VisibleForTesting
fun getCustomConfigMarkerFilePath(configDir: Path): Path {
return configDir.resolve(ConfigImportHelper.CUSTOM_MARKER_FILE_NAME)
}
}
}
| apache-2.0 |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/ide/plugins/advertiser/PluginFeatureCacheService.kt | 1 | 1329 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplacePutWithAssignment", "ReplaceGetOrSet")
package com.intellij.ide.plugins.advertiser
import com.intellij.openapi.components.*
import kotlinx.serialization.Serializable
import org.jetbrains.annotations.ApiStatus
@Service(Service.Level.APP)
@State(name = "PluginFeatureCacheService", storages = [Storage(StoragePathMacros.CACHE_FILE)], allowLoadInTests = true)
@ApiStatus.Internal
class PluginFeatureCacheService : SerializablePersistentStateComponent<PluginFeatureCacheService.MyState>(MyState()) {
companion object {
fun getInstance(): PluginFeatureCacheService = service()
}
override fun getStateModificationCount(): Long {
val state = state
return (state.extensions?.modificationCount ?: 0) + (state.dependencies?.modificationCount ?: 0)
}
@Serializable
data class MyState(
val extensions: PluginFeatureMap? = null,
val dependencies: PluginFeatureMap? = null
)
var extensions: PluginFeatureMap?
get() = state.extensions
set(value) {
loadState(MyState(value, state.dependencies))
}
var dependencies: PluginFeatureMap?
get() = state.dependencies
set(value) {
loadState(MyState(state.extensions, value))
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/structuralsearch/callExpression/callAnyParameter.kt | 4 | 267 | class FirstClass {
fun firstClassFun() {}
fun firstClassFunTwo(i: Int) { <warning descr="SSR">print(i)</warning> }
fun testFoo() {
<warning descr="SSR">firstClassFun()</warning>
<warning descr="SSR">firstClassFunTwo(2)</warning>
}
} | apache-2.0 |
jotomo/AndroidAPS | core/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt | 1 | 9140 | package info.nightscout.androidaps.plugins.configBuilder
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.ConstraintsInterface
import info.nightscout.androidaps.interfaces.PluginType
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ConstraintChecker @Inject constructor(private val activePlugin: ActivePluginProvider) : ConstraintsInterface {
fun isLoopInvocationAllowed(): Constraint<Boolean> =
isLoopInvocationAllowed(Constraint(true))
fun isClosedLoopAllowed(): Constraint<Boolean> =
isClosedLoopAllowed(Constraint(true))
fun isAutosensModeEnabled(): Constraint<Boolean> =
isAutosensModeEnabled(Constraint(true))
fun isAMAModeEnabled(): Constraint<Boolean> =
isAMAModeEnabled(Constraint(true))
fun isSMBModeEnabled(): Constraint<Boolean> =
isSMBModeEnabled(Constraint(true))
fun isUAMEnabled(): Constraint<Boolean> =
isUAMEnabled(Constraint(true))
fun isAdvancedFilteringEnabled(): Constraint<Boolean> =
isAdvancedFilteringEnabled(Constraint(true))
fun isSuperBolusEnabled(): Constraint<Boolean> =
isSuperBolusEnabled(Constraint(true))
fun getMaxBasalAllowed(profile: Profile): Constraint<Double> =
applyBasalConstraints(Constraint(Constants.REALLYHIGHBASALRATE), profile)
fun getMaxBasalPercentAllowed(profile: Profile): Constraint<Int> =
applyBasalPercentConstraints(Constraint(Constants.REALLYHIGHPERCENTBASALRATE), profile)
fun getMaxBolusAllowed(): Constraint<Double> =
applyBolusConstraints(Constraint(Constants.REALLYHIGHBOLUS))
fun getMaxExtendedBolusAllowed(): Constraint<Double> =
applyExtendedBolusConstraints(Constraint(Constants.REALLYHIGHBOLUS))
fun getMaxCarbsAllowed(): Constraint<Int> =
applyCarbsConstraints(Constraint(Constants.REALLYHIGHCARBS))
fun getMaxIOBAllowed(): Constraint<Double> =
applyMaxIOBConstraints(Constraint(Constants.REALLYHIGHIOB))
fun isAutomationEnabled(): Constraint<Boolean> =
isAutomationEnabled(Constraint(true))
override fun isLoopInvocationAllowed(value: Constraint<Boolean>): Constraint<Boolean> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constraint.isLoopInvocationAllowed(value)
}
return value
}
override fun isClosedLoopAllowed(value: Constraint<Boolean>): Constraint<Boolean> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constraint.isClosedLoopAllowed(value)
}
return value
}
override fun isAutosensModeEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constraint.isAutosensModeEnabled(value)
}
return value
}
override fun isAMAModeEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constrain = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constrain.isAMAModeEnabled(value)
}
return value
}
override fun isSMBModeEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constraint.isSMBModeEnabled(value)
}
return value
}
override fun isUAMEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constraint.isUAMEnabled(value)
}
return value
}
override fun isAdvancedFilteringEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constraint.isAdvancedFilteringEnabled(value)
}
return value
}
override fun isSuperBolusEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constraint.isSuperBolusEnabled(value)
}
return value
}
override fun applyBasalConstraints(absoluteRate: Constraint<Double>, profile: Profile): Constraint<Double> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constraint.applyBasalConstraints(absoluteRate, profile)
}
return absoluteRate
}
override fun applyBasalPercentConstraints(percentRate: Constraint<Int>, profile: Profile): Constraint<Int> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constrain = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constrain.applyBasalPercentConstraints(percentRate, profile)
}
return percentRate
}
override fun applyBolusConstraints(insulin: Constraint<Double>): Constraint<Double> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constrain = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constrain.applyBolusConstraints(insulin)
}
return insulin
}
override fun applyExtendedBolusConstraints(insulin: Constraint<Double>): Constraint<Double> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constrain = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constrain.applyExtendedBolusConstraints(insulin)
}
return insulin
}
override fun applyCarbsConstraints(carbs: Constraint<Int>): Constraint<Int> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constrain = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constrain.applyCarbsConstraints(carbs)
}
return carbs
}
override fun applyMaxIOBConstraints(maxIob: Constraint<Double>): Constraint<Double> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constrain = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constrain.applyMaxIOBConstraints(maxIob)
}
return maxIob
}
override fun isAutomationEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
constraint.isAutomationEnabled(value)
}
return value
}
} | agpl-3.0 |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/scene/PointMesh.kt | 1 | 1883 | package de.fabmax.kool.scene
import de.fabmax.kool.math.Vec3f
import de.fabmax.kool.pipeline.Attribute
import de.fabmax.kool.pipeline.GlslType
import de.fabmax.kool.pipeline.shadermodel.vertexStage
import de.fabmax.kool.pipeline.shading.UnlitMaterialConfig
import de.fabmax.kool.pipeline.shading.UnlitShader
import de.fabmax.kool.scene.geometry.IndexedVertexList
import de.fabmax.kool.scene.geometry.PrimitiveType
import de.fabmax.kool.scene.geometry.VertexView
import de.fabmax.kool.util.Color
/**
* @author fabmax
*/
fun pointMesh(name: String? = null, block: PointMesh.() -> Unit): PointMesh {
return PointMesh(name = name).apply(block)
}
open class PointMesh(geometry: IndexedVertexList = IndexedVertexList(Attribute.POSITIONS, ATTRIB_POINT_SIZE, Attribute.COLORS), name: String? = null) :
Mesh(geometry, name) {
init {
geometry.primitiveType = PrimitiveType.POINTS
rayTest = MeshRayTest.nopTest()
val unlitCfg = UnlitMaterialConfig()
val unlitModel = UnlitShader.defaultUnlitModel(unlitCfg).apply {
vertexStage {
pointSize(attributeNode(ATTRIB_POINT_SIZE).output)
}
}
shader = UnlitShader(unlitCfg, unlitModel)
}
fun addPoint(block: VertexView.() -> Unit): Int {
val idx = geometry.addVertex(block)
geometry.addIndex(idx)
return idx
}
fun addPoint(position: Vec3f, pointSize: Float, color: Color): Int {
val idx = geometry.addVertex {
this.position.set(position)
this.color.set(color)
getFloatAttribute(ATTRIB_POINT_SIZE)?.f = pointSize
}
geometry.addIndex(idx)
return idx
}
fun clear() {
geometry.clear()
bounds.clear()
}
companion object {
val ATTRIB_POINT_SIZE = Attribute("aPointSize", GlslType.FLOAT)
}
}
| apache-2.0 |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/tasks/form/HabitScoringButtonsView.kt | 1 | 3417 | package com.habitrpg.android.habitica.ui.views.tasks.form
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.accessibility.AccessibilityEvent
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.extensions.asDrawable
import com.habitrpg.android.habitica.ui.helpers.bindView
import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper
class HabitScoringButtonsView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
private val positiveView: ViewGroup by bindView(R.id.positive_view)
private val negativeView: ViewGroup by bindView(R.id.negative_view)
private val positiveImageView: ImageView by bindView(R.id.positive_image_view)
private val negativeImageView: ImageView by bindView(R.id.negative_image_view)
private val positiveTextView: TextView by bindView(R.id.positive_text_view)
private val negativeTextView: TextView by bindView(R.id.negative_text_view)
var tintColor: Int = ContextCompat.getColor(context, R.color.brand_300)
var isPositive = true
set(value) {
field = value
positiveImageView.setImageDrawable(HabiticaIconsHelper.imageOfHabitControlPlus(tintColor, value).asDrawable(resources))
if (value) {
positiveTextView.setTextColor(tintColor)
positiveView.contentDescription = toContentDescription(R.string.positive_habit_form, R.string.on)
} else {
positiveTextView.setTextColor(ContextCompat.getColor(context, R.color.gray_100))
positiveView.contentDescription = toContentDescription(R.string.positive_habit_form, R.string.off)
}
}
var isNegative = true
set(value) {
field = value
negativeImageView.setImageDrawable(HabiticaIconsHelper.imageOfHabitControlMinus(tintColor, value).asDrawable(resources))
if (value) {
negativeTextView.setTextColor(tintColor)
negativeView.contentDescription = toContentDescription(R.string.negative_habit_form, R.string.on)
} else {
negativeTextView.setTextColor(ContextCompat.getColor(context, R.color.gray_100))
negativeView.contentDescription = toContentDescription(R.string.negative_habit_form, R.string.off)
}
}
private fun toContentDescription(descriptionStringId: Int, statusStringId: Int): String {
return context.getString(descriptionStringId) + ", " + context.getString(statusStringId)
}
init {
View.inflate(context, R.layout.task_form_habit_scoring, this)
gravity = Gravity.CENTER
positiveView.setOnClickListener {
isPositive = !isPositive
sendAccessibilityEvent(AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION)
}
negativeView.setOnClickListener {
isNegative = !isNegative
sendAccessibilityEvent(AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
}
isPositive = true
isNegative = true
}
}
| gpl-3.0 |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ui2/RowLayout.kt | 1 | 4993 | package de.fabmax.kool.modules.ui2
import de.fabmax.kool.KoolContext
import de.fabmax.kool.math.MutableVec2f
import kotlin.math.max
import kotlin.math.round
object RowLayout : Layout {
override fun measureContentSize(uiNode: UiNode, ctx: KoolContext) {
HorizontalLayout.measure(uiNode, true)
}
override fun layoutChildren(uiNode: UiNode, ctx: KoolContext) {
HorizontalLayout.layout(uiNode, true)
}
}
object ReverseRowLayout : Layout {
override fun measureContentSize(uiNode: UiNode, ctx: KoolContext) {
HorizontalLayout.measure(uiNode, false)
}
override fun layoutChildren(uiNode: UiNode, ctx: KoolContext) {
HorizontalLayout.layout(uiNode, false)
}
}
private object HorizontalLayout {
fun measure(uiNode: UiNode, isStartToEnd: Boolean) = uiNode.run {
val modWidth = modifier.width
val modHeight = modifier.height
var measuredWidth = 0f
var measuredHeight = 0f
var isDynamicWidth = true
var isDynamicHeight = true
if (modWidth is Dp) {
measuredWidth = modWidth.px
isDynamicWidth = false
}
if (modHeight is Dp) {
measuredHeight = modHeight.px
isDynamicHeight = false
}
if (isDynamicWidth || isDynamicHeight) {
// determine content size based on child sizes
var prevMargin = paddingTopPx
val indices = if (isStartToEnd) children.indices else children.indices.reversed()
for (i in indices) {
val child = children[i]
if (isDynamicWidth) {
measuredWidth += round(child.contentWidthPx) + round(max(prevMargin, child.marginStartPx))
prevMargin = child.marginEndPx
}
if (isDynamicHeight) {
val pTop = max(paddingTopPx, child.marginTopPx)
val pBottom = max(paddingBottomPx, child.marginBottomPx)
measuredHeight = max(measuredHeight, round(child.contentHeightPx + pTop + pBottom))
}
if (i == children.lastIndex && isDynamicWidth) {
measuredWidth += round(max(prevMargin, paddingEndPx))
}
}
if (modWidth is Grow) measuredWidth = modWidth.clampPx(measuredWidth, measuredWidth)
if (modHeight is Grow) measuredHeight = modHeight.clampPx(measuredHeight, measuredHeight)
}
setContentSize(measuredWidth, measuredHeight)
}
fun layout(uiNode: UiNode, isStartToEnd: Boolean) = uiNode.run {
val growSpace = determineAvailableGrowSpace(isStartToEnd)
var x = if (isStartToEnd) leftPx else rightPx
var prevMargin = if (isStartToEnd) paddingStartPx else paddingEndPx
for (i in children.indices) {
val child = children[i]
val growSpaceW = growSpace.x / growSpace.y
val growSpaceH = heightPx - max(paddingTopPx, child.marginTopPx) - max(paddingBottomPx, child.marginBottomPx)
val layoutW = round(child.computeWidthFromDimension(growSpaceW))
val layoutH = round(child.computeHeightFromDimension(growSpaceH))
val layoutY = round(uiNode.computeChildLocationY(child, layoutH))
val cw = child.modifier.width
if (cw is Grow) {
growSpace.x -= layoutW
growSpace.y -= cw.weight
}
val layoutX: Float
if (isStartToEnd) {
x += round(max(prevMargin, child.marginStartPx))
prevMargin = child.marginEndPx
layoutX = round(x)
x += layoutW
} else {
x -= round(max(prevMargin, child.marginEndPx))
prevMargin = child.marginStartPx
x -= layoutW
layoutX = round(x)
}
child.setBounds(layoutX, layoutY, layoutX + layoutW, layoutY + layoutH)
}
}
private fun UiNode.determineAvailableGrowSpace(isStartToEnd: Boolean): MutableVec2f {
var prevMargin = paddingStartPx
var remainingSpace = widthPx
var totalWeight = 0f
val indices = if (isStartToEnd) children.indices else children.indices.reversed()
for (i in indices) {
val child = children[i]
when (val childW = child.modifier.width) {
is Dp -> remainingSpace -= childW.px
is Grow -> totalWeight += childW.weight
FitContent -> remainingSpace -= child.contentWidthPx
}
remainingSpace -= max(prevMargin, child.marginStartPx)
prevMargin = child.marginEndPx
if (i == uiNode.children.lastIndex) {
remainingSpace -= max(prevMargin, uiNode.paddingEndPx)
}
}
if (totalWeight == 0f) totalWeight = 1f
return MutableVec2f(remainingSpace, totalWeight)
}
}
| apache-2.0 |
kickstarter/android-oss | app/src/main/java/com/kickstarter/ui/views/ConfirmDialog.kt | 1 | 2313 | package com.kickstarter.ui.views
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatDialog
import com.kickstarter.R
import com.kickstarter.databinding.GenericDialogAlertBinding
class ConfirmDialog @JvmOverloads constructor(
context: Context,
val title: String?,
val message: String,
private val buttonText: String? = null
) : AppCompatDialog(context) {
private lateinit var binding: GenericDialogAlertBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
binding = GenericDialogAlertBinding.inflate(layoutInflater)
setContentView(binding.root)
if (title != null) {
setTitleText(title)
} else {
binding.titleTextView.visibility = View.GONE
}
if (buttonText != null) {
setButtonText(buttonText)
} else {
setButtonText(context.getString(R.string.general_alert_buttons_ok))
}
setMessage(message)
binding.okButton.setOnClickListener {
okButtonClick()
}
}
private fun setButtonText(buttonText: String) {
binding.okButton.text = buttonText
}
/**
* Set the title on the TextView with id title_text_view.
* Note, default visibility is GONE since we may not always want a title.
*/
private fun setTitleText(title: String) {
binding.titleTextView.text = title
binding.titleTextView.visibility = TextView.VISIBLE
val params = binding.messageTextView.layoutParams as LinearLayout.LayoutParams
params.topMargin = context.resources.getDimension(R.dimen.grid_1).toInt()
binding.messageTextView.layoutParams = params
}
/**
* Set the message on the TextView with id message_text_view.
*/
private fun setMessage(message: String) {
binding.messageTextView.text = message
}
/**
* Dismiss the dialog on click ok_button".
*/
private fun okButtonClick() {
dismiss()
}
}
| apache-2.0 |
Flank/flank | test_runner/src/main/kotlin/ftl/adapter/GoogleJUnitTestFetch.kt | 1 | 545 | package ftl.adapter
import ftl.api.JUnitTest
import ftl.client.google.createAndUploadPerformanceMetricsForAndroid
import ftl.client.google.fetchMatrices
import ftl.client.junit.createJUnitTestResult
object GoogleJUnitTestFetch :
JUnitTest.Result.GenerateFromApi,
(JUnitTest.Result.ApiIdentity) -> JUnitTest.Result by { (args, matrixMap) ->
fetchMatrices(matrixMap.map.values.map { it.matrixId }, args.project)
.createAndUploadPerformanceMetricsForAndroid(args, matrixMap)
.createJUnitTestResult()
}
| apache-2.0 |
mdaniel/intellij-community | plugins/ide-features-trainer/src/training/ui/LessonMessagePane.kt | 1 | 26269 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package training.ui
import com.intellij.icons.AllIcons
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.FontPreferences
import com.intellij.openapi.keymap.Keymap
import com.intellij.openapi.keymap.KeymapManagerListener
import com.intellij.openapi.util.SystemInfo
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.*
import training.FeaturesTrainerIcons
import training.dsl.TaskTextProperties
import training.learn.lesson.LessonManager
import java.awt.*
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.awt.font.GlyphVector
import java.awt.geom.Point2D
import java.awt.geom.Rectangle2D
import java.awt.geom.RoundRectangle2D
import javax.swing.Icon
import javax.swing.JTextPane
import javax.swing.text.AttributeSet
import javax.swing.text.BadLocationException
import javax.swing.text.SimpleAttributeSet
import javax.swing.text.StyleConstants
import kotlin.math.roundToInt
internal class LessonMessagePane(private val panelMode: Boolean = true) : JTextPane(), Disposable {
//Style Attributes for LessonMessagePane(JTextPane)
private val INACTIVE = SimpleAttributeSet()
private val REGULAR = SimpleAttributeSet()
private val BOLD = SimpleAttributeSet()
private val SHORTCUT = SimpleAttributeSet()
private val SHORTCUT_SEPARATOR = SimpleAttributeSet()
private val ROBOTO = SimpleAttributeSet()
private val CODE = SimpleAttributeSet()
private val LINK = SimpleAttributeSet()
private var codeFontSize = UISettings.getInstance().plainFont.size
private val TASK_PARAGRAPH_STYLE = SimpleAttributeSet()
private val INTERNAL_PARAGRAPH_STYLE = SimpleAttributeSet()
private val BALLOON_STYLE = SimpleAttributeSet()
private val textColor: Color = if (panelMode) UISettings.getInstance().defaultTextColor else UISettings.getInstance().tooltipTextColor
private val codeForegroundColor: Color = if (panelMode) UISettings.getInstance().codeForegroundColor else UISettings.getInstance().tooltipTextColor
private val shortcutTextColor = if (panelMode) UISettings.getInstance().shortcutTextColor else UISettings.getInstance().tooltipShortcutTextColor
enum class MessageState { NORMAL, PASSED, INACTIVE, RESTORE, INFORMER }
data class MessageProperties(val state: MessageState = MessageState.NORMAL,
val visualIndex: Int? = null,
val useInternalParagraphStyle: Boolean = false,
val textProperties: TaskTextProperties? = null)
private data class LessonMessage(
val messageParts: List<MessagePart>,
var state: MessageState,
val visualIndex: Int?,
val useInternalParagraphStyle: Boolean,
val textProperties: TaskTextProperties?,
var start: Int = 0,
var end: Int = 0
)
private data class RangeData(var range: IntRange, val action: (Point, Int) -> Unit)
private val activeMessages = mutableListOf<LessonMessage>()
private val restoreMessages = mutableListOf<LessonMessage>()
private val inactiveMessages = mutableListOf<LessonMessage>()
private val fontFamily: String get() = StartupUiUtil.getLabelFont().fontName
private val ranges = mutableSetOf<RangeData>()
private var insertOffset: Int = 0
private var paragraphStyle = SimpleAttributeSet()
private fun allLessonMessages() = activeMessages + restoreMessages + inactiveMessages
var currentAnimation = 0
var totalAnimation = 0
//, fontFace, check_width + check_right_indent
init {
UIUtil.doNotScrollToCaret(this)
initStyleConstants()
isEditable = false
val listener = object : MouseAdapter() {
override fun mouseClicked(me: MouseEvent) {
val rangeData = getRangeDataForMouse(me) ?: return
val middle = (rangeData.range.first + rangeData.range.last) / 2
val rectangle = modelToView2D(middle)
rangeData.action(Point(rectangle.x.roundToInt(), (rectangle.y.roundToInt() + rectangle.height.roundToInt() / 2)),
rectangle.height.roundToInt())
}
override fun mouseMoved(me: MouseEvent) {
val rangeData = getRangeDataForMouse(me)
cursor = if (rangeData == null) {
Cursor.getDefaultCursor()
}
else {
Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
}
}
}
addMouseListener(listener)
addMouseMotionListener(listener)
val connect = ApplicationManager.getApplication().messageBus.connect(this)
connect.subscribe(KeymapManagerListener.TOPIC, object : KeymapManagerListener {
override fun activeKeymapChanged(keymap: Keymap?) {
redrawMessages()
}
override fun shortcutChanged(keymap: Keymap, actionId: String) {
redrawMessages()
}
})
}
override fun dispose() = Unit
private fun getRangeDataForMouse(me: MouseEvent): RangeData? {
val offset = viewToModel2D(Point2D.Double(me.x.toDouble(), me.y.toDouble()))
val result = ranges.find { offset in it.range } ?: return null
if (offset < 0 || offset >= document.length) return null
for (i in result.range) {
val rectangle = modelToView2D(i)
if (me.x >= rectangle.x && me.y >= rectangle.y && me.y <= rectangle.y + rectangle.height) {
return result
}
}
return null
}
override fun addNotify() {
super.addNotify()
initStyleConstants()
redrawMessages()
}
override fun updateUI() {
super.updateUI()
ApplicationManager.getApplication().invokeLater(Runnable {
initStyleConstants()
redrawMessages()
})
}
private fun initStyleConstants() {
val fontSize = UISettings.getInstance().plainFont.size
StyleConstants.setForeground(INACTIVE, UISettings.getInstance().inactiveColor)
StyleConstants.setFontFamily(REGULAR, fontFamily)
StyleConstants.setFontSize(REGULAR, fontSize)
StyleConstants.setFontFamily(BOLD, fontFamily)
StyleConstants.setFontSize(BOLD, fontSize)
StyleConstants.setBold(BOLD, true)
StyleConstants.setFontFamily(SHORTCUT, fontFamily)
StyleConstants.setFontSize(SHORTCUT, fontSize)
StyleConstants.setBold(SHORTCUT, true)
StyleConstants.setFontFamily(SHORTCUT_SEPARATOR, fontFamily)
StyleConstants.setFontSize(SHORTCUT_SEPARATOR, fontSize)
EditorColorsManager.getInstance().globalScheme.editorFontName
StyleConstants.setFontFamily(CODE, EditorColorsManager.getInstance().globalScheme.editorFontName)
StyleConstants.setFontSize(CODE, codeFontSize)
StyleConstants.setFontFamily(LINK, fontFamily)
StyleConstants.setUnderline(LINK, true)
StyleConstants.setFontSize(LINK, fontSize)
StyleConstants.setSpaceAbove(TASK_PARAGRAPH_STYLE, UISettings.getInstance().taskParagraphAbove.toFloat())
setCommonParagraphAttributes(TASK_PARAGRAPH_STYLE)
StyleConstants.setSpaceAbove(INTERNAL_PARAGRAPH_STYLE, UISettings.getInstance().taskInternalParagraphAbove.toFloat())
setCommonParagraphAttributes(INTERNAL_PARAGRAPH_STYLE)
StyleConstants.setLineSpacing(BALLOON_STYLE, 0.2f)
StyleConstants.setLeftIndent(BALLOON_STYLE, UISettings.getInstance().balloonIndent.toFloat())
StyleConstants.setForeground(REGULAR, textColor)
StyleConstants.setForeground(BOLD, textColor)
StyleConstants.setForeground(SHORTCUT, shortcutTextColor)
StyleConstants.setForeground(SHORTCUT_SEPARATOR, UISettings.getInstance().shortcutSeparatorColor)
StyleConstants.setForeground(LINK, UISettings.getInstance().lessonLinkColor)
StyleConstants.setForeground(CODE, codeForegroundColor)
}
private fun setCommonParagraphAttributes(attributeSet: SimpleAttributeSet) {
StyleConstants.setLeftIndent(attributeSet, UISettings.getInstance().checkIndent.toFloat())
StyleConstants.setRightIndent(attributeSet, 0f)
StyleConstants.setSpaceBelow(attributeSet, 0.0f)
StyleConstants.setLineSpacing(attributeSet, 0.2f)
}
fun messagesNumber(): Int = activeMessages.size
@Suppress("SameParameterValue")
private fun removeMessagesRange(startIdx: Int, endIdx: Int, list: MutableList<LessonMessage>) {
if (startIdx == endIdx) return
list.subList(startIdx, endIdx).clear()
}
fun clearRestoreMessages(): () -> Rectangle? {
removeMessagesRange(0, restoreMessages.size, restoreMessages)
redrawMessages()
val lastOrNull = activeMessages.lastOrNull()
return { lastOrNull?.let { getRectangleToScroll(it) } }
}
fun removeInactiveMessages(number: Int) {
removeMessagesRange(0, number, inactiveMessages)
redrawMessages()
}
fun resetMessagesNumber(number: Int): () -> Rectangle? {
val move = activeMessages.subList(number, activeMessages.size)
move.forEach {
it.state = MessageState.INACTIVE
}
inactiveMessages.addAll(0, move)
move.clear()
return clearRestoreMessages()
}
fun getCurrentMessageRectangle(): Rectangle? {
val lessonMessage = restoreMessages.lastOrNull() ?: activeMessages.lastOrNull() ?: return null
return getRectangleToScroll(lessonMessage)
}
private fun insertText(text: String, attributeSet: AttributeSet) {
document.insertString(insertOffset, text, attributeSet)
styledDocument.setParagraphAttributes(insertOffset, text.length - 1, paragraphStyle, true)
insertOffset += text.length
}
private fun insertIconWithFixedHeight(iconIdx: String, state: MessageState, getFixedHeight: (Icon) -> Int) {
val original = LearningUiManager.iconMap[iconIdx] ?: error("Not found icon with index: $iconIdx")
val icon = if (state == MessageState.INACTIVE) getInactiveIcon(original) else original
insertIcon(object : Icon {
override fun getIconWidth() = icon.iconWidth
override fun getIconHeight() = getFixedHeight(icon)
override fun paintIcon(c: Component, g: Graphics, x: Int, y: Int) {
icon.paintIcon(c, g, x, y)
}
})
insertOffset++
}
fun addMessage(messageParts: List<MessagePart>, properties: MessageProperties = MessageProperties()): () -> Rectangle? {
val lessonMessage = LessonMessage(messageParts,
properties.state,
properties.visualIndex,
properties.useInternalParagraphStyle,
properties.textProperties,
)
when (properties.state) {
MessageState.INACTIVE -> inactiveMessages
MessageState.RESTORE -> restoreMessages
else -> activeMessages
}.add(lessonMessage)
redrawMessages()
return { getRectangleToScroll(lessonMessage) }
}
fun removeMessage(index: Int) {
activeMessages.removeAt(index)
}
private fun getRectangleToScroll(lessonMessage: LessonMessage): Rectangle? {
val startRect = modelToView2D(lessonMessage.start + 1)?.toRectangle() ?: return null
val endRect = modelToView2D(lessonMessage.end - 1)?.toRectangle() ?: return null
return Rectangle(startRect.x, startRect.y - activeTaskInset, endRect.x + endRect.width - startRect.x,
endRect.y + endRect.height - startRect.y + activeTaskInset * 2)
}
fun redrawMessages() {
initStyleConstants()
ranges.clear()
highlighter.removeAllHighlights()
text = ""
insertOffset = 0
var previous: LessonMessage? = null
for (lessonMessage in allLessonMessages()) {
if (previous?.messageParts?.firstOrNull()?.type != MessagePart.MessageType.ILLUSTRATION) {
val textProperties = previous?.textProperties
paragraphStyle = when {
textProperties != null -> {
val customStyle = SimpleAttributeSet()
setCommonParagraphAttributes(customStyle)
StyleConstants.setSpaceAbove(customStyle, textProperties.spaceAbove.toFloat())
StyleConstants.setSpaceBelow(customStyle, textProperties.spaceBelow.toFloat())
customStyle
}
previous?.useInternalParagraphStyle == true -> INTERNAL_PARAGRAPH_STYLE
panelMode -> TASK_PARAGRAPH_STYLE
else -> BALLOON_STYLE
}
}
val messageParts: List<MessagePart> = lessonMessage.messageParts
lessonMessage.start = insertOffset
if (insertOffset != 0)
insertText("\n", paragraphStyle)
for (part in messageParts) {
part.updateTextAndSplit()
val startOffset = insertOffset
part.startOffset = startOffset
when (part.type) {
MessagePart.MessageType.TEXT_REGULAR -> insertText(part.text, REGULAR)
MessagePart.MessageType.TEXT_BOLD -> insertText(part.text, BOLD)
MessagePart.MessageType.SHORTCUT -> {
val start = insertOffset
appendShortcut(part)?.let { ranges.add(it) }
val end = insertOffset
highlighter.addHighlight(start, end) { g, _, _, _, _ ->
val bg = if (panelMode) UISettings.getInstance().shortcutBackgroundColor else UISettings.getInstance().tooltipShortcutBackgroundColor
val needColor = if (lessonMessage.state == MessageState.INACTIVE) Color(bg.red, bg.green, bg.blue, 255 * 3 / 10) else bg
for (p in part.splitMe()) {
drawRectangleAroundText(p.startOffset, p.endOffset, g as Graphics2D, needColor, fill = true)
}
}
}
MessagePart.MessageType.CODE -> {
val start = insertOffset
insertText(part.text, CODE)
val end = insertOffset
highlighter.addHighlight(start, end) { g, _, _, _, _ ->
val needColor = UISettings.getInstance().codeBorderColor
drawRectangleAroundText(start, end, g, needColor, fill = !panelMode)
}
}
MessagePart.MessageType.CHECK -> insertText(part.text, ROBOTO)
MessagePart.MessageType.LINK -> appendLink(part)?.let { ranges.add(it) }
MessagePart.MessageType.ICON_IDX -> {
insertIconWithFixedHeight(part.text, lessonMessage.state) {
// substitute fake height to place icon little lower
getFontMetrics([email protected]).ascent
}
}
MessagePart.MessageType.PROPOSE_RESTORE -> insertText(part.text, BOLD)
MessagePart.MessageType.ILLUSTRATION -> {
insertIconWithFixedHeight(part.text, lessonMessage.state) { icon ->
// reduce the icon height by the line height, because otherwise there will be extra space below the icon
icon.iconHeight - getFontMetrics([email protected]).height
}
paragraphStyle = INTERNAL_PARAGRAPH_STYLE
}
MessagePart.MessageType.LINE_BREAK -> {
insertText("\n", REGULAR)
paragraphStyle = INTERNAL_PARAGRAPH_STYLE
}
}
part.endOffset = insertOffset
}
lessonMessage.end = insertOffset
if (lessonMessage.state == MessageState.INACTIVE) {
setInactiveStyle(lessonMessage)
}
previous = lessonMessage
}
}
fun passPreviousMessages() {
for (message in activeMessages) {
message.state = MessageState.PASSED
}
redrawMessages()
}
private fun setInactiveStyle(lessonMessage: LessonMessage) {
styledDocument.setCharacterAttributes(lessonMessage.start, lessonMessage.end, INACTIVE, false)
}
fun clear() {
text = ""
activeMessages.clear()
restoreMessages.clear()
inactiveMessages.clear()
ranges.clear()
}
/**
* Appends link inside JTextPane to Run another lesson
* @param messagePart - should have LINK type. message.runnable starts when the message has been clicked.
*/
@Throws(BadLocationException::class)
private fun appendLink(messagePart: MessagePart): RangeData? {
val clickRange = appendClickableRange(messagePart.text, LINK)
val runnable = messagePart.runnable ?: return null
return RangeData(clickRange) { _, _ -> runnable.run() }
}
private fun appendShortcut(messagePart: MessagePart): RangeData? {
val split = messagePart.split
val range = if (split != null) {
var start = 0
val startRange = insertOffset
for (part in split) {
appendClickableRange(messagePart.text.substring(start, part.first), SHORTCUT_SEPARATOR)
appendClickableRange(messagePart.text.substring(part.first, part.last + 1), SHORTCUT)
start = part.last + 1
}
appendClickableRange(messagePart.text.substring(start), SHORTCUT_SEPARATOR)
startRange .. insertOffset
} else {
appendClickableRange(messagePart.text, SHORTCUT)
}
val actionId = messagePart.link ?: return null
val clickRange = IntRange(range.first + 1, range.last - 1) // exclude around spaces
return RangeData(clickRange) { p, h -> showShortcutBalloon(p, h, actionId) }
}
private fun showShortcutBalloon(point: Point2D, height: Int, actionName: String?) {
if (actionName == null) return
showActionKeyPopup(this, point.toPoint(), height, actionName)
}
private fun appendClickableRange(clickable: String, attributeSet: SimpleAttributeSet): IntRange {
if (clickable.isEmpty()) return insertOffset .. insertOffset
val startLink = insertOffset
insertText(clickable, attributeSet)
val endLink = insertOffset
return startLink..endLink
}
override fun paintComponent(g: Graphics) {
adjustCodeFontSize(g)
try {
highlightActiveMessage(g)
}
catch (e: BadLocationException) {
LOG.warn(e)
}
super.paintComponent(g)
paintLessonCheckmarks(g)
drawTaskNumbers(g)
}
private fun adjustCodeFontSize(g: Graphics) {
val fontSize = StyleConstants.getFontSize(CODE)
val labelFont = UISettings.getInstance().plainFont
val (numberFont, _, _) = getNumbersFont(labelFont, g)
if (numberFont.size != fontSize) {
StyleConstants.setFontSize(CODE, numberFont.size)
codeFontSize = numberFont.size
redrawMessages()
}
}
private fun paintLessonCheckmarks(g: Graphics) {
val plainFont = UISettings.getInstance().plainFont
val fontMetrics = g.getFontMetrics(plainFont)
val height = if (g is Graphics2D) letterHeight(plainFont, g, "A") else fontMetrics.height
val baseLineOffset = fontMetrics.ascent + fontMetrics.leading
for (lessonMessage in allLessonMessages()) {
var startOffset = lessonMessage.start
if (startOffset != 0) startOffset++
val rectangle = modelToView2D(startOffset).toRectangle()
if (lessonMessage.messageParts.singleOrNull()?.type == MessagePart.MessageType.ILLUSTRATION) {
continue
}
val icon = if (lessonMessage.state == MessageState.PASSED) {
FeaturesTrainerIcons.Img.GreenCheckmark
}
else if (!LessonManager.instance.lessonIsRunning()) {
AllIcons.General.Information
}
else continue
val xShift = icon.iconWidth + UISettings.getInstance().numberTaskIndent
val y = rectangle.y + baseLineOffset - (height + icon.iconHeight + 1) / 2
icon.paintIcon(this, g, rectangle.x - xShift, y)
}
}
private data class FontSearchResult(val numberFont: Font, val numberHeight: Int, val textLetterHeight: Int)
private fun drawTaskNumbers(g: Graphics) {
val oldFont = g.font
val labelFont = UISettings.getInstance().plainFont
val (numberFont, numberHeight, textLetterHeight) = getNumbersFont(labelFont, g)
val textFontMetrics = g.getFontMetrics(labelFont)
val baseLineOffset = textFontMetrics.ascent + textFontMetrics.leading
g.font = numberFont
fun paintNumber(lessonMessage: LessonMessage, color: Color) {
var startOffset = lessonMessage.start
if (startOffset != 0) startOffset++
val s = lessonMessage.visualIndex?.toString()?.padStart(2, '0') ?: return
val width = textFontMetrics.stringWidth(s)
val modelToView2D = modelToView2D(startOffset)
val rectangle = modelToView2D.toRectangle()
val xOffset = rectangle.x - (width + UISettings.getInstance().numberTaskIndent)
val baseLineY = rectangle.y + baseLineOffset
val yOffset = baseLineY + (numberHeight - textLetterHeight)
val backupColor = g.color
g.color = color
GraphicsUtil.setupAAPainting(g)
g.drawString(s, xOffset, yOffset)
g.color = backupColor
}
for (lessonMessage in inactiveMessages) {
paintNumber(lessonMessage, UISettings.getInstance().futureTaskNumberColor)
}
if (activeMessages.lastOrNull()?.state != MessageState.PASSED || !panelMode) { // lesson can be opened as passed
val firstActiveMessage = firstActiveMessage()
if (firstActiveMessage != null) {
val color = if (panelMode) UISettings.getInstance().activeTaskNumberColor else UISettings.getInstance().tooltipTaskNumberColor
paintNumber(firstActiveMessage, color)
}
}
g.font = oldFont
}
private fun getNumbersFont(textFont: Font, g: Graphics): FontSearchResult {
val style = Font.PLAIN
val monoFontName = FontPreferences.DEFAULT_FONT_NAME
if (g is Graphics2D) {
val textHeight = letterHeight(textFont, g, "A")
var size = textFont.size
var numberHeight = 0
lateinit var numberFont: Font
fun calculateHeight(): Int {
numberFont = Font(monoFontName, style, size)
numberHeight = letterHeight(numberFont, g, "0")
return numberHeight
}
calculateHeight()
if (numberHeight > textHeight) {
size--
while (calculateHeight() >= textHeight) {
size--
}
size++
calculateHeight()
}
else if (numberHeight < textHeight) {
size++
while (calculateHeight() < textHeight) {
size++
}
}
return FontSearchResult(numberFont, numberHeight, textHeight)
}
return FontSearchResult(Font(monoFontName, style, textFont.size), 0, 0)
}
private fun letterHeight(font: Font, g: Graphics2D, str: String): Int {
val gv: GlyphVector = font.createGlyphVector(g.fontRenderContext, str)
return gv.getGlyphMetrics(0).bounds2D.height.roundToInt()
}
@Throws(BadLocationException::class)
private fun highlightActiveMessage(g: Graphics) {
val g2d = g as Graphics2D
val lastActiveMessage = activeMessages.lastOrNull()
val firstActiveMessage = firstActiveMessage()
if (panelMode && lastActiveMessage != null && lastActiveMessage.state == MessageState.NORMAL) {
val c = UISettings.getInstance().activeTaskBorder
val a = if (totalAnimation == 0) 255 else 255 * currentAnimation / totalAnimation
val needColor = Color(c.red, c.green, c.blue, a)
drawRectangleAroundMessage(firstActiveMessage, lastActiveMessage, g2d, needColor)
}
}
private fun getInactiveIcon(icon: Icon) = WatermarkIcon(icon, UISettings.getInstance().transparencyInactiveFactor.toFloat())
private fun firstActiveMessage(): LessonMessage? = activeMessages.indexOfLast { it.state == MessageState.PASSED }
.takeIf { it != -1 && it < activeMessages.size - 1 }
?.let { activeMessages[it + 1] } ?: activeMessages.firstOrNull()
private fun drawRectangleAroundText(startOffset: Int,
endOffset: Int,
g: Graphics,
needColor: Color,
fill: Boolean) {
val g2d = g as Graphics2D
val rectangleStart = modelToView2D(startOffset)
val rectangleEnd = modelToView2D(endOffset)
val color = g2d.color
val fontSize = UISettings.getInstance().fontSize
g2d.color = needColor
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
val shift = if (SystemInfo.isMac) 1f else 2f
val r2d = RoundRectangle2D.Double(rectangleStart.x - 2 * indent, rectangleStart.y - indent + JBUIScale.scale(shift),
rectangleEnd.x - rectangleStart.x + 4 * indent, (fontSize + 2 * indent).toDouble(),
arc.toDouble(), arc.toDouble())
if (fill) g2d.fill(r2d) else g2d.draw(r2d)
g2d.color = color
}
private fun drawRectangleAroundMessage(lastPassedMessage: LessonMessage? = null,
lastActiveMessage: LessonMessage,
g2d: Graphics2D,
needColor: Color) {
val startOffset = lastPassedMessage?.let { if (it.start == 0) 0 else it.start + 1 } ?: 0
val endOffset = lastActiveMessage.end
val topLineY = modelToView2D(startOffset).y
val bottomLineY = modelToView2D(endOffset - 1).let { it.y + it.height }
val textHeight = bottomLineY - topLineY
val color = g2d.color
g2d.color = needColor
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
val xOffset = JBUI.scale(2).toDouble()
val yOffset = topLineY - activeTaskInset
val width = this.bounds.width - 2*xOffset - JBUIScale.scale(2) // 1 + 1 line width
val height = textHeight + 2 * activeTaskInset - JBUIScale.scale(2) + (lastActiveMessage.textProperties?.spaceBelow ?: 0)
g2d.draw(RoundRectangle2D.Double(xOffset, yOffset, width, height, arc.toDouble(), arc.toDouble()))
g2d.color = color
}
override fun getMaximumSize(): Dimension {
return preferredSize
}
companion object {
private val LOG = Logger.getInstance(LessonMessagePane::class.java)
//arc & indent for shortcut back plate
private val arc by lazy { JBUI.scale(4) }
private val indent by lazy { JBUI.scale(2) }
private val activeTaskInset by lazy { JBUI.scale(12) }
private fun Point2D.toPoint(): Point {
return Point(x.roundToInt(), y.roundToInt())
}
private fun Rectangle2D.toRectangle(): Rectangle {
return Rectangle(x.roundToInt(), y.roundToInt(), width.roundToInt(), height.roundToInt())
}
}
}
| apache-2.0 |
anthonycr/Lightning-Browser | app/src/main/java/acr/browser/lightning/preference/delegates/BooleanPreference.kt | 1 | 973 | package acr.browser.lightning.preference.delegates
import android.content.SharedPreferences
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
/**
* A [Boolean] delegate that is backed by [SharedPreferences].
*/
private class BooleanPreferenceDelegate(
private val name: String,
private val defaultValue: Boolean,
private val preferences: SharedPreferences
) : ReadWriteProperty<Any, Boolean> {
override fun getValue(thisRef: Any, property: KProperty<*>): Boolean =
preferences.getBoolean(name, defaultValue)
override fun setValue(thisRef: Any, property: KProperty<*>, value: Boolean) {
preferences.edit().putBoolean(name, value).apply()
}
}
/**
* Creates a [Boolean] from [SharedPreferences] with the provided arguments.
*/
fun SharedPreferences.booleanPreference(
name: String,
defaultValue: Boolean
): ReadWriteProperty<Any, Boolean> = BooleanPreferenceDelegate(name, defaultValue, this)
| mpl-2.0 |
rei-m/HBFav_material | app/src/main/kotlin/me/rei_m/hbfavmaterial/viewmodel/activity/BookmarkActivityViewModel.kt | 1 | 2567 | /*
* Copyright (c) 2017. Rei Matsushita
*
* 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 me.rei_m.hbfavmaterial.viewmodel.activity
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import android.databinding.ObservableField
import android.view.View
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.subjects.PublishSubject
import me.rei_m.hbfavmaterial.application.HatenaService
class BookmarkActivityViewModel(private val hatenaService: HatenaService) : ViewModel() {
val entryTitle: ObservableField<String> = ObservableField()
val entryLink: ObservableField<String> = ObservableField()
private var showBookmarkEditEventSubject = PublishSubject.create<Unit>()
val showBookmarkEditEvent: Observable<Unit> = showBookmarkEditEventSubject
private var unauthorisedEventSubject = PublishSubject.create<Unit>()
val unauthorisedEvent: Observable<Unit> = unauthorisedEventSubject
private val disposable = CompositeDisposable()
init {
disposable.addAll(hatenaService.confirmAuthorisedEvent.subscribe {
if (it) {
showBookmarkEditEventSubject.onNext(Unit)
} else {
unauthorisedEventSubject.onNext(Unit)
}
})
}
override fun onCleared() {
disposable.dispose()
super.onCleared()
}
@Suppress("UNUSED_PARAMETER")
fun onClickFab(view: View) {
hatenaService.confirmAuthorised()
}
fun onAuthoriseHatena() {
hatenaService.confirmAuthorised()
}
class Factory(private val hatenaService: HatenaService) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(BookmarkActivityViewModel::class.java)) {
return BookmarkActivityViewModel(hatenaService) as T
}
throw IllegalArgumentException("Unknown class name")
}
}
}
| apache-2.0 |
siosio/intellij-community | plugins/kotlin/jps/jps-plugin/tests/testData/incremental/classHierarchyAffected/inferredTypeArgumentChanged/useListOfAWithListOfB.kt | 5 | 60 | fun useListOfAWithListOfB() {
useListOfA(getListOfB())
} | apache-2.0 |
siosio/intellij-community | plugins/eclipse/testSources/org/jetbrains/idea/eclipse/EclipseEmlTest.kt | 1 | 1905 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.eclipse
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.testFramework.ApplicationRule
import com.intellij.testFramework.rules.ProjectModelRule
import com.intellij.testFramework.rules.TempDirectory
import com.intellij.util.io.copy
import org.junit.Assume.assumeTrue
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TestName
import java.nio.file.Path
import kotlin.io.path.ExperimentalPathApi
import kotlin.io.path.div
@ExperimentalPathApi
class EclipseEmlTest {
@JvmField
@Rule
val tempDirectory = TempDirectory()
@JvmField
@Rule
val testName = TestName()
@Test
fun testSrcInZip() {
doTest()
}
@Test
fun testPreserveInheritedInvalidJdk() {
doTest({ ModuleRootModificationUtil.setSdkInherited(ModuleManager.getInstance(it).modules.single()) },
{
val from = eclipseTestDataRoot / "eml" / "preserveInheritedInvalidJdk" / "test" / "expected" / "preserveInheritedInvalidJdk.eml"
from.copy(it / "test" / "preserveInheritedInvalidJdk.eml")
})
}
private fun doTest(edit: (Project) -> Unit = {}, updateExpectedDir: (Path) -> Unit = {}) {
val testName = testName.methodName.removePrefix("test").decapitalize()
val testRoot = eclipseTestDataRoot / "eml" / testName
val commonRoot = eclipseTestDataRoot / "common" / "testModuleWithClasspathStorage"
checkEmlFileGeneration(listOf(testRoot, commonRoot), tempDirectory, listOf("test" to "test/$testName"), edit, updateExpectedDir)
}
companion object {
@JvmField
@ClassRule
val appRule = ApplicationRule()
}
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/dfa/basicIn.kt | 1 | 136 | // PROBLEM: Condition is always false
// FIX: none
fun test(obj : Int) {
if (obj > 10) {
if (<caret>obj in 1..5) {}
}
}
| apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/formatter/RightBracketOnNewLine.after.kt | 5 | 124 | class Test {
fun someLong(a: Int
) {
}
}
// SET_FALSE: ALIGN_MULTILINE_METHOD_BRACKETS
// TRAILING_COMMA: false | apache-2.0 |
kivensolo/UiUsingListView | app-Kotlin-Coroutines-Examples/src/main/java/com/kingz/coroutines/learn/errorhandling/exceptionhandler/ExceptionHandlerActivity.kt | 1 | 3150 | package com.kingz.coroutines.learn.errorhandling.exceptionhandler
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.kingz.base.response.Status
import com.kingz.coroutines.data.api.ApiHelperImpl
import com.kingz.coroutines.data.api.RetrofitBuilder
import com.kingz.coroutines.data.local.DatabaseBuilder
import com.kingz.coroutines.data.local.DatabaseHelperImpl
import com.kingz.coroutines.data.model.ApiUser
import com.kingz.coroutines.learn.base.ApiUserAdapter
import com.kingz.coroutines.utils.ViewModelFactory
import com.zeke.example.coroutines.R
import kotlinx.android.synthetic.main.activity_recycler_view.*
/**
* Learn how to handle error in Kotlin Coroutines using CoroutineExceptionHandler.
*/
class ExceptionHandlerActivity : AppCompatActivity() {
private lateinit var viewModel: ExceptionHandlerViewModel
private lateinit var adapter: ApiUserAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_recycler_view)
setupUI()
setupViewModel()
setupObserver()
}
private fun setupUI() {
recyclerView.layoutManager = LinearLayoutManager(this)
adapter =
ApiUserAdapter(
arrayListOf()
)
recyclerView.addItemDecoration(
DividerItemDecoration(
recyclerView.context,
(recyclerView.layoutManager as LinearLayoutManager).orientation
)
)
recyclerView.adapter = adapter
}
private fun setupObserver() {
viewModel.getUsers().observe(this, Observer {
when (it.status) {
Status.SUCCESS -> {
progressBar.visibility = View.GONE
it.data?.let { users -> renderList(users) }
recyclerView.visibility = View.VISIBLE
}
Status.LOADING -> {
progressBar.visibility = View.VISIBLE
recyclerView.visibility = View.GONE
}
Status.ERROR -> {
//Handle Error
progressBar.visibility = View.GONE
Toast.makeText(this, it.message, Toast.LENGTH_LONG).show()
}
}
})
}
private fun renderList(users: List<ApiUser>) {
adapter.addData(users)
adapter.notifyDataSetChanged()
}
private fun setupViewModel() {
viewModel = ViewModelProvider(
this,
ViewModelFactory.build {
ExceptionHandlerViewModel(
ApiHelperImpl(RetrofitBuilder.USER_SERVICE_API),
DatabaseHelperImpl(DatabaseBuilder.getInstance(applicationContext))
)
}
).get(ExceptionHandlerViewModel::class.java)
}
}
| gpl-2.0 |
alisle/Penella | src/test/java/org/penella/codecs/DatabaseQueryCodecTest.kt | 1 | 2087 | package org.penella.codecs
import com.fasterxml.jackson.module.kotlin.KotlinModule
import io.vertx.core.buffer.Buffer
import io.vertx.core.json.Json
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.penella.messages.DatabaseBulkAddTriples
import org.penella.messages.DatabaseQuery
import org.penella.query.Query
import org.penella.structures.triples.Triple
/**
* 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.
*
*
* Created by alisle on 1/27/17.
*/
class DatabaseQueryCodecTest {
@Before
fun setUp() {
Json.mapper.registerModule(KotlinModule())
}
@Test
fun testName() {
val codec = DatabaseQueryCodec()
Assert.assertEquals(codec.name(), "DatabaseQuery")
}
@Test
fun testEncodeDecode() {
val codec = DatabaseQueryCodec()
val buffer = Buffer.buffer()
val value = DatabaseQuery(Query(arrayOf("Hello", "World"), arrayOf("I am a variable", "So am I"), arrayOf(Triple("S0", "P0", "O0"), Triple("S1", "P1", "O1"), Triple("S2", "P2", "O2"))))
codec.encodeToWire(buffer, value)
val codecValue = codec.decodeFromWire(0, buffer)
Assert.assertEquals(value, codecValue )
}
@Test
fun testTransform() {
val codec = DatabaseQueryCodec()
val value = DatabaseQuery(Query(arrayOf("Hello", "World"), arrayOf("I am a variable", "So am I"), arrayOf(Triple("S0", "P0", "O0"), Triple("S1", "P1", "O1"), Triple("S2", "P2", "O2"))))
val codecValue = codec.transform(value)
Assert.assertEquals(value, codecValue)
}
} | apache-2.0 |
jwren/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/vfilefinder/IDEVirtualFileFinder.kt | 1 | 2062 | // 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.vfilefinder
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.indexing.FileBasedIndex
import com.intellij.util.indexing.ID
import org.jetbrains.kotlin.load.kotlin.VirtualFileFinder
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import java.io.FileNotFoundException
import java.io.InputStream
class IDEVirtualFileFinder(private val scope: GlobalSearchScope) : VirtualFileFinder() {
override fun findMetadata(classId: ClassId): InputStream? {
val file = findVirtualFileWithHeader(classId.asSingleFqName(), KotlinMetadataFileIndex.KEY) ?: return null
return try {
file.inputStream
} catch (e: FileNotFoundException) {
null
}
}
override fun hasMetadataPackage(fqName: FqName): Boolean = KotlinMetadataFilePackageIndex.hasSomethingInPackage(fqName, scope)
override fun findBuiltInsData(packageFqName: FqName): InputStream? =
findVirtualFileWithHeader(packageFqName, KotlinBuiltInsMetadataIndex.KEY)?.inputStream
override fun findSourceOrBinaryVirtualFile(classId: ClassId) = findVirtualFileWithHeader(classId)
init {
if (scope != GlobalSearchScope.EMPTY_SCOPE && scope.project == null) {
LOG.warn("Scope with null project $scope")
}
}
override fun findVirtualFileWithHeader(classId: ClassId): VirtualFile? =
findVirtualFileWithHeader(classId.asSingleFqName(), KotlinClassFileIndex.KEY)
private fun findVirtualFileWithHeader(fqName: FqName, key: ID<FqName, Void>): VirtualFile? =
FileBasedIndex.getInstance().getContainingFiles(key, fqName, scope).firstOrNull()
companion object {
private val LOG = Logger.getInstance(IDEVirtualFileFinder::class.java)
}
}
| apache-2.0 |
BijoySingh/Quick-Note-Android | base/src/main/java/com/maubis/scarlet/base/security/sheets/NoPincodeBottomSheet.kt | 1 | 2649 | package com.maubis.scarlet.base.security.sheets
import android.app.Dialog
import com.facebook.litho.Column
import com.facebook.litho.Component
import com.facebook.litho.ComponentContext
import com.facebook.litho.widget.Text
import com.facebook.yoga.YogaEdge
import com.maubis.scarlet.base.R
import com.maubis.scarlet.base.config.ApplicationBase.Companion.sAppPreferences
import com.maubis.scarlet.base.config.ApplicationBase.Companion.sAppTheme
import com.maubis.scarlet.base.config.ApplicationBase.Companion.sAppTypeface
import com.maubis.scarlet.base.support.sheets.LithoBottomSheet
import com.maubis.scarlet.base.support.sheets.getLithoBottomSheetTitle
import com.maubis.scarlet.base.support.specs.BottomSheetBar
import com.maubis.scarlet.base.support.ui.ThemeColorType
import com.maubis.scarlet.base.support.ui.ThemedActivity
const val STORE_KEY_NO_PIN_ASK = "KEY_NO_PIN_ASK"
var sNoPinSetupNoticeShown: Boolean
get() = sAppPreferences.get(STORE_KEY_NO_PIN_ASK, false)
set(value) = sAppPreferences.put(STORE_KEY_NO_PIN_ASK, value)
class NoPincodeBottomSheet : LithoBottomSheet() {
var onSuccess: () -> Unit = {}
override fun getComponent(componentContext: ComponentContext, dialog: Dialog): Component {
val activity = context as ThemedActivity
val component = Column.create(componentContext)
.widthPercent(100f)
.paddingDip(YogaEdge.VERTICAL, 8f)
.paddingDip(YogaEdge.HORIZONTAL, 20f)
.child(
getLithoBottomSheetTitle(componentContext)
.textRes(R.string.no_pincode_sheet_title)
.marginDip(YogaEdge.HORIZONTAL, 0f))
.child(
Text.create(componentContext)
.typeface(sAppTypeface.text())
.textSizeRes(R.dimen.font_size_large)
.textRes(R.string.no_pincode_sheet_details)
.marginDip(YogaEdge.BOTTOM, 16f)
.textColor(sAppTheme.get(ThemeColorType.TERTIARY_TEXT)))
.child(BottomSheetBar.create(componentContext)
.primaryActionRes(R.string.no_pincode_sheet_set_up)
.onPrimaryClick {
openCreateSheet(
activity = activity,
onCreateSuccess = {})
dismiss()
}
.secondaryActionRes(R.string.no_pincode_sheet_dont_ask)
.onSecondaryClick {
onSuccess()
dismiss()
}
.tertiaryActionRes(R.string.no_pincode_sheet_not_now)
.onTertiaryClick {
onSuccess()
dismiss()
}
.paddingDip(YogaEdge.VERTICAL, 8f))
return component.build()
}
}
| gpl-3.0 |
K0zka/kerub | src/test/kotlin/com/github/kerubistan/kerub/data/ispn/VirtualMachineDynamicDaoImplTest.kt | 2 | 1809 | package com.github.kerubistan.kerub.data.ispn
import com.github.kerubistan.kerub.data.EventListener
import com.github.kerubistan.kerub.data.HistoryDao
import com.github.kerubistan.kerub.data.dynamic.VirtualMachineDynamicDao
import com.github.kerubistan.kerub.model.VirtualMachineStatus
import com.github.kerubistan.kerub.model.dynamic.VirtualMachineDynamic
import com.nhaarman.mockito_kotlin.mock
import io.github.kerubistan.kroki.size.GB
import org.infinispan.Cache
import org.infinispan.manager.DefaultCacheManager
import org.junit.After
import org.junit.Before
import org.junit.Test
import java.util.UUID
import kotlin.test.assertEquals
class VirtualMachineDynamicDaoImplTest {
private val eventListener: EventListener = mock()
private var cacheManager: DefaultCacheManager? = null
private var cache: Cache<UUID, VirtualMachineDynamic>? = null
private var historyDao = mock<HistoryDao<VirtualMachineDynamic>>()
private var dao: VirtualMachineDynamicDao? = null
@Before
fun setup() {
cacheManager = DefaultCacheManager()
cacheManager!!.start()
cache = cacheManager!!.getCache("test")
cache!!.clear()
dao = VirtualMachineDynamicDaoImpl(cache!!, historyDao, eventListener)
}
@After fun cleanup() {
cacheManager?.stop()
}
@Test
fun findByHostId() {
val host1Id = UUID.randomUUID()
val host2Id = UUID.randomUUID()
val dyn1 = VirtualMachineDynamic(
id = UUID.randomUUID(),
hostId = host1Id,
status = VirtualMachineStatus.Up,
memoryUsed = 1.GB
)
val dyn2 = VirtualMachineDynamic(
id = UUID.randomUUID(),
hostId = host2Id,
status = VirtualMachineStatus.Up,
memoryUsed = 1.GB
)
dao!!.add(dyn1)
dao!!.add(dyn2)
assertEquals(dao!!.findByHostId(host1Id), listOf(dyn1))
assertEquals(dao!!.findByHostId(host2Id), listOf(dyn2))
}
} | apache-2.0 |
K0zka/kerub | src/main/kotlin/com/github/kerubistan/kerub/model/AccountMembership.kt | 2 | 905 | package com.github.kerubistan.kerub.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonTypeName
import org.hibernate.search.annotations.Analyze
import org.hibernate.search.annotations.DocumentId
import org.hibernate.search.annotations.Field
import org.hibernate.search.annotations.Index
import org.hibernate.search.annotations.Indexed
import org.hibernate.search.annotations.Store
import java.util.UUID
@Indexed
@JsonTypeName("account-membership")
data class AccountMembership(
@Field(analyze = Analyze.NO)
override val user: String,
@Field(analyze = Analyze.NO)
override val groupId: UUID,
override val quota: Quota? = null,
@DocumentId
override val id: UUID = UUID.randomUUID()
) : GroupMembership {
val groupIdStr: String
@Field(store = Store.YES, index = Index.YES, analyze = Analyze.NO)
@JsonIgnore
get() = groupId.toString()
} | apache-2.0 |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/highlighter/KotlinTestRunLineMarkerContributor.kt | 1 | 5639 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.highlighter
import com.intellij.execution.TestStateStorage
import com.intellij.execution.lineMarker.ExecutorAction
import com.intellij.execution.lineMarker.RunLineMarkerContributor
import com.intellij.psi.PsiElement
import com.intellij.util.Function
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.configuration.isGradleModule
import org.jetbrains.kotlin.idea.platform.tooling
import org.jetbrains.kotlin.idea.project.platform
import org.jetbrains.kotlin.idea.run.KotlinMainFunctionLocatingService
import org.jetbrains.kotlin.idea.testIntegration.framework.KotlinTestFramework
import org.jetbrains.kotlin.idea.util.isUnderKotlinSourceRootTypes
import org.jetbrains.kotlin.idea.util.projectStructure.module
import org.jetbrains.kotlin.konan.target.HostManager
import org.jetbrains.kotlin.konan.target.KonanTarget
import org.jetbrains.kotlin.platform.SimplePlatform
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.idePlatformKind
import org.jetbrains.kotlin.platform.isMultiPlatform
import org.jetbrains.kotlin.platform.konan.NativePlatformWithTarget
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClass
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import javax.swing.Icon
class KotlinTestRunLineMarkerContributor : RunLineMarkerContributor() {
companion object {
private fun KtNamedDeclaration.getTestFramework(): KotlinTestFramework? =
KotlinTestFramework.getApplicableFor(this)
private fun KtNamedFunction.isIgnored(): Boolean {
return getTestFramework()?.isIgnoredMethod(this) ?: false
}
fun getTestStateIcon(urls: List<String>, declaration: KtNamedDeclaration): Icon {
val testStateStorage = TestStateStorage.getInstance(declaration.project)
val isClass = declaration is KtClass
val state: TestStateStorage.Record? = run {
for (url in urls) {
testStateStorage.getState(url)?.let { return@run it }
}
null
}
return getTestStateIcon(state, isClass)
}
fun SimplePlatform.providesRunnableTests(): Boolean {
if (this is NativePlatformWithTarget) {
return when {
HostManager.hostIsMac -> target in listOf(
KonanTarget.IOS_X64,
KonanTarget.MACOS_X64,
KonanTarget.WATCHOS_X64, KonanTarget.WATCHOS_X86,
KonanTarget.TVOS_X64
)
HostManager.hostIsLinux -> target == KonanTarget.LINUX_X64
HostManager.hostIsMingw -> target in listOf(KonanTarget.MINGW_X86, KonanTarget.MINGW_X64)
else -> false
}
}
return true
}
fun TargetPlatform.providesRunnableTests(): Boolean = componentPlatforms.any { it.providesRunnableTests() }
}
override fun getInfo(element: PsiElement): Info? = calculateIcon(element, false)
override fun getSlowInfo(element: PsiElement): Info? = calculateIcon(element, true)
private fun calculateIcon(
element: PsiElement,
includeSlowProviders: Boolean
): Info? {
val declaration = element.getStrictParentOfType<KtNamedDeclaration>()?.takeIf { it.nameIdentifier == element } ?: return null
val targetPlatform = declaration.module?.platform ?: return null
if (declaration is KtNamedFunction) {
if (declaration.containingClassOrObject == null ||
targetPlatform.isMultiPlatform() && declaration.containingClass() == null) return null
if (declaration.isIgnored() && declaration.module?.isGradleModule() == true) return null
} else {
if (declaration !is KtClassOrObject ||
targetPlatform.isMultiPlatform() && declaration !is KtClass
) return null
}
if (!targetPlatform.providesRunnableTests()) return null
if (!declaration.isUnderKotlinSourceRootTypes()) return null
val icon = targetPlatform.idePlatformKind.tooling.getTestIcon(
declaration = declaration,
descriptorProvider = {
declaration.resolveToDescriptorIfAny()
},
includeSlowProviders = includeSlowProviders
) ?: return null
return Info(
icon,
Function { KotlinBundle.message("highlighter.tool.tip.text.run.test") },
*ExecutorAction.getActions(getOrder(declaration))
)
}
private fun getOrder(declaration: KtNamedDeclaration): Int {
val mainFunctionDetector = KotlinMainFunctionLocatingService.getInstance()
if (declaration is KtClassOrObject && mainFunctionDetector.hasMain(declaration.companionObjects)) {
return 1
}
if (declaration is KtNamedFunction) {
val declarations = declaration.containingClassOrObject?.declarations ?: return 0
if (mainFunctionDetector.hasMain(declarations)) return 1
return 0
}
val file = declaration.containingFile
return if (file is KtFile && mainFunctionDetector.hasMain(file.declarations)) 1 else 0
}
}
| apache-2.0 |
K0zka/kerub | src/main/kotlin/com/github/kerubistan/kerub/planner/steps/host/ksm/DisableKsm.kt | 2 | 792 | package com.github.kerubistan.kerub.planner.steps.host.ksm
import com.fasterxml.jackson.annotation.JsonTypeName
import com.github.kerubistan.kerub.model.Host
import com.github.kerubistan.kerub.planner.OperationalState
import com.github.kerubistan.kerub.planner.steps.AbstractOperationalStep
import com.github.kerubistan.kerub.planner.steps.InvertibleStep
import com.github.kerubistan.kerub.planner.steps.ProducedBy
import com.github.kerubistan.kerub.planner.steps.vm.base.HostStep
@ProducedBy(KsmFactory::class)
@JsonTypeName("disable-ksm")
data class DisableKsm(override val host: Host) : HostStep, InvertibleStep {
override fun isInverseOf(other: AbstractOperationalStep) = other is EnableKsm && other.host == host
override fun take(state: OperationalState): OperationalState = state
} | apache-2.0 |
jwren/intellij-community | plugins/kotlin/completion/tests/testData/basic/common/substitutedSignature/SubstitutedSignature2.kt | 8 | 219 | // FIR_IDENTICAL
// FIR_COMPARISON
open class C<T> {
fun foo(t: T): T = t
}
class B : C<String>() {
fun f() {
<caret>
}
}
// EXIST: { itemText: "foo", tailText: "(t: String)", typeText: "String" }
| apache-2.0 |
jwren/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/style/GrUnnecessaryModifierInspection.kt | 3 | 1737 | // 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.codeInspection.style
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.util.elementType
import org.jetbrains.plugins.groovy.GroovyBundle
import org.jetbrains.plugins.groovy.codeInspection.bugs.GrModifierFix
import org.jetbrains.plugins.groovy.codeInspection.bugs.GrRemoveModifierFix
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier
import org.jetbrains.plugins.groovy.lang.psi.impl.auxiliary.modifiers.GrModifierListImpl
abstract class GrUnnecessaryModifierInspection(@GrModifier.GrModifierConstant val modifier: String) : LocalInspectionTool(), CleanupLocalInspectionTool {
private fun getFix(): GrModifierFix {
return GrRemoveModifierFix(modifier)
}
private val requiredElementType = GrModifierListImpl.NAME_TO_MODIFIER_ELEMENT_TYPE[modifier]!!
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = object : PsiElementVisitor() {
override fun visitElement(element: PsiElement) {
if (element.elementType === requiredElementType && isRedundant(element)) {
holder.registerProblem(
element,
GroovyBundle.message("unnecessary.modifier.description", modifier),
getFix()
)
}
}
}
/**
* [element] has element type that corresponds to [modifier]
*/
abstract fun isRedundant(element: PsiElement): Boolean
} | apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/gradle/hierarchicalMultiplatformImport/kT46417NativePlatformTestSourceSets/p1/src/iosTest/kotlin/P1IosTest.kt | 10 | 441 | import kotlin.test.Test
import kotlin.test.assertEquals
class P1IosTest {
@Test
fun testCommonMain() {
val x = P1CommonMain()
assertEquals(x.invoke(), P1CommonMain())
}
@Test
fun testNativeMain() {
val x = P1NativeMain()
assertEquals(x.invoke(), P1NativeMain())
}
@Test
fun testIosMain() {
val x = P1IosMain()
assertEquals(x.invoke(), P1IosMain())
}
}
| apache-2.0 |
youdonghai/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/GrReferenceResolveRunner.kt | 1 | 7021 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.resolve
import com.intellij.psi.*
import com.intellij.psi.scope.PsiScopeProcessor
import com.intellij.psi.util.InheritanceUtil
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes
import org.jetbrains.plugins.groovy.lang.psi.api.SpreadState
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationArrayInitializer
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationNameValuePair
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.psi.impl.GrTraitType
import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyPsiManager
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil
import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.ClosureParameterEnhancer
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil
import org.jetbrains.plugins.groovy.lang.resolve.processors.ClassHint
class GrReferenceResolveRunner(val place: GrReferenceExpression, val processor: PsiScopeProcessor) {
fun resolveReferenceExpression(): Boolean {
val processNonCode = PsiTreeUtil.skipParentsOfType(
place, GrReferenceExpression::class.java, GrAnnotationArrayInitializer::class.java
) !is GrAnnotationNameValuePair
val initialState = initialState(processNonCode)
val qualifier = place.qualifier
if (qualifier == null) {
if (!treeWalkUp(place, processor, initialState)) return false
if (!processNonCode) return true
if (place.context is GrMethodCall && !ClosureMissingMethodContributor.processMethodsFromClosures(place, processor)) return false
}
else {
if (place.dotTokenType === GroovyTokenTypes.mSPREAD_DOT) {
val qType = qualifier.type
val componentType = ClosureParameterEnhancer.findTypeForIteration(qType, place)
if (componentType != null) {
val state = initialState.put(ClassHint.RESOLVE_CONTEXT, qualifier).put(SpreadState.SPREAD_STATE, SpreadState.create(qType, null))
return processQualifierType(componentType, state)
}
}
else {
if (ResolveUtil.isClassReference(place)) return false
if (!processJavaLangClass(qualifier, initialState)) return false
if (!processQualifier(qualifier, initialState)) return false
}
}
return true
}
private fun processJavaLangClass(qualifier: GrExpression, initialState: ResolveState): Boolean {
if (qualifier !is GrReferenceExpression) return true
//optimization: only 'class' or 'this' in static context can be an alias of java.lang.Class
if ("class" != qualifier.referenceName && !PsiUtil.isThisReference(qualifier) && qualifier.resolve() !is PsiClass) return true
val classType = ResolveUtil.unwrapClassType(qualifier.getType())
return classType?.let {
val state = initialState.put(ClassHint.RESOLVE_CONTEXT, qualifier)
processQualifierType(classType, state)
} ?: true
}
private fun processQualifier(qualifier: GrExpression, initialState: ResolveState): Boolean {
val qualifierType = qualifier.type
val state = initialState.put(ClassHint.RESOLVE_CONTEXT, qualifier)
if (qualifierType == null || PsiType.VOID == qualifierType) {
if (qualifier is GrReferenceExpression) {
val resolved = qualifier.resolve()
if (resolved is PsiClass) {
if (!ResolveUtil.processClassDeclarations((resolved as PsiClass?)!!, processor, state, null, place)) return false
}
else if (resolved != null && !resolved.processDeclarations(processor, state, null, place)) return false
if (resolved !is PsiPackage) {
val objectQualifier = TypesUtil.getJavaLangObject(place)
if (!processQualifierType(objectQualifier, state)) return false
}
}
}
else {
if (!processQualifierType(qualifierType, state)) return false
}
return true
}
private fun processQualifierType(qualifierType: PsiType, state: ResolveState): Boolean {
val type = (qualifierType as? PsiDisjunctionType)?.leastUpperBound ?: qualifierType
return doProcessQualifierType(type, state)
}
private fun doProcessQualifierType(qualifierType: PsiType, state: ResolveState): Boolean {
if (qualifierType is PsiIntersectionType) {
return qualifierType.conjuncts.find { !processQualifierType(it, state) } == null
}
if (qualifierType is PsiCapturedWildcardType) {
val wildcard = qualifierType.wildcard
if (wildcard.isExtends) {
return processQualifierType(wildcard.extendsBound, state)
}
}
// Process trait type conjuncts in reversed order because last applied trait matters.
if (qualifierType is GrTraitType) return qualifierType.conjuncts.findLast { !processQualifierType(it, state) } == null
if (qualifierType is PsiClassType) {
val qualifierResult = qualifierType.resolveGenerics()
qualifierResult.element?.let {
val resolveState = state.put(PsiSubstitutor.KEY, qualifierResult.substitutor)
if (!ResolveUtil.processClassDeclarations(it, processor, resolveState, null, place)) return false
}
}
else if (qualifierType is PsiArrayType) {
GroovyPsiManager.getInstance(place.project).getArrayClass(qualifierType.componentType)?.let {
if (!ResolveUtil.processClassDeclarations(it, processor, state, null, place)) return false
}
}
if (place.parent !is GrMethodCall && InheritanceUtil.isInheritor(qualifierType, CommonClassNames.JAVA_UTIL_COLLECTION)) {
ClosureParameterEnhancer.findTypeForIteration(qualifierType, place)?.let {
val spreadState = state.get(SpreadState.SPREAD_STATE)
val resolveState = state.put(SpreadState.SPREAD_STATE, SpreadState.create(qualifierType, spreadState))
if (!processQualifierType(it, resolveState)) return false
}
}
if (state.processNonCodeMembers()) {
if (!ResolveUtil.processCategoryMembers(place, processor, state)) return false
if (!ResolveUtil.processNonCodeMembers(qualifierType, processor, place, state)) return false
}
return true
}
}
| apache-2.0 |
oldcwj/iPing | app/src/main/java/com/wpapper/iping/ui/utils/hub/SimpleHUD.kt | 1 | 1050 | package com.wpapper.iping.ui.utils.hub
import android.content.Context
object SimpleHUD {
private var dialog: SimpleHUDDialog? = null
fun show(context: Context, msgRes: Int, cancelable: Boolean) {
show(context, context.getString(msgRes), cancelable)
}
fun show(context: Context, msg: String, cancelable: Boolean) {
dismiss()
setupDialog(context, msg, cancelable)
try {
dialog!!.show()
} catch (ex: Exception) {
}
}
fun setMessage(context: Context, msg: String) {
dialog?.setMessage(msg)
}
private fun setupDialog(ctx: Context, msg: String, cancelable: Boolean) {
dialog = SimpleHUDDialog.createDialog(ctx)
dialog!!.setMessage(msg)
dialog!!.setCanceledOnTouchOutside(false)
dialog!!.setCancelable(cancelable)
}
fun dismiss() {
if (dialog?.isShowing ?: false)
try {
dialog!!.dismiss()
} catch (ex: Exception) {
}
dialog = null
}
}
| gpl-3.0 |
androidx/androidx | inspection/inspection-testing/src/androidTest/java/androidx/inspection/testing/echo/EchoInspector.kt | 3 | 2557 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.inspection.testing.echo
import androidx.inspection.Connection
import androidx.inspection.Inspector
import androidx.inspection.InspectorEnvironment
import androidx.inspection.InspectorFactory
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import java.util.concurrent.Executor
/**
* An inspector for test purposes, it echoes on commands and sends events once
* [TickleManager] is tickled.
*/
class EchoInspector(connection: Connection) : Inspector(connection) {
private val scope = CoroutineScope(Dispatchers.Default)
private var tickleCounter: Byte = 1
init {
scope.launch {
TickleManager.tickles.collect {
connection.sendEvent("counter: ${tickleCounter++}".toByteArray())
}
}
}
override fun onReceiveCommand(data: ByteArray, callback: CommandCallback) {
val command = String(data)
if (command == "<cancellation-test>") {
callback.addCancellationListener(
DirectExecutor,
Runnable {
connection.sendEvent("cancellation: successfully cancelled".toByteArray())
}
)
connection.sendEvent("cancellation: listener added".toByteArray())
} else {
callback.reply("echoed: $command".toByteArray())
}
}
override fun onDispose() {
scope.cancel()
}
}
const val ECHO_INSPECTION_ID = "androidx.inspection.testing.echo"
object DirectExecutor : Executor {
override fun execute(command: Runnable) {
command.run()
}
}
class EchoInspectorFactory : InspectorFactory<EchoInspector>(ECHO_INSPECTION_ID) {
override fun createInspector(connection: Connection, unusedEnvironment: InspectorEnvironment) =
EchoInspector(connection)
} | apache-2.0 |
pokk/SSFM | app/src/main/kotlin/taiwan/no1/app/ssfm/misc/utilies/PausableTimer.kt | 1 | 2008 | package taiwan.no1.app.ssfm.misc.utilies
import android.os.CountDownTimer
/**
* Countdown timer with the pause function.
*
* @author jieyi
* @since 7/23/17
*/
class PausableTimer(private val millisInFuture: Long = -1,
private val countDownInterval: Long = 1000) {
var onTick: (millisUntilFinished: Long) -> Unit = {}
var onFinish: () -> Unit = {}
var isPause = false
var isStart = false
var curTime = 0L
lateinit private var timer: CountDownTimer
init {
val millisTime = if (-1L == millisInFuture) Long.MAX_VALUE else millisInFuture
init(millisTime, countDownInterval)
}
fun pause(): Long {
isPause = true
stop()
return curTime
}
fun resume() {
val time = if (isPause && 0 <= curTime) {
isPause = false
curTime
}
else {
millisInFuture
}
stop()
init(time, countDownInterval)
start()
}
fun start() {
if (!isStart && !isPause) {
if (0L == curTime) {
init(millisInFuture, countDownInterval)
}
timer.start()
isStart = true
}
else if (isPause) {
resume()
}
}
fun stop() {
timer.cancel()
isStart = false
}
private fun init(millisInFuture: Long, countDownInterval: Long) {
timer = object : CountDownTimer(millisInFuture, countDownInterval) {
override fun onTick(millisUntilFinished: Long) {
// OPTIMIZE(jieyi): 9/29/17
// val time = (Math.round(millisUntilFinished.toDouble() / 1000) - 1).toInt()
[email protected] = millisUntilFinished
[email protected](millisUntilFinished)
}
override fun onFinish() {
[email protected] = 0
[email protected]()
}
}
}
} | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/maven/tests/testData/languageFeature/addKotlinReflect/src.kt | 26 | 114 | import kotlin.reflect.full.*
class Foo(val prop: Any) {
fun func() {}
}
fun y01() = Foo::prop.gett<caret>er
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.