content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package testing.kt
open class KotlinBase {
open fun <caret>test() {}
}
// REF: of testing.jj.JavaBase.test()
| plugins/kotlin/idea/tests/testData/navigation/implementations/multifile/ImplementFunInJava/ImplementFunInJava.kt | 475681902 |
// 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.util
import kotlinx.coroutines.CoroutineScope
import org.jetbrains.annotations.ApiStatus.Experimental
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
/**
* Creates a new instance of the [Lazy] that uses the specified initialization function [initializer].
*
* If the initialization of a value recurs or throws an exception,
* it will attempt to reinitialize the value at next access.
*
* The returned instance uses the specified [recursionKey] object as computation ID
* to check if [this computation][initializer] is already running on the current thread.
* When the [recursionKey] is not specified the instance uses itself as computation ID.
*
* @see com.intellij.openapi.util.RecursionGuard.doPreventingRecursion
*/
fun <T> recursionSafeLazy(recursionKey: Any? = null, initializer: () -> T): Lazy<T?> {
return RecursionPreventingSafePublicationLazy(recursionKey, initializer)
}
fun <T> lazyPub(initializer: () -> T): Lazy<T> = lazy(LazyThreadSafetyMode.PUBLICATION, initializer)
/**
* Creates a new instance of [SuspendingLazy] that uses the specified initialization function [initializer].
*
* If the initializer is running, and coroutines suspended in [SuspendingLazy.getValue] are cancelled,
* then the [initializer] gets also cancelled, and the next call to [SuspendingLazy.getValue] will start the initializer from scratch.
*
* Once the initialized completes, the [SuspendingLazy] is considered completed.
* Once completed, hard references to [this], [initializerContext] and [initializer] are erased,
* and the returned instance only references the result.
*
* If the [initializer] throws, the throwable is stored in the returned instance, and this [SuspendingLazy] is also considered completed.
* Suspended and subsequent [SuspendingLazy.getValue] calls are resumed with the thrown instance.
*/
@Experimental
fun <T> CoroutineScope.suspendingLazy(
initializerContext: CoroutineContext = EmptyCoroutineContext,
initializer: suspend CoroutineScope.() -> T,
): SuspendingLazy<T> {
return SuspendingLazyImpl(this, initializerContext, initializer)
}
| platform/util-ex/src/com/intellij/util/lazy.kt | 2259021158 |
// "Remove suppression" "true"
@Suppress("<caret>MoveVariableDeclarationIntoWhen")
fun function() {
}
// TOOL: com.intellij.codeInspection.RedundantSuppressInspection
// TOOL: org.jetbrains.kotlin.idea.inspections.MoveVariableDeclarationIntoWhenInspection
| plugins/kotlin/idea/tests/testData/quickfix/suppress/redundant/RemoveAnnotation.kt | 3675160328 |
// 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.util
import com.intellij.openapi.Disposable
import com.intellij.openapi.progress.util.BackgroundTaskUtil
import com.intellij.openapi.util.Computable
@Deprecated("Use 'com.intellij.openapi.progress.util.BackgroundTaskUtil' instead")
object ProgressIndicatorUtils {
@Deprecated(
"Use 'com.intellij.openapi.progress.util.BackgroundTaskUtil.runUnderDisposeAwareIndicator()' instead",
ReplaceWith(
"BackgroundTaskUtil.runUnderDisposeAwareIndicator(parent, Computable { computable() })",
imports = ["com.intellij.openapi.progress.util.BackgroundTaskUtil", "com.intellij.openapi.util.Computable"]
)
)
fun <T> runUnderDisposeAwareIndicator(parent: Disposable, computable: () -> T): T {
return BackgroundTaskUtil.runUnderDisposeAwareIndicator(parent, Computable { computable() })
}
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/util/ProgressIndicatorUtils.kt | 2587661871 |
// 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.execution.runToolbar
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.JBValue
import kotlin.math.roundToInt
@Service(Service.Level.PROJECT)
internal class RunWidgetWidthHelper(private var project: Project) {
companion object {
const val RUN_CONFIG_WIDTH_UNSCALED_MIN = 200
private const val RUN_CONFIG_WIDTH_UNSCALED_MAX = 1200
private const val ARROW_WIDTH_UNSCALED = 28
fun getInstance(project: Project): RunWidgetWidthHelper = project.service()
}
private val listeners = mutableListOf<UpdateWidth>()
fun addListener(listener: UpdateWidth) {
listeners.add(listener)
}
fun removeListener(listener: UpdateWidth) {
listeners.remove(listener)
}
var runConfig: Int = JBUI.scale(RUN_CONFIG_WIDTH_UNSCALED_MIN)
set(value) {
if(field == value) return
val min = JBUI.scale(RUN_CONFIG_WIDTH_UNSCALED_MIN)
val max = JBUI.scale(RUN_CONFIG_WIDTH_UNSCALED_MAX)
field = if(value > max) {
max
} else if(value < min) {
min
} else value
listeners.forEach { it.updated() }
}
val runTarget: Int
get() {
return (runConfig / 2.5).roundToInt()
}
val arrow: Int
get() {
return JBUI.scale(ARROW_WIDTH_UNSCALED)
}
val configWithArrow: Int
get() {
return JBUI.scale(
ARROW_WIDTH_UNSCALED) + runConfig
}
var runConfigWidth: JBValue.Float? = null
var rightSideWidth: JBValue.Float? = null
}
interface UpdateWidth {
fun updated()
} | platform/execution-impl/src/com/intellij/execution/runToolbar/RunWidgetWidthHelper.kt | 2801597348 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.commit
import com.intellij.openapi.Disposable
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.ui.components.JBCheckBox
import org.jetbrains.annotations.ApiStatus
import java.awt.event.KeyEvent
@ApiStatus.Internal
class ToggleAmendCommitOption(commitPanel: CheckinProjectPanel, parent: Disposable) : JBCheckBox(VcsBundle.message("commit.amend.commit")) {
private val amendCommitHandler = commitPanel.commitWorkflowHandler.amendCommitHandler
init {
mnemonic = KeyEvent.VK_M
toolTipText = VcsBundle.message("commit.tooltip.merge.this.commit.with.the.previous.one")
addActionListener { amendCommitHandler.isAmendCommitMode = isSelected }
amendCommitHandler.addAmendCommitModeListener(object : AmendCommitModeListener {
override fun amendCommitModeToggled() {
isSelected = amendCommitHandler.isAmendCommitMode
}
}, parent)
}
companion object {
@JvmStatic
fun isAmendCommitOptionSupported(commitPanel: CheckinProjectPanel, amendAware: AmendCommitAware) =
!commitPanel.isNonModalCommit && amendAware.isAmendCommitSupported()
}
} | platform/vcs-impl/src/com/intellij/vcs/commit/ToggleAmendCommitOption.kt | 4287982296 |
package me.ycdev.android.lib.common.internalapi.android.os
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.RequiresDevice
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@RequiresDevice
class ProcessIATest {
@Test
fun test_setArgV0() {
assertTrue("failed to reflect #setArgV0", ProcessIA.checkReflectSetArgV0())
}
@Test
fun test_readProcLines() {
assertTrue("failed to reflect #readProcLines", ProcessIA.checkReflectReadProcLines())
}
@Test
fun test_getParentPid() {
assertTrue("failed to reflect #getParentPid", ProcessIA.checkReflectGetParentPid())
// app process --> zygote
val pid = android.os.Process.myPid()
val zygotePid = ProcessIA.getParentPid(pid)
assertTrue("failed to get pid of zygote", zygotePid != pid && zygotePid > 0)
}
@Test
fun test_myPpid() {
assertTrue("failed to reflect #myPpid", ProcessIA.checkReflectMyPpid())
// app process --> zygote
val pid = android.os.Process.myPid()
val zygotePid = ProcessIA.myPpid()
assertTrue("failed to get pid of zygote", zygotePid != pid && zygotePid > 0)
}
@Test
fun test_getProcessName() {
// this test app's process name is the package name
val myProcName = ProcessIA.getProcessName(android.os.Process.myPid())
assertEquals(
"failed to validate the test app",
"me.ycdev.android.lib.common.test",
myProcName
)
}
@Test
fun test_getProcessPid() {
// this test app's process name is the package name
val myPid = ProcessIA.getProcessPid("me.ycdev.android.lib.common.test")
assertEquals(
"failed to validate the test app",
android.os.Process.myPid().toLong(),
myPid.toLong()
)
}
}
| baseLib/src/androidTest/java/me/ycdev/android/lib/common/internalapi/android/os/ProcessIATest.kt | 1062413943 |
package com.sqrtf.megumin
import android.os.Build
import android.os.Bundle
import android.view.View
import com.sqrtf.common.activity.BaseActivity
import com.sqrtf.common.cache.PreferencesUtil
abstract class BaseThemeActivity : BaseActivity() {
protected val isWhiteTheme: Boolean
get() = PreferencesUtil.getInstance().getBoolean("whiteTheme", false)!!
open fun themeWhite(): Int {
return R.style.AppThemeWhite
}
open fun themeStand(): Int {
return R.style.AppTheme
}
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(if (isWhiteTheme) themeWhite() else themeStand())
super.onCreate(savedInstanceState)
}
protected fun themeChanged() {
PreferencesUtil.getInstance().putBoolean("whiteTheme", !isWhiteTheme)
recreate()
}
}
| mobile/src/main/java/com/sqrtf/megumin/BaseThemeActivity.kt | 1347809670 |
/*
* 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.tests.hosts
import io.ktor.server.engine.*
import kotlin.test.*
class BuildApplicationConfigJvmTest {
@Test
fun testPropertyConfig() {
System.setProperty("ktor.deployment.port", "1333")
assertEquals(1333, commandLineEnvironment(emptyArray()).connectors.single().port)
System.clearProperty("ktor.deployment.port")
}
@Test
fun testPropertyConfigOverride() {
System.setProperty("ktor.deployment.port", "1333")
assertEquals(13698, commandLineEnvironment(arrayOf("-P:ktor.deployment.port=13698")).connectors.single().port)
System.clearProperty("ktor.deployment.port")
}
}
| ktor-server/ktor-server-host-common/jvm/test/io/ktor/tests/hosts/BuildApplicationConfigJvmTest.kt | 2233555862 |
package quanti.com.kotlinlog3
import android.content.Context
import android.support.test.espresso.Espresso.onView
import android.support.test.espresso.action.ViewActions.click
import android.support.test.espresso.matcher.ViewMatchers.withId
import android.support.test.filters.LargeTest
import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import quanti.com.kotlinlog.file.file.DayLogFile
import quanti.com.kotlinlog.utils.logFilesDir
import java.io.File
@RunWith(AndroidJUnit4::class)
@LargeTest
class HelloWorldEspressoTest {
@get:Rule
val activityRule = ActivityTestRule(MainActivity::class.java)
private lateinit var appCtx: Context
private lateinit var file: File
@Before
fun init() {
appCtx = activityRule.activity.applicationContext
onView(withId(R.id.delete)).perform(click())
val dayFile = DayLogFile(appCtx, 7)
file = File(appCtx.filesDir, dayFile.fileName)
}
@Test
fun button_hitme() {
onView(withId(R.id.hitme)).perform(click())
//sleep to force write
Thread.sleep(6000L)
val any = file
.readLines()
.map { it.contains(RANDOM_TEXT) }
.any()
Assert.assertEquals(true, any)
}
@Test
fun button_test1() {
onView(withId(R.id.test1)).perform(click())
//sleep to force write
Thread.sleep(6000L)
val count = file
.readLines()
.count()
Assert.assertEquals(50, count)
}
@Test
fun button_test2() {
onView(withId(R.id.test2)).perform(click())
//sleep to force write
Thread.sleep(6000L)
val count = file
.readLines()
.count()
Assert.assertEquals(5000, count)
}
@Test
fun button_test3() {
onView(withId(R.id.test3)).perform(click())
//wait some time for everything to happen
Thread.sleep(6000L)
val count = appCtx
.logFilesDir
.listFiles()
.filter { it.name.contains("ArrayIndexOutOf") }
.count()
Assert.assertTrue("At least one handled exception file should be present.", count >= 1)
}
@Test
fun button_test4() {
onView(withId(R.id.throwu)).perform(click())
//wait some time for everything to happen
Thread.sleep(6000L)
val count = appCtx
.logFilesDir
.listFiles()
.filter { it.name.contains("unhandled") }
.count()
Assert.assertTrue("At least one handled exception file should be present.", count >= 1)
}
@Test
fun button_testStrictCircle() {
onView(withId(R.id.switchButton))
.perform(click())
.perform(click())
onView(withId(R.id.test2))
.perform(click())
.perform(click())
.perform(click())
.perform(click())
.perform(click())
//wait some time for everything to happen
Thread.sleep(12000L)
val filtered = appCtx
.logFilesDir
.listFiles()
.filter { it.name.contains("strictcircle") }
val countFull = filtered.count { it.length() > 1022 * 1024 }
val countEmpty = filtered.count() - countFull
Assert.assertEquals("There should be two full files.", 2, countFull)
Assert.assertEquals("There should be one opened file.", 1, countEmpty)
}
@Test
fun button_testStrictCircleDeletesOldFiles() {
onView(withId(R.id.switchButton))
.perform(click())
.perform(click())
//write huge amount of data
onView(withId(R.id.test2))
.perform(click()).perform(click()).perform(click())
.perform(click()).perform(click()).perform(click())
.perform(click()).perform(click()).perform(click())
.perform(click()).perform(click()).perform(click())
.perform(click()).perform(click()).perform(click())
.perform(click()).perform(click()).perform(click())
.perform(click()).perform(click()).perform(click())
//wait some time for everything to happen
Thread.sleep(12000L)
val count = appCtx
.logFilesDir
.listFiles()
.filter { it.name.contains("strictcircle") }
.count()
Assert.assertEquals("There should be 4 files.", 4, count)
}
}
| app/src/androidTest/java/quanti/com/kotlinlog3/MainActivity.kt | 2857375977 |
package `in`.testpress.testpress.models.pojo
data class OTPLoginResponse(
val token: String? = null,
val isNewUser: Boolean = false,
val nonFieldErrors: ArrayList<String> = arrayListOf()
) | app/src/main/java/in/testpress/testpress/models/pojo/OTPLoginResponse.kt | 1528478796 |
package eu.kanade.tachiyomi.data.track.job
import android.content.Context
import androidx.work.BackoffPolicy
import androidx.work.Constraints
import androidx.work.CoroutineWorker
import androidx.work.ExistingWorkPolicy
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.track.TrackManager
import eu.kanade.tachiyomi.util.system.logcat
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import logcat.LogPriority
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.util.concurrent.TimeUnit
class DelayedTrackingUpdateJob(context: Context, workerParams: WorkerParameters) :
CoroutineWorker(context, workerParams) {
override suspend fun doWork(): Result {
val db = Injekt.get<DatabaseHelper>()
val trackManager = Injekt.get<TrackManager>()
val delayedTrackingStore = Injekt.get<DelayedTrackingStore>()
withContext(Dispatchers.IO) {
val tracks = delayedTrackingStore.getItems().mapNotNull {
val manga = db.getManga(it.mangaId).executeAsBlocking() ?: return@withContext
db.getTracks(manga).executeAsBlocking()
.find { track -> track.id == it.trackId }
?.also { track ->
track.last_chapter_read = it.lastChapterRead
}
}
tracks.forEach { track ->
try {
val service = trackManager.getService(track.sync_id)
if (service != null && service.isLogged) {
service.update(track, true)
db.insertTrack(track).executeAsBlocking()
}
} catch (e: Exception) {
logcat(LogPriority.ERROR, e)
}
}
delayedTrackingStore.clear()
}
return Result.success()
}
companion object {
private const val TAG = "DelayedTrackingUpdate"
fun setupTask(context: Context) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val request = OneTimeWorkRequestBuilder<DelayedTrackingUpdateJob>()
.setConstraints(constraints)
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 20, TimeUnit.SECONDS)
.addTag(TAG)
.build()
WorkManager.getInstance(context)
.enqueueUniqueWork(TAG, ExistingWorkPolicy.REPLACE, request)
}
}
}
| app/src/main/java/eu/kanade/tachiyomi/data/track/job/DelayedTrackingUpdateJob.kt | 1260904373 |
package pama
trait Expr
class Number(val value: Int): Expr
class Sum(val left: Expr, val right: Expr): Expr
class Mult(val left: Expr, val right: Expr): Expr
fun eval(e: Expr): Int = when(e) {
is Number -> e.value
is Sum -> eval(e.left) + eval(e.right)
is Mult -> eval(e.left) + eval(e.right)
else -> throw IllegalArgumentException("Unknown expression: $e")
}
| snippets/pama.kt | 2447877289 |
package com.ihsanbal.logging
import okhttp3.Headers
import okhttp3.RequestBody
import okhttp3.Response
import okhttp3.internal.http.promisesBody
import okio.Buffer
import okio.GzipSource
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.io.EOFException
import java.io.IOException
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets
/**
* @author ihsan on 09/02/2017.
*/
class Printer private constructor() {
companion object {
private const val JSON_INDENT = 3
private val LINE_SEPARATOR = System.getProperty("line.separator")
private val DOUBLE_SEPARATOR = LINE_SEPARATOR + LINE_SEPARATOR
private const val N = "\n"
private const val T = "\t"
private const val REQUEST_UP_LINE = "┌────── Request ────────────────────────────────────────────────────────────────────────"
private const val END_LINE = "└───────────────────────────────────────────────────────────────────────────────────────"
private const val RESPONSE_UP_LINE = "┌────── Response ───────────────────────────────────────────────────────────────────────"
private const val BODY_TAG = "Body:"
private const val URL_TAG = "URL: "
private const val METHOD_TAG = "Method: @"
private const val HEADERS_TAG = "Headers:"
private const val STATUS_CODE_TAG = "Status Code: "
private const val RECEIVED_TAG = "Received in: "
private const val DEFAULT_LINE = "│ "
private val OOM_OMITTED = LINE_SEPARATOR + "Output omitted because of Object size."
private fun isEmpty(line: String): Boolean {
return line.isEmpty() || N == line || T == line || line.trim { it <= ' ' }.isEmpty()
}
fun printJsonRequest(builder: LoggingInterceptor.Builder, body: RequestBody?, url: String, header: Headers, method: String) {
val requestBody = body?.let {
LINE_SEPARATOR + BODY_TAG + LINE_SEPARATOR + bodyToString(body, header)
} ?: ""
val tag = builder.getTag(true)
if (builder.logger == null) I.log(builder.type, tag, REQUEST_UP_LINE, builder.isLogHackEnable)
logLines(builder.type, tag, arrayOf(URL_TAG + url), builder.logger, false, builder.isLogHackEnable)
logLines(builder.type, tag, getRequest(builder.level, header, method), builder.logger, true, builder.isLogHackEnable)
if (builder.level == Level.BASIC || builder.level == Level.BODY) {
logLines(builder.type, tag, requestBody.split(LINE_SEPARATOR).toTypedArray(), builder.logger, true, builder.isLogHackEnable)
}
if (builder.logger == null) I.log(builder.type, tag, END_LINE, builder.isLogHackEnable)
}
fun printJsonResponse(builder: LoggingInterceptor.Builder, chainMs: Long, isSuccessful: Boolean,
code: Int, headers: Headers, response: Response, segments: List<String>, message: String, responseUrl: String) {
val responseBody = LINE_SEPARATOR + BODY_TAG + LINE_SEPARATOR + getResponseBody(response)
val tag = builder.getTag(false)
val urlLine = arrayOf(URL_TAG + responseUrl, N)
val responseString = getResponse(headers, chainMs, code, isSuccessful,
builder.level, segments, message)
if (builder.logger == null) {
I.log(builder.type, tag, RESPONSE_UP_LINE, builder.isLogHackEnable)
}
logLines(builder.type, tag, urlLine, builder.logger, true, builder.isLogHackEnable)
logLines(builder.type, tag, responseString, builder.logger, true, builder.isLogHackEnable)
if (builder.level == Level.BASIC || builder.level == Level.BODY) {
logLines(builder.type, tag, responseBody.split(LINE_SEPARATOR).toTypedArray(), builder.logger,
true, builder.isLogHackEnable)
}
if (builder.logger == null) {
I.log(builder.type, tag, END_LINE, builder.isLogHackEnable)
}
}
private fun getResponseBody(response: Response): String {
val responseBody = response.body!!
val headers = response.headers
val contentLength = responseBody.contentLength()
if (!response.promisesBody()) {
return "End request - Promises Body"
} else if (bodyHasUnknownEncoding(response.headers)) {
return "encoded body omitted"
} else {
val source = responseBody.source()
source.request(Long.MAX_VALUE) // Buffer the entire body.
var buffer = source.buffer
var gzippedLength: Long? = null
if ("gzip".equals(headers["Content-Encoding"], ignoreCase = true)) {
gzippedLength = buffer.size
GzipSource(buffer.clone()).use { gzippedResponseBody ->
buffer = Buffer()
buffer.writeAll(gzippedResponseBody)
}
}
val contentType = responseBody.contentType()
val charset: Charset = contentType?.charset(StandardCharsets.UTF_8)
?: StandardCharsets.UTF_8
if (!buffer.isProbablyUtf8()) {
return "End request - binary ${buffer.size}:byte body omitted"
}
if (contentLength != 0L) {
return getJsonString(buffer.clone().readString(charset))
}
return if (gzippedLength != null) {
"End request - ${buffer.size}:byte, $gzippedLength-gzipped-byte body"
} else {
"End request - ${buffer.size}:byte body"
}
}
}
private fun getRequest(level: Level, headers: Headers, method: String): Array<String> {
val log: String
val loggableHeader = level == Level.HEADERS || level == Level.BASIC
log = METHOD_TAG + method + DOUBLE_SEPARATOR +
if (isEmpty("$headers")) "" else if (loggableHeader) HEADERS_TAG + LINE_SEPARATOR + dotHeaders(headers) else ""
return log.split(LINE_SEPARATOR).toTypedArray()
}
private fun getResponse(headers: Headers, tookMs: Long, code: Int, isSuccessful: Boolean,
level: Level, segments: List<String>, message: String): Array<String> {
val log: String
val loggableHeader = level == Level.HEADERS || level == Level.BASIC
val segmentString = slashSegments(segments)
log = ((if (segmentString.isNotEmpty()) "$segmentString - " else "") + "[is success : "
+ isSuccessful + "] - " + RECEIVED_TAG + tookMs + "ms" + DOUBLE_SEPARATOR + STATUS_CODE_TAG +
code + " / " + message + DOUBLE_SEPARATOR + when {
isEmpty("$headers") -> ""
loggableHeader -> HEADERS_TAG + LINE_SEPARATOR +
dotHeaders(headers)
else -> ""
})
return log.split(LINE_SEPARATOR).toTypedArray()
}
private fun slashSegments(segments: List<String>): String {
val segmentString = StringBuilder()
for (segment in segments) {
segmentString.append("/").append(segment)
}
return segmentString.toString()
}
private fun dotHeaders(headers: Headers): String {
val builder = StringBuilder()
headers.forEach { pair ->
builder.append("${pair.first}: ${pair.second}").append(N)
}
return builder.dropLast(1).toString()
}
private fun logLines(type: Int, tag: String, lines: Array<String>, logger: Logger?,
withLineSize: Boolean, useLogHack: Boolean) {
for (line in lines) {
val lineLength = line.length
val maxLogSize = if (withLineSize) 110 else lineLength
for (i in 0..lineLength / maxLogSize) {
val start = i * maxLogSize
var end = (i + 1) * maxLogSize
end = if (end > line.length) line.length else end
if (logger == null) {
I.log(type, tag, DEFAULT_LINE + line.substring(start, end), useLogHack)
} else {
logger.log(type, tag, line.substring(start, end))
}
}
}
}
private fun bodyToString(requestBody: RequestBody?, headers: Headers): String {
return requestBody?.let {
return try {
when {
bodyHasUnknownEncoding(headers) -> {
return "encoded body omitted)"
}
requestBody.isDuplex() -> {
return "duplex request body omitted"
}
requestBody.isOneShot() -> {
return "one-shot body omitted"
}
else -> {
val buffer = Buffer()
requestBody.writeTo(buffer)
val contentType = requestBody.contentType()
val charset: Charset = contentType?.charset(StandardCharsets.UTF_8)
?: StandardCharsets.UTF_8
return if (buffer.isProbablyUtf8()) {
getJsonString(buffer.readString(charset)) + LINE_SEPARATOR + "${requestBody.contentLength()}-byte body"
} else {
"binary ${requestBody.contentLength()}-byte body omitted"
}
}
}
} catch (e: IOException) {
"{\"err\": \"" + e.message + "\"}"
}
} ?: ""
}
private fun bodyHasUnknownEncoding(headers: Headers): Boolean {
val contentEncoding = headers["Content-Encoding"] ?: return false
return !contentEncoding.equals("identity", ignoreCase = true) &&
!contentEncoding.equals("gzip", ignoreCase = true)
}
private fun getJsonString(msg: String): String {
val message: String
message = try {
when {
msg.startsWith("{") -> {
val jsonObject = JSONObject(msg)
jsonObject.toString(JSON_INDENT)
}
msg.startsWith("[") -> {
val jsonArray = JSONArray(msg)
jsonArray.toString(JSON_INDENT)
}
else -> {
msg
}
}
} catch (e: JSONException) {
msg
} catch (e1: OutOfMemoryError) {
OOM_OMITTED
}
return message
}
fun printFailed(tag: String, builder: LoggingInterceptor.Builder) {
I.log(builder.type, tag, RESPONSE_UP_LINE, builder.isLogHackEnable)
I.log(builder.type, tag, DEFAULT_LINE + "Response failed", builder.isLogHackEnable)
I.log(builder.type, tag, END_LINE, builder.isLogHackEnable)
}
}
init {
throw UnsupportedOperationException()
}
}
/**
* @see 'https://github.com/square/okhttp/blob/master/okhttp-logging-interceptor/src/main/java/okhttp3/logging/utf8.kt'
* */
internal fun Buffer.isProbablyUtf8(): Boolean {
try {
val prefix = Buffer()
val byteCount = size.coerceAtMost(64)
copyTo(prefix, 0, byteCount)
for (i in 0 until 16) {
if (prefix.exhausted()) {
break
}
val codePoint = prefix.readUtf8CodePoint()
if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
return false
}
}
return true
} catch (_: EOFException) {
return false // Truncated UTF-8 sequence.
}
} | lib/src/main/java/com/ihsanbal/logging/Printer.kt | 2475185238 |
/*
* Copyright (C) 2015 Hannes Dorfmann
* Copyright (C) 2015 Tickaroo, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.tickaroo.tikxml.annotationprocessing.elementlist.polymorphism
import com.tickaroo.tikxml.annotation.Attribute
import com.tickaroo.tikxml.annotation.Xml
/**
* @author Hannes Dorfmann
*/
@Xml
data class BossDataClass(
@field:Attribute
var firstName: String? = null,
@field:Attribute
var lastName: String? = null
) : Person | annotationprocessortesting-kt/src/main/java/com/tickaroo/tikxml/annotationprocessing/elementlist/polymorphism/BossDataClass.kt | 1224055721 |
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.common.valuetype.validation.failures
sealed class CoordinateFailure : Throwable() {
object CoordinateMalformedException : CoordinateFailure()
}
| core/src/main/java/org/hisp/dhis/android/core/common/valuetype/validation/failures/CoordinateFailure.kt | 1451867154 |
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.visualization.internal
import dagger.Reusable
import javax.inject.Inject
import org.hisp.dhis.android.core.visualization.DataDimensionItemTableInfo
import org.hisp.dhis.android.core.visualization.VisualizationCategoryDimensionLinkTableInfo
import org.hisp.dhis.android.core.visualization.VisualizationTableInfo
import org.hisp.dhis.android.core.wipe.internal.ModuleWiper
import org.hisp.dhis.android.core.wipe.internal.TableWiper
@Reusable
class VisualizationModuleWiper @Inject internal constructor(private val tableWiper: TableWiper) : ModuleWiper {
override fun wipeMetadata() {
tableWiper.wipeTables(
VisualizationTableInfo.TABLE_INFO,
VisualizationCategoryDimensionLinkTableInfo.TABLE_INFO,
DataDimensionItemTableInfo.TABLE_INFO
)
}
override fun wipeData() {
// No data to wipe
}
}
| core/src/main/java/org/hisp/dhis/android/core/visualization/internal/VisualizationModuleWiper.kt | 1642083152 |
/*
* Copyright 2017, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.talentica.androidkotlin.db.converter
import androidx.room.TypeConverter
import java.util.*
object DateConverter {
@kotlin.jvm.JvmStatic
@TypeConverter
fun toDate(timestamp: Long?): Date? {
return if (timestamp == null) null else Date(timestamp)
}
@kotlin.jvm.JvmStatic
@TypeConverter
fun toTimestamp(date: Date?): Long? {
return date?.time
}
} | app/src/main/java/com/talentica/androidkotlin/db/converter/DateConverter.kt | 2400183321 |
package src
import org.junit.Test
import kotlin.test.assertTrue
/**
* Created by vicboma on 01/11/15.
*/
class FunctionalTest{
val expected = arrayOf<Long>(0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368,75025,121393,196418,317811,514229,832040,1346269,2178309,3524578,5702887,9227465,14930352,24157817,39088169,63245986,102334155,165580141,267914296,433494437,701408733,1134903170)
@Test
fun testMethod() {
val fibonacci = Functional()
val size = expected.size-1
for(sequence in 0..size) {
val result = fibonacci.method(sequence.toLong())
assertTrue {
"Fail resutl"
result == expected.get(sequence)
}
}
}
} | src/test/java/src/FunctionalTest.kt | 1288747192 |
package com.tungnui.dalatlaptop.ux.login
import android.support.design.widget.TabLayout
import android.support.v7.app.AppCompatActivity
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.os.Bundle
import android.view.MenuItem
import com.tungnui.dalatlaptop.R
import com.tungnui.dalatlaptop.SettingsMy
import com.tungnui.dalatlaptop.interfaces.LoginDialogInterface
import com.tungnui.dalatlaptop.models.Customer
import com.tungnui.dalatlaptop.ux.MainActivity
import com.tungnui.dalatlaptop.ux.MainActivity.Companion.LOGIN_RESULT_CODE
import kotlinx.android.synthetic.main.activity_login.*
class LoginActivity : AppCompatActivity() {
/**
* The [android.support.v4.view.PagerAdapter] that will provide
* fragments for each of the sections. We use a
* {@link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* [android.support.v4.app.FragmentStatePagerAdapter].
*/
private var mSectionsPagerAdapter: SectionsPagerAdapter? = null
private var loginDialogInterface: LoginDialogInterface? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
this.title = "Đăng nhập/ Đăng kí"
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = SectionsPagerAdapter(supportFragmentManager)
// Set up the ViewPager with the sections adapter.
container.adapter = mSectionsPagerAdapter
container.addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener(tabs))
tabs.addOnTabSelectedListener(TabLayout.ViewPagerOnTabSelectedListener(container))
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when(item.itemId){
android.R.id.home ->{
this.finish()
return true
}
}
return super.onOptionsItemSelected(item)
}
/**
* A [FragmentPagerAdapter] that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
inner class SectionsPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
override fun getItem(position: Int): Fragment {
return when(position){
0 -> LoginFragment()
else -> RegisterFragment()
}
}
override fun getCount(): Int {
// Show 3 total pages.
return 2
}
}
fun handleUserLogin(customer: Customer) {
SettingsMy.setActiveUser(customer)
MainActivity.invalidateDrawerMenuHeader()
if (loginDialogInterface != null) {
loginDialogInterface?.successfulLoginOrRegistration(customer)
}
setResult(LOGIN_RESULT_CODE,intent)
this.finish()
}
companion object {
fun logoutUser() {
SettingsMy.setActiveUser(null)
MainActivity.invalidateDrawerMenuHeader()
}
}
}
| app/src/main/java/com/tungnui/dalatlaptop/ux/login/LoginActivity.kt | 2439003960 |
// 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.idea.maven.project.importing
import com.intellij.openapi.util.registry.Registry
import com.intellij.maven.testFramework.MavenMultiVersionImportingTestCase
import org.junit.Assume
import org.junit.Test
class MavenProjectsManagerNewFlowTest : MavenMultiVersionImportingTestCase() {
@Throws(Exception::class)
override fun setUp() {
super.setUp()
Assume.assumeTrue(Registry.`is`("maven.linear.import"))
}
@Test
fun shouldSetMavenFilesIntoProjectManager() {
val file = createProjectPom("<groupId>test</groupId>" +
"<artifactId>project</artifactId>" +
"<version>1</version>")
importViaNewFlow(listOf(file), true, emptyList())
}
} | plugins/maven/src/test/java/org/jetbrains/idea/maven/project/importing/MavenProjectsManagerNewFlowTest.kt | 2008505762 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix.migration
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.base.fe10.analysis.getEnumValue
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors.DEPRECATION
import org.jetbrains.kotlin.diagnostics.Errors.DEPRECATION_ERROR
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.inspections.RemoveAnnotationFix
import org.jetbrains.kotlin.idea.quickfix.CleanupFix
import org.jetbrains.kotlin.idea.quickfix.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory
import org.jetbrains.kotlin.idea.util.addAnnotation
import org.jetbrains.kotlin.idea.util.findAnnotation
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.checkers.OptInNames
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
/**
* The quick fix to replace a deprecated `@Experimental` annotation with the new `@RequiresOptIn` annotation.
*/
class MigrateExperimentalToRequiresOptInFix(
annotationEntry: KtAnnotationEntry,
private val requiresOptInInnerText: String?
) : KotlinQuickFixAction<KtAnnotationEntry>(annotationEntry), CleanupFix {
override fun getText(): String = KotlinBundle.message("fix.opt_in.migrate.experimental.annotation.replace")
override fun getFamilyName(): String = KotlinBundle.message("fix.opt_in.migrate.experimental.annotation.replace")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val oldAnnotationEntry = element ?: return
val owner = oldAnnotationEntry.getStrictParentOfType<KtModifierListOwner>() ?: return
val added = owner.addAnnotation(
OptInNames.REQUIRES_OPT_IN_FQ_NAME,
requiresOptInInnerText,
useSiteTarget = null,
searchForExistingEntry = false // We don't want to resolve existing annotations in the write action
)
if (added) oldAnnotationEntry.delete()
}
/**
* Quick fix factory to create remove/replace quick fixes for deprecated `@Experimental` annotations.
*
* If the annotated expression has both `@Experimental` annotation and `@RequiresOptIn` annotation,
* the "Remove annotation" action is proposed to get rid of the obsolete `@Experimental` annotation
* (we don't check if the `level` arguments match in both annotations).
*
* If there is only an `@Experimental` annotation, the factory generates a "Replace annotation" quick fix
* that removes the `@Experimental` annotation and creates a `@RequiresOptIn` annotation
* with the matching value of the `level` argument.
*/
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
if (diagnostic.factory !in setOf(DEPRECATION, DEPRECATION_ERROR)) return null
val constructorCallee = diagnostic.psiElement.getStrictParentOfType<KtConstructorCalleeExpression>() ?: return null
val annotationEntry = constructorCallee.parent?.safeAs<KtAnnotationEntry>() ?: return null
val annotationDescriptor = annotationEntry.resolveToDescriptorIfAny() ?: return null
if (annotationDescriptor.fqName == OptInNames.OLD_EXPERIMENTAL_FQ_NAME) {
val annotationOwner = annotationEntry.getStrictParentOfType<KtModifierListOwner>() ?: return null
if (annotationOwner.findAnnotation(OptInNames.REQUIRES_OPT_IN_FQ_NAME) != null)
return RemoveAnnotationFix(KotlinBundle.message("fix.opt_in.migrate.experimental.annotation.remove"), annotationEntry)
val requiresOptInInnerText = when (annotationDescriptor.getEnumValue("level")?.enumEntryName?.asString()) {
"ERROR" -> "level = RequiresOptIn.Level.ERROR"
"WARNING" -> "level = RequiresOptIn.Level.WARNING"
else -> null
}
return MigrateExperimentalToRequiresOptInFix(annotationEntry, requiresOptInInnerText)
}
return null
}
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/migration/MigrateExperimentalToRequiresOptInFix.kt | 4204975595 |
// 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.git
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Couple
import com.intellij.openapi.vcs.FilePath
import git4idea.checkin.GitCheckinExplicitMovementProvider
import org.jetbrains.kotlin.idea.base.codeInsight.pathBeforeJavaToKotlinConversion
import java.util.*
class KotlinExplicitMovementProvider : GitCheckinExplicitMovementProvider() {
override fun isEnabled(project: Project): Boolean {
return true
}
override fun getDescription(): String {
return KotlinGitBundle.message("j2k.extra.commit.description")
}
override fun getCommitMessage(oldCommitMessage: String): String {
return KotlinGitBundle.message("j2k.extra.commit.commit.message")
}
override fun collectExplicitMovements(
project: Project,
beforePaths: List<FilePath>,
afterPaths: List<FilePath>
): Collection<Movement> {
val movedChanges = ArrayList<Movement>()
for (after in afterPaths) {
val pathBeforeJ2K = after.virtualFile?.pathBeforeJavaToKotlinConversion
if (pathBeforeJ2K != null) {
val before = beforePaths.firstOrNull { it.path == pathBeforeJ2K }
if (before != null) {
movedChanges.add(Movement(before, after))
}
}
}
return movedChanges
}
override fun afterMovementsCommitted(project: Project, movedPaths: MutableList<Couple<FilePath>>) {
movedPaths.forEach { it.second.virtualFile?.pathBeforeJavaToKotlinConversion = null }
}
}
| plugins/kotlin/git/src/org/jetbrains/kotlin/idea/git/KotlinExplicitMovementProvider.kt | 3367892418 |
// PROBLEM: none
fun a(a: Int) = Unit
fun b() {
a(a = -<caret>1)
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/unusedUnaryOperator/namedParameter.kt | 614525154 |
package jp.juggler.subwaytooter
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.woxthebox.draglistview.DragItem
import com.woxthebox.draglistview.DragItemAdapter
import com.woxthebox.draglistview.DragListView
import com.woxthebox.draglistview.swipe.ListSwipeHelper
import com.woxthebox.draglistview.swipe.ListSwipeItem
import jp.juggler.subwaytooter.api.entity.Acct
import jp.juggler.subwaytooter.column.ColumnEncoder
import jp.juggler.subwaytooter.column.ColumnType
import jp.juggler.util.*
class ActColumnList : AppCompatActivity() {
companion object {
private val log = LogCategory("ActColumnList")
internal const val TMP_FILE_COLUMN_LIST = "tmp_column_list"
const val EXTRA_ORDER = "order"
const val EXTRA_SELECTION = "selection"
fun createIntent(activity: ActMain, currentItem: Int) =
Intent(activity, ActColumnList::class.java).apply {
val array = activity.appState.encodeColumnList()
AppState.saveColumnList(activity, TMP_FILE_COLUMN_LIST, array)
putExtra(EXTRA_SELECTION, currentItem)
}
}
private lateinit var listView: DragListView
private lateinit var listAdapter: MyListAdapter
private var oldSelection: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
backPressed {
makeResult(-1)
finish()
}
App1.setActivityTheme(this)
initUI()
if (savedInstanceState != null) {
restoreData(savedInstanceState.getInt(EXTRA_SELECTION))
} else {
val intent = intent
restoreData(intent.getIntExtra(EXTRA_SELECTION, -1))
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt(EXTRA_SELECTION, oldSelection)
val array = listAdapter.itemList.map { it.json }.toJsonArray()
AppState.saveColumnList(this, TMP_FILE_COLUMN_LIST, array)
}
private fun initUI() {
setContentView(R.layout.act_column_list)
App1.initEdgeToEdge(this)
Styler.fixHorizontalPadding0(findViewById(R.id.llContent))
// リストのアダプター
listAdapter = MyListAdapter()
// ハンドル部分をドラッグで並べ替えできるRecyclerView
listView = findViewById(R.id.drag_list_view)
listView.setLayoutManager(androidx.recyclerview.widget.LinearLayoutManager(this))
listView.setAdapter(listAdapter, true)
listView.setCanDragHorizontally(false)
listView.setCustomDragItem(MyDragItem(this, R.layout.lv_column_list))
listView.recyclerView.isVerticalScrollBarEnabled = true
listView.setDragListListener(object : DragListView.DragListListenerAdapter() {
override fun onItemDragStarted(position: Int) {
// 操作中はリフレッシュ禁止
// mRefreshLayout.setEnabled( false );
}
override fun onItemDragEnded(fromPosition: Int, toPosition: Int) {
// 操作完了でリフレッシュ許可
// mRefreshLayout.setEnabled( USE_SWIPE_REFRESH );
// if( fromPosition != toPosition ){
// // 並べ替えが発生した
// }
}
})
// リストを左右スワイプした
listView.setSwipeListener(object : ListSwipeHelper.OnSwipeListenerAdapter() {
override fun onItemSwipeStarted(item: ListSwipeItem) {
// 操作中はリフレッシュ禁止
// mRefreshLayout.setEnabled( false );
}
override fun onItemSwipeEnded(
item: ListSwipeItem,
swipedDirection: ListSwipeItem.SwipeDirection?,
) {
// 操作完了でリフレッシュ許可
// mRefreshLayout.setEnabled( USE_SWIPE_REFRESH );
// 左にスワイプした(右端に青が見えた) なら要素を削除する
if (swipedDirection == ListSwipeItem.SwipeDirection.LEFT) {
val adapterItem = item.tag as MyItem
if (adapterItem.json.optBoolean(ColumnEncoder.KEY_DONT_CLOSE, false)) {
showToast(false, R.string.column_has_dont_close_option)
listView.resetSwipedViews(null)
return
}
listAdapter.removeItem(listAdapter.getPositionForItem(adapterItem))
}
}
})
}
private fun restoreData(ivSelection: Int) {
this.oldSelection = ivSelection
val tmpList = ArrayList<MyItem>()
try {
AppState.loadColumnList(this, TMP_FILE_COLUMN_LIST)
?.objectList()
?.forEachIndexed { index, src ->
try {
val item = MyItem(src, index.toLong(), this)
tmpList.add(item)
if (oldSelection == item.oldIndex) {
item.setOldSelection(true)
}
} catch (ex: Throwable) {
log.trace(ex)
}
}
} catch (ex: Throwable) {
log.trace(ex)
}
listAdapter.itemList = tmpList
}
private fun makeResult(newSelection: Int) {
val intent = Intent()
val itemList = listAdapter.itemList
// どの要素を選択するか
if (newSelection >= 0 && newSelection < listAdapter.itemCount) {
intent.putExtra(EXTRA_SELECTION, newSelection)
} else {
var i = 0
val ie = itemList.size
while (i < ie) {
if (itemList[i].bOldSelection) {
intent.putExtra(EXTRA_SELECTION, i)
break
}
++i
}
}
// 並べ替え用データ
val orderList = ArrayList<Int>()
for (item in itemList) {
orderList.add(item.oldIndex)
}
intent.putExtra(EXTRA_ORDER, orderList)
setResult(Activity.RESULT_OK, intent)
}
private fun performItemSelected(item: MyItem) {
val idx = listAdapter.getPositionForItem(item)
makeResult(idx)
finish()
}
// リスト要素のデータ
internal class MyItem(val json: JsonObject, val id: Long, context: Context) {
val name: String = json.optString(ColumnEncoder.KEY_COLUMN_NAME)
val acct: Acct = Acct.parse(json.optString(ColumnEncoder.KEY_COLUMN_ACCESS_ACCT))
val acctName: String = json.optString(ColumnEncoder.KEY_COLUMN_ACCESS_STR)
val oldIndex = json.optInt(ColumnEncoder.KEY_OLD_INDEX)
val type = ColumnType.parse(json.optInt(ColumnEncoder.KEY_TYPE))
val acctColorBg = json.optInt(ColumnEncoder.KEY_COLUMN_ACCESS_COLOR_BG, 0)
val acctColorFg = json.optInt(ColumnEncoder.KEY_COLUMN_ACCESS_COLOR, 0)
.notZero() ?: context.attrColor(R.attr.colorColumnListItemText)
var bOldSelection: Boolean = false
fun setOldSelection(b: Boolean) {
bOldSelection = b
}
}
// リスト要素のViewHolder
internal inner class MyViewHolder(viewRoot: View) : DragItemAdapter.ViewHolder(
viewRoot,
R.id.ivDragHandle, // View ID。 ここを押すとドラッグ操作をすぐに開始する
true, // 長押しでドラッグ開始するなら真
) {
private val ivBookmark: View = viewRoot.findViewById(R.id.ivBookmark)
private val tvAccess: TextView = viewRoot.findViewById(R.id.tvAccess)
private val tvName: TextView = viewRoot.findViewById(R.id.tvName)
private val ivColumnIcon: ImageView = viewRoot.findViewById(R.id.ivColumnIcon)
private val acctPadLr = (0.5f + 4f * viewRoot.resources.displayMetrics.density).toInt()
init {
// リスト要素のビューが ListSwipeItem だった場合、Swipe操作を制御できる
if (viewRoot is ListSwipeItem) {
viewRoot.setSwipeInStyle(ListSwipeItem.SwipeInStyle.SLIDE)
viewRoot.supportedSwipeDirection = ListSwipeItem.SwipeDirection.LEFT
}
}
fun bind(item: MyItem) {
itemView.tag = item // itemView は親クラスのメンバ変数
ivBookmark.visibility = if (item.bOldSelection) View.VISIBLE else View.INVISIBLE
tvAccess.text = item.acctName
tvAccess.setTextColor(item.acctColorFg)
tvAccess.setBackgroundColor(item.acctColorBg)
tvAccess.setPaddingRelative(acctPadLr, 0, acctPadLr, 0)
tvName.text = item.name
ivColumnIcon.setImageResource(item.type.iconId(item.acct))
// 背景色がテーマ次第なので、カラム設定の色を反映するとアイコンが見えなくなる可能性がある
// よってアイコンやテキストにカラム設定の色を反映しない
}
// @Override
// public boolean onItemLongClicked( View view ){
// return false;
// }
override fun onItemClicked(view: View?) {
val item = itemView.tag as MyItem // itemView は親クラスのメンバ変数
(view.activity as? ActColumnList)?.performItemSelected(item)
}
}
// ドラッグ操作中のデータ
private inner class MyDragItem(context: Context, layoutId: Int) :
DragItem(context, layoutId) {
override fun onBindDragView(clickedView: View, dragView: View) {
val item = clickedView.tag as MyItem
var tv: TextView = dragView.findViewById(R.id.tvAccess)
tv.text = item.acctName
tv.setTextColor(item.acctColorFg)
tv.setBackgroundColor(item.acctColorBg)
tv = dragView.findViewById(R.id.tvName)
tv.text = item.name
val ivColumnIcon: ImageView = dragView.findViewById(R.id.ivColumnIcon)
ivColumnIcon.setImageResource(item.type.iconId(item.acct))
dragView.findViewById<View>(R.id.ivBookmark).visibility =
clickedView.findViewById<View>(R.id.ivBookmark).visibility
dragView.findViewById<View>(R.id.item_layout)
.setBackgroundColor(attrColor(R.attr.list_item_bg_pressed_dragged))
}
}
private inner class MyListAdapter :
DragItemAdapter<MyItem, MyViewHolder>() {
init {
setHasStableIds(true)
itemList = ArrayList()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val view = layoutInflater.inflate(R.layout.lv_column_list, parent, false)
return MyViewHolder(view)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
super.onBindViewHolder(holder, position)
holder.bind(itemList[position])
}
override fun getUniqueItemId(position: Int): Long {
val item = mItemList[position] // mItemList は親クラスのメンバ変数
return item.id
}
}
}
| app/src/main/java/jp/juggler/subwaytooter/ActColumnList.kt | 919705483 |
/*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.base.db.typeconverters
import androidx.room.TypeConverter
import de.dreier.mytargets.shared.models.EBowType
class EBowTypeConverters {
@TypeConverter
fun getDBValue(model: EBowType?): Int? {
return model?.ordinal
}
@TypeConverter
fun getModelValue(data: Int?): EBowType? {
return if (data != null) EBowType.fromId(data) else null
}
}
| app/src/main/java/de/dreier/mytargets/base/db/typeconverters/EBowTypeConverters.kt | 3090909825 |
package com.github.kurtyan.fanfou4j.request.friend
import com.github.kurtyan.fanfou4j.core.AbstractRequest
import com.github.kurtyan.fanfou4j.core.HttpMethod
import com.github.kurtyan.fanfou4j.entity.User
/**
* Created by yanke on 2016/12/7.
*/
class DeleteFriendRequest : AbstractRequest<User>("/friendships/destroy.json", HttpMethod.POST) {
var id: String by stringDelegate
} | src/main/java/com/github/kurtyan/fanfou4j/request/friend/DeleteFriendRequest.kt | 3555770096 |
package com.slack.api.model.kotlin_extension.block
/**
* This annotation signifies that the class is a builder for the Block Kit DSL.
*
* Classes marked with this annotation make it so that invoking functions with a receiver outside
* the most immediate block are illegal without an explicit labeled `this`
*/
@DslMarker
annotation class BlockLayoutBuilder
| slack-api-model-kotlin-extension/src/main/kotlin/com/slack/api/model/kotlin_extension/block/BlockLayoutBuilder.kt | 4180057181 |
package com.alexstyl.specialdates.events.namedays.activity
class AndroidNamedaysOnADayView(private val screenAdapter: NamedaysScreenAdapter) : NamedaysOnADayView {
override fun displayNamedays(viewModels: List<NamedayScreenViewModel>) {
screenAdapter.display(viewModels)
}
}
| android_mobile/src/main/java/com/alexstyl/specialdates/events/namedays/activity/AndroidNamedaysOnADayView.kt | 4044392198 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.editorconfig.language.codeinsight.inspections
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import org.editorconfig.language.codeinsight.quickfixes.EditorConfigRemoveOptionQuickFix
import org.editorconfig.language.messages.EditorConfigBundle
import org.editorconfig.language.psi.EditorConfigOption
import org.editorconfig.language.psi.EditorConfigVisitor
import org.editorconfig.language.schema.descriptors.impl.EditorConfigQualifiedKeyDescriptor
import org.editorconfig.language.util.EditorConfigDescriptorUtil
import org.editorconfig.language.util.EditorConfigPsiTreeUtil.findShadowingSections
class EditorConfigShadowedOptionInspection : LocalInspectionTool() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : EditorConfigVisitor() {
override fun visitOption(option: EditorConfigOption) {
findShadowingSections(option.section)
.asSequence()
.flatMap { it.optionList.asSequence() }
.dropWhile { it !== option }
.drop(1)
.firstOrNull { equalOptions(option, it) }
?.apply {
val message = EditorConfigBundle["inspection.option.shadowed.message"]
holder.registerProblem(option, message, ProblemHighlightType.LIKE_UNUSED_SYMBOL, EditorConfigRemoveOptionQuickFix())
}
}
}
companion object {
fun equalOptions(first: EditorConfigOption, second: EditorConfigOption): Boolean {
val firstDescriptor = first.getDescriptor(false) ?: return false
val firstDeclarations = findDeclarations(first)
if (first.keyParts.size != second.keyParts.size) return false
val secondDescriptor = second.getDescriptor(false)
if (firstDescriptor != secondDescriptor) return false
if (EditorConfigDescriptorUtil.isConstant(firstDescriptor.key)) return true
val secondDeclarations = findDeclarations(second)
return equalToIgnoreCase(firstDeclarations, secondDeclarations)
}
private fun equalToIgnoreCase(first: List<String>, second: List<String>): Boolean {
if (first.size != second.size) return false
return first.zip(second).all(::equalToIgnoreCase)
}
private fun equalToIgnoreCase(pair: Pair<String, String>) =
pair.first.equals(pair.second, true)
private fun findDeclarations(option: EditorConfigOption): List<String> {
val descriptor = option.getDescriptor(false) ?: return emptyList()
val keyDescriptor = descriptor.key as? EditorConfigQualifiedKeyDescriptor ?: return emptyList()
if (option.keyParts.size != keyDescriptor.children.size) throw IllegalStateException()
return option.keyParts.filterIndexed { index, _ ->
EditorConfigDescriptorUtil.isVariable(keyDescriptor.children[index])
}
}
}
}
| plugins/editorconfig/src/org/editorconfig/language/codeinsight/inspections/EditorConfigShadowedOptionInspection.kt | 1159777343 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.util
import com.intellij.psi.*
import com.intellij.testFramework.PsiTestCase
import org.jetbrains.plugins.gradle.util.GradleExecutionSettingsUtil.createTestFilterFrom
import org.jetbrains.plugins.gradle.util.GradleExecutionSettingsUtil.createTestFilterFromClass
import org.jetbrains.plugins.gradle.util.GradleExecutionSettingsUtil.createTestFilterFromMethod
import org.jetbrains.plugins.gradle.util.GradleExecutionSettingsUtil.createTestFilterFromPackage
import org.junit.Test
class GradleExecutionSettingsUtilTest : PsiTestCase() {
fun `test filter generation by name`() {
assertEquals("""--tests *""", createTestFilterFromPackage("", false))
assertEquals("""--tests * """, createTestFilterFromPackage("", true))
assertEquals("""--tests "org.jetbrains.test.*"""", createTestFilterFromPackage("org.jetbrains.test", false))
assertEquals("""--tests "org.jetbrains.test.*" """, createTestFilterFromPackage("org.jetbrains.test", true))
assertEquals("""--tests "org.jetbrains.te*st.*"""", createTestFilterFromPackage("org.jetbrains.te\"st", false))
assertEquals("""--tests "org.jetbrains.te*st.*" """, createTestFilterFromPackage("org.jetbrains.te\"st", true))
assertEquals("""--tests "org.jetbrains.te\st.*"""", createTestFilterFromPackage("org.jetbrains.te\\st", false))
assertEquals("""--tests "org.jetbrains.te\st.*" """, createTestFilterFromPackage("org.jetbrains.te\\st", true))
assertEquals("""--tests "My favorite test case"""", createTestFilterFromClass("My favorite test case", false))
assertEquals("""--tests "My favorite test case" """, createTestFilterFromClass("My favorite test case", true))
assertEquals("""--tests "It isn't a favorite * test case"""", createTestFilterFromClass("It isn't a favorite \" test case", false))
assertEquals("""--tests "It isn't a favorite * test case" """, createTestFilterFromClass("It isn't a favorite \" test case", true))
assertEquals("""--tests "Test case.it is my favorite test"""", createTestFilterFromMethod("Test case", "it is my favorite test", false))
assertEquals("""--tests "Test case.it is my favorite test" """, createTestFilterFromMethod("Test case", "it is my favorite test", true))
assertEquals("""--tests "Test.it isn't a favorite * test"""", createTestFilterFromMethod("Test", "it isn't a favorite . test", false))
assertEquals("""--tests "Test.it isn't a favorite * test" """, createTestFilterFromMethod("Test", "it isn't a favorite . test", true))
}
@Test
fun `test filter generation by groovy method`() {
val psiFile = createGroovyPsiFile(
"Test",
"test",
"'test'",
"'tes\\\'t'",
"'tes\\\\\\\'t'",
"'tes\\\\t'",
"'tes\\\\\\\\t'",
"'t\\\\es\\\\t'"
)
val (actualFilters, actualFiltersWithSuffix) = runReadActionAndWait {
val aClass = psiFile.findChildByType<PsiClass>()
val methods = aClass.findChildByElementType("CLASS_BODY")
.findChildrenByType<PsiMethod>()
methods.map { createTestFilterFrom(aClass, it, false) } to
methods.map { createTestFilterFrom(aClass, it, true) }
}
val expectedFilters = listOf(
"""--tests "Test.test"""",
"""--tests "Test.test"""",
"""--tests "Test.tes't"""",
"""--tests "Test.tes\'t"""",
"""--tests "Test.tes\t"""",
"""--tests "Test.tes\\t"""",
"""--tests "Test.t\es\t""""
)
for ((expected, actual) in expectedFilters.zip(actualFilters)) {
assertEquals(expected, actual)
}
for ((expected, actual) in expectedFilters.zip(actualFiltersWithSuffix)) {
assertEquals("$expected ", actual)
}
}
@Test
fun `test filter generation by groovy class`() {
val psiFile = createGroovyPsiFile("Test")
val (actualFilter, actualFilterWithSuffix) = runReadActionAndWait {
val aClass = psiFile.findChildByType<PsiClass>()
createTestFilterFrom(aClass, false) to
createTestFilterFrom(aClass, true)
}
val expectedFilter = """--tests "Test""""
assertEquals(expectedFilter, actualFilter)
assertEquals("$expectedFilter ", actualFilterWithSuffix)
}
@Test
fun `test filter generation by java method`() {
val psiFile = createJavaPsiFile(
"Test",
"test",
"test2",
"super_test",
"super${'$'}test"
)
val (actualFilters, actualFiltersWithSuffix) = runReadActionAndWait {
val aClass = psiFile.findChildByType<PsiClass>()
val methods = aClass.findChildrenByType<PsiMethod>()
methods.map { createTestFilterFrom(aClass, it, false) } to
methods.map { createTestFilterFrom(aClass, it, true) }
}
val expectedFilters = listOf(
"""--tests "Test.test"""",
"""--tests "Test.test2"""",
"""--tests "Test.super_test"""",
"""--tests "Test.super${'$'}test""""
)
for ((expected, actual) in expectedFilters.zip(actualFilters)) {
assertEquals(expected, actual)
}
for ((expected, actual) in expectedFilters.zip(actualFiltersWithSuffix)) {
assertEquals("$expected ", actual)
}
}
@Test
fun `test filter generation by java class`() {
val psiFile = createJavaPsiFile("Te${'$'}${'$'}${'$'}st")
val (actualFilter, actualFilterWithSuffix) = runReadActionAndWait {
val aClass = psiFile.findChildByType<PsiClass>()
createTestFilterFrom(aClass, false) to
createTestFilterFrom(aClass, true)
}
val expectedFilter = """--tests "Te${'$'}${'$'}${'$'}st""""
assertEquals(expectedFilter, actualFilter)
assertEquals("$expectedFilter ", actualFilterWithSuffix)
}
private fun createJavaFileContent(className: String, vararg methodNames: String): String {
val methods = methodNames.map {
"""
| @Test
| void $it() {
| fail()
| }
""".trim()
}
val classBody = methods.joinToString("\n")
return """
|import static org.junit.Assert.fail
|import org.junit.Test
|
|class $className {
$classBody
|}
""".trim().replaceIndentByMargin()
}
private fun createGroovyPsiFile(className: String, vararg methodNames: String): PsiFile {
val content = createJavaFileContent(className, *methodNames)
return createFile("$className.groovy", content)
}
private fun createJavaPsiFile(className: String, vararg methodNames: String): PsiFile {
val content = createJavaFileContent(className, *methodNames)
return createFile("$className.java", content)
}
} | plugins/gradle/java/testSources/util/GradleExecutionSettingsUtilTest.kt | 2213220580 |
/*
* Copyright 2016-2019 Julien Guerinet
*
* 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.guerinet.suitcase.ui.extensions
import android.graphics.drawable.Drawable
import androidx.annotation.ColorInt
import androidx.core.graphics.drawable.DrawableCompat
/**
* Drawable extensions
* @author Julien Guerinet
* @since 2.3.0
*/
/**
* Sets the tint with the given [color] in a backwards compatible way
*/
fun Drawable.setTintCompat(@ColorInt color: Int): Drawable {
// Wrap the drawable in the compat library
val wrappedDrawable = DrawableCompat.wrap(this).mutate()
// Tint the Drawable and return it
wrappedDrawable.setTint(color)
return wrappedDrawable
}
| ui/src/main/java/com/guerinet/suitcase/ui/extensions/DrawableExt.kt | 1964337012 |
package com.esafirm.androidplayground.conductor.sharedtransition
import android.os.Bundle
import androidx.core.view.ViewCompat
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import butterknife.BindView
import com.esafirm.androidplayground.R
import com.esafirm.conductorextra.butterknife.BinderController
import com.esafirm.conductorextra.getProps
import com.esafirm.conductorextra.toPropsBundle
class SharedTransitionDetailController : BinderController {
@BindView(R.id.img) lateinit var imageView: ImageView
@BindView(R.id.txt) lateinit var textView: TextView
constructor(bundle: Bundle) : super(bundle)
constructor(sharedItem: SharedItem) : this(sharedItem.toPropsBundle())
override fun getLayoutResId(): Int = R.layout.controller_share_transition_detail
override fun onViewBound(bindingResult: View, savedState: Bundle?) {
val item = getProps<SharedItem>()
textView.text = item.text
imageView.setImageResource(item.imageRes)
ViewCompat.setTransitionName(imageView, "IMAGE${item.imageRes}")
ViewCompat.setTransitionName(textView, "TEXT${item.imageRes}")
}
}
| app/src/main/java/com/esafirm/androidplayground/conductor/sharedtransition/SharedTransitionDetailController.kt | 1566387185 |
package org.strangeforest.tcb.model
import org.junit.jupiter.api.*
class OutcomeCurveIT {
@Test @Disabled
fun testCurve() {
println("Point Game TieBreak Set NoTB Set BestOf3 BestOf5 BestOf5TB")
var p = 0.25
while (p <= 0.75) {
System.out.printf("%1\$f %2\$f %3\$f %4\$f %5\$f %6\$f %7\$f %8\$f\n",
p,
GameOutcome(p).pWin(),
TieBreakOutcome(p, p).pWin(),
SetOutcome(p, p).pWin(),
SetOutcome(p, p, null).pWin(),
MatchOutcome(p, p, 3).pWin(),
MatchOutcome(p, p, 5).pWin(),
MatchOutcome(p, p, 5, 6).pWin()
)
p += 0.005
}
}
}
| crystal-ball/src/test/kotlin/org/strangeforest/tcb/model/OutcomeCurveIT.kt | 644556222 |
/*
Commandspy - A Minecraft server plugin to facilitate real-time usage of commands, and sign-changes
Copyright (C) 2015 Evelyn Snow
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package moe.evelyn.commandspy.platform.common
import com.google.gson.JsonObject
import java.io.File
public interface CommonPlugin
{
val version :String
val pluginName :String
val platform :CommonPlatform
val dataDirectory :File
fun prepareAndLoadConfig(path :String) : JsonObject
}
| src/main/kotlin/moe/evelyn/commandspy/platform/common/CommonPlugin.kt | 2920704882 |
object Atbash {
fun encode(text: String): String {
return text.filter { it.isLetterOrDigit() }
.map { mirror(it.toLowerCase()) }
.intersperse(' ', 5)
}
fun decode(cipher: String): String =
cipher.filterNot { it.isWhitespace() }
.map { mirror(it) }
.joinToString("")
private fun mirror(c: Char): Char =
if (c in 'a' .. 'z') (219 - c.toInt()).toChar() else c
}
fun Iterable<Char>.intersperse(c: Char, span: Int): String {
val iter = this.iterator()
return object : Iterable<Char> {
override operator fun iterator(): Iterator<Char> =
object : Iterator<Char> {
val source = iter
var count = 0
override fun hasNext(): Boolean = source.hasNext()
override fun next(): Char = if (count++ % (span + 1) == span) c else source.next()
}
}.joinToString("")
}
| exercism/kotlin/atbash-cipher/src/main/kotlin/Atbash.kt | 59293252 |
// 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.tools.projectWizard.ir.buildsystem
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle.GradleConfigureTaskIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle.GradleIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle.GradleNamedTaskAccessIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle.irsList
import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.TargetJvmVersion
import org.jetbrains.kotlin.tools.projectWizard.plugins.printer.GradlePrinter
fun runTaskIrs(@NonNls mainClass: String, classPath: BuildSystemIR? = null) = irsList {
+ApplicationPluginIR(mainClass)
+ApplicationConfigurationIR(mainClass)
if (classPath != null) {
+GradleConfigureTaskIR(GradleNamedTaskAccessIR("run", "JavaExec")) {
"classpath" assign classPath
}
}
}
class ApplicationConfigurationIR(private val mainClass: String): GradleIR, FreeIR {
override fun GradlePrinter.renderGradle() {
sectionCall("application", needIndent = true) {
when (dsl) {
GradlePrinter.GradleDsl.KOTLIN -> {
call("mainClass.set") { +mainClass.quotified}
}
GradlePrinter.GradleDsl.GROOVY -> {
assignment("mainClassName") { +mainClass.quotified}
}
}
}
}
}
class KotlinExtensionConfigurationIR(private val targetJvmVersion: TargetJvmVersion) : GradleIR, FreeIR {
override fun GradlePrinter.renderGradle() {
sectionCall("kotlin", needIndent = true) {
JvmToolchainConfigurationIR(targetJvmVersion).render(this)
}
}
}
class JvmToolchainConfigurationIR(private val targetJvmVersion: TargetJvmVersion) : GradleIR, FreeIR {
override fun GradlePrinter.renderGradle() {
+"jvmToolchain"
par{ +targetJvmVersion.versionNumber.toString() }
}
}
| plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/ir/buildsystem/tasks.kt | 630803708 |
package org.jetbrains.cabal.psi
import org.jetbrains.cabal.psi.PathsField
import org.jetbrains.cabal.psi.MultiValueField
import org.jetbrains.cabal.parser.CabalTokelTypes
import com.intellij.lang.ASTNode
import com.intellij.openapi.vfs.VirtualFile
import java.io.File
import java.util.ArrayList
class IncludesField(node: ASTNode) : MultiValueField(node), PathsField {
override fun validVirtualFile(file: VirtualFile): Boolean = file.isDirectory
override fun validRelativity(path: File): Boolean = !path.isAbsolute
override fun getSourceDirs(originalRootDir: VirtualFile): List<VirtualFile>
= (getParentBuildSection()!!.getIncludeDirs().map { it.getVirtualFile(originalRootDir) }).filterNotNull()
} | plugin/src/org/jetbrains/cabal/psi/IncludesField.kt | 2620538134 |
package com.simplemobiletools.gallery.pro.activities
import android.annotation.TargetApi
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import androidx.exifinterface.media.ExifInterface
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.FileDirItem
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.dialogs.SaveAsDialog
import com.simplemobiletools.gallery.pro.extensions.config
import com.simplemobiletools.gallery.pro.extensions.fixDateTaken
import com.simplemobiletools.gallery.pro.extensions.tryDeleteFileDirItem
import com.simplemobiletools.gallery.pro.helpers.getPermissionToRequest
import ly.img.android.pesdk.VideoEditorSettingsList
import ly.img.android.pesdk.assets.filter.basic.FilterPackBasic
import ly.img.android.pesdk.assets.font.basic.FontPackBasic
import ly.img.android.pesdk.assets.overlay.basic.OverlayPackBasic
import ly.img.android.pesdk.assets.sticker.animated.StickerPackAnimated
import ly.img.android.pesdk.assets.sticker.emoticons.StickerPackEmoticons
import ly.img.android.pesdk.assets.sticker.shapes.StickerPackShapes
import ly.img.android.pesdk.backend.model.config.CropAspectAsset
import ly.img.android.pesdk.backend.model.constant.OutputMode
import ly.img.android.pesdk.backend.model.state.BrushSettings
import ly.img.android.pesdk.backend.model.state.LoadSettings
import ly.img.android.pesdk.backend.model.state.VideoEditorSaveSettings
import ly.img.android.pesdk.backend.model.state.manager.SettingsList
import ly.img.android.pesdk.ui.activity.VideoEditorBuilder
import ly.img.android.pesdk.ui.model.state.*
import ly.img.android.pesdk.ui.panels.item.CropAspectItem
import ly.img.android.pesdk.ui.panels.item.PersonalStickerAddItem
import ly.img.android.pesdk.ui.panels.item.ToggleAspectItem
import java.io.File
import java.io.InputStream
class NewVideoEditActivity : SimpleActivity() {
private val VESDK_EDIT_VIDEO = 1
private val SETTINGS_LIST = "SETTINGS_LIST"
private val SOURCE_URI = "SOURCE_URI"
private val RESULT_URI = "RESULT_URI"
private var sourceFileLastModified = 0L
private var oldExif: ExifInterface? = null
private lateinit var uri: Uri
private lateinit var saveUri: Uri
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_new_video_edit)
if (checkAppSideloading()) {
return
}
handlePermission(getPermissionToRequest()) {
if (it) {
initEditActivity()
} else {
toast(R.string.no_storage_permissions)
finish()
}
}
}
private fun initEditActivity() {
if (intent.data == null) {
toast(R.string.invalid_video_path)
finish()
return
}
uri = intent.data!!
if (uri.scheme != "file" && uri.scheme != "content") {
toast(R.string.unknown_file_location)
finish()
return
}
if (intent.extras?.containsKey(REAL_FILE_PATH) == true) {
val realPath = intent.extras!!.getString(REAL_FILE_PATH)
uri = when {
isPathOnOTG(realPath!!) -> uri
realPath.startsWith("file:/") -> Uri.parse(realPath)
else -> Uri.fromFile(File(realPath))
}
} else {
(getRealPathFromURI(uri))?.apply {
uri = Uri.fromFile(File(this))
}
}
saveUri = when {
intent.extras?.containsKey(MediaStore.EXTRA_OUTPUT) == true -> intent.extras!!.get(MediaStore.EXTRA_OUTPUT) as Uri
else -> uri
}
openEditor(uri)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
if (requestCode == VESDK_EDIT_VIDEO) {
val extras = resultData?.extras
val resultPath = extras?.get(RESULT_URI)?.toString() ?: ""
val sourcePath = Uri.decode(extras?.get(SOURCE_URI)?.toString() ?: "")
val settings = extras?.getParcelable<SettingsList>(SETTINGS_LIST)
if (settings != null) {
val brush = settings.getSettingsModel(BrushSettings::class.java)
config.editorBrushColor = brush.brushColor
config.editorBrushHardness = brush.brushHardness
config.editorBrushSize = brush.brushSize
}
if (resultCode != Activity.RESULT_OK || resultPath.isEmpty()) {
toast(R.string.video_editing_cancelled)
finish()
} else {
val source = if (sourcePath.isEmpty() || sourcePath.startsWith("content")) {
internalStoragePath
} else {
sourcePath.substringAfter("file://")
}
SaveAsDialog(this, source, true, cancelCallback = {
toast(R.string.video_editing_failed)
finish()
}, callback = {
val destinationFilePath = it
handleSAFDialog(destinationFilePath) {
if (it) {
ensureBackgroundThread {
storeOldExif(source)
sourceFileLastModified = File(source).lastModified()
handleFileOverwriting(destinationFilePath) {
try {
val inputStream = contentResolver.openInputStream(Uri.parse(resultPath))
val outputStream = getFileOutputStreamSync(destinationFilePath, destinationFilePath.getMimeType())
inputStream?.use {
outputStream?.use {
inputStream.copyTo(outputStream)
}
}
if (config.keepLastModified) {
// add 1 s to the last modified time to properly update the thumbnail
updateLastModified(destinationFilePath, sourceFileLastModified + 1000)
}
val paths = arrayListOf(destinationFilePath)
rescanPaths(paths) {
fixDateTaken(paths, false)
setResult(Activity.RESULT_OK)
toast(R.string.file_edited_successfully)
finish()
}
} catch (e: Exception) {
showErrorToast(e)
}
}
}
} else {
toast(R.string.video_editing_failed)
finish()
}
}
})
}
}
super.onActivityResult(requestCode, resultCode, resultData)
}
@TargetApi(Build.VERSION_CODES.N)
private fun storeOldExif(sourcePath: String) {
var inputStream: InputStream? = null
try {
if (isNougatPlus()) {
inputStream = contentResolver.openInputStream(Uri.fromFile(File(sourcePath)))
oldExif = ExifInterface(inputStream!!)
}
} catch (ignored: Exception) {
} finally {
inputStream?.close()
}
}
// In case the user wants to overwrite the original file and it is on an SD card, delete it manually first. Else the system just appends (1)
private fun handleFileOverwriting(path: String, callback: () -> Unit) {
if (!isRPlus() && getDoesFilePathExist(path) && isPathOnSD(path)) {
val fileDirItem = FileDirItem(path, path.getFilenameFromPath())
tryDeleteFileDirItem(fileDirItem, false, true) { success ->
if (success) {
callback()
} else {
toast(R.string.unknown_error_occurred)
finish()
}
}
} else {
callback()
}
}
private fun openEditor(inputVideo: Uri) {
val settingsList = createVesdkSettingsList()
settingsList.configure<LoadSettings> {
it.source = inputVideo
}
settingsList[LoadSettings::class].source = inputVideo
VideoEditorBuilder(this)
.setSettingsList(settingsList)
.startActivityForResult(this, VESDK_EDIT_VIDEO)
settingsList.release()
}
private fun createVesdkSettingsList(): VideoEditorSettingsList {
val settingsList = VideoEditorSettingsList(false).apply {
configure<UiConfigFilter> {
it.setFilterList(FilterPackBasic.getFilterPack())
}
configure<UiConfigText> {
it.setFontList(FontPackBasic.getFontPack())
}
config.getAssetMap(CropAspectAsset::class.java).apply {
add(CropAspectAsset("my_crop_1_2", 1, 2, false))
add(CropAspectAsset("my_crop_2_1", 2, 1, false))
add(CropAspectAsset("my_crop_19_9", 19, 9, false))
add(CropAspectAsset("my_crop_9_19", 9, 19, false))
add(CropAspectAsset("my_crop_5_4", 5, 4, false))
add(CropAspectAsset("my_crop_4_5", 4, 5, false))
add(CropAspectAsset("my_crop_37_18", 37, 18, false))
add(CropAspectAsset("my_crop_18_37", 18, 37, false))
add(CropAspectAsset("my_crop_16_10", 16, 10, false))
add(CropAspectAsset("my_crop_10_16", 10, 16, false))
}
getSettingsModel(UiConfigAspect::class.java).aspectList.apply {
add(ToggleAspectItem(CropAspectItem("my_crop_2_1"), CropAspectItem("my_crop_1_2")))
add(ToggleAspectItem(CropAspectItem("my_crop_19_9"), CropAspectItem("my_crop_9_19")))
add(ToggleAspectItem(CropAspectItem("my_crop_5_4"), CropAspectItem("my_crop_4_5")))
add(ToggleAspectItem(CropAspectItem("my_crop_37_18"), CropAspectItem("my_crop_18_37")))
add(ToggleAspectItem(CropAspectItem("my_crop_16_10"), CropAspectItem("my_crop_10_16")))
}
getSettingsModel(BrushSettings::class.java).apply {
brushColor = applicationContext.config.editorBrushColor
brushHardness = applicationContext.config.editorBrushHardness
brushSize = applicationContext.config.editorBrushSize
}
configure<UiConfigOverlay> {
it.setOverlayList(OverlayPackBasic.getOverlayPack())
}
configure<UiConfigSticker> {
it.setStickerLists(
PersonalStickerAddItem(),
StickerPackEmoticons.getStickerCategory(),
StickerPackShapes.getStickerCategory(),
StickerPackAnimated.getStickerCategory()
)
}
val theme = if (isUsingSystemDarkTheme()) {
R.style.Theme_Imgly_NoFullscreen
} else {
R.style.Theme_Imgly_Light_NoFullscreen
}
getSettingsModel(UiConfigTheme::class.java).theme = theme
configure<VideoEditorSaveSettings> {
it.allowOrientationMatrixMetadata = true
it.setOutputToTemp()
it.outputMode = OutputMode.EXPORT_IF_NECESSARY
}
}
return settingsList
}
}
| app/src/proprietary/kotlin/com/simplemobiletools/gallery/pro/activities/NewVideoEditActivity.kt | 3735026280 |
package test
import com.apollographql.apollo3.api.Optional
import kotlin.test.Test
import kotlin.test.assertIs
class OptionalTest {
@Test
fun presentIfNotNullTest() {
assertIs<Optional.Present<*>>(Optional.presentIfNotNull("some value"))
assertIs<Optional.Absent>(Optional.presentIfNotNull(null))
}
} | apollo-api/src/commonTest/kotlin/test/OptionalTest.kt | 3911705077 |
package no.skatteetaten.aurora.boober.feature
import no.skatteetaten.aurora.boober.model.AuroraDeploymentSpec
data class S3ObjectArea(
val tenant: String,
val bucketName: String,
val specifiedAreaKey: String,
val area: String = specifiedAreaKey
)
val AuroraDeploymentSpec.s3ObjectAreas
get(): List<S3ObjectArea> {
val tenantName = "$affiliation-$cluster"
val defaultBucketName: String = this["$FEATURE_DEFAULTS_FIELD_NAME/bucketName"]
val defaultObjectAreaName =
this.get<String>("$FEATURE_DEFAULTS_FIELD_NAME/objectArea").takeIf { it.isNotBlank() } ?: "default"
return if (this.isSimplifiedAndEnabled(FEATURE_FIELD_NAME)) {
val defaultS3Bucket = S3ObjectArea(
tenant = tenantName,
bucketName = defaultBucketName,
specifiedAreaKey = defaultObjectAreaName
)
listOf(defaultS3Bucket)
} else {
val objectAreaNames = getSubKeyValues(FEATURE_FIELD_NAME)
objectAreaNames
.filter { objectAreaName -> this["$FEATURE_FIELD_NAME/$objectAreaName/enabled"] }
.map { objectAreaName ->
S3ObjectArea(
tenant = tenantName,
bucketName = getOrNull("$FEATURE_FIELD_NAME/$objectAreaName/bucketName") ?: defaultBucketName,
specifiedAreaKey = objectAreaName,
area = this["$FEATURE_FIELD_NAME/$objectAreaName/objectArea"]
)
}
}
}
fun AuroraDeploymentSpec.validateS3(): List<IllegalArgumentException> {
val objectAreas = this.s3ObjectAreas
if (objectAreas.isEmpty()) return emptyList()
val requiredFieldsExceptions = objectAreas.validateRequiredFieldsArePresent()
val duplicateObjectAreaInSameBucketExceptions = objectAreas.verifyObjectAreasAreUnique()
val bucketNameExceptions = objectAreas.validateBucketNames()
return requiredFieldsExceptions + duplicateObjectAreaInSameBucketExceptions + bucketNameExceptions
}
private fun List<S3ObjectArea>.validateBucketNames() = runValidators(
{
if (!Regex("[a-z0-9-.]*").matches(it.bucketName))
"s3 bucketName can only contain lower case characters, numbers, hyphen(-) or period(.), specified value was: \"${it.bucketName}\""
else null
}, { s3ObjectArea ->
"${s3ObjectArea.tenant}-${s3ObjectArea.bucketName}"
.takeIf { it.length < 3 || it.length >= 63 }
?.let { "combination of bucketName and tenantName must be between 3 and 63 chars, specified value was ${it.length} chars long" }
}
)
private fun List<S3ObjectArea>.validateRequiredFieldsArePresent() = runValidators(
{ if (it.bucketName.isEmpty()) "Missing field: bucketName for s3" else null },
{ if (it.area.isEmpty()) "Missing field: objectArea for s3" else null }
)
private fun List<S3ObjectArea>.verifyObjectAreasAreUnique(): List<IllegalArgumentException> {
return groupBy { it.area }
.mapValues { it.value.size }
.filter { it.value > 1 }
.map { (name, count) -> IllegalArgumentException("objectArea name=$name used $count times for same application") }
}
private fun <T> List<T>.runValidators(vararg validators: (T) -> String?) =
validators.flatMap { validator -> this.mapNotNull(validator) }.map { IllegalArgumentException(it) }
private const val FEATURE_FIELD_NAME = "s3"
private const val FEATURE_DEFAULTS_FIELD_NAME = "s3Defaults"
| src/main/kotlin/no/skatteetaten/aurora/boober/feature/S3StorageGridSpec.kt | 2029053924 |
/*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okio
import kotlinx.cinterop.alloc
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.ptr
import platform.posix.ENOENT
import platform.posix.S_IFDIR
import platform.posix.S_IFMT
import platform.posix.S_IFREG
import platform.posix.errno
import platform.posix.lstat
import platform.posix.stat
internal actual fun PosixFileSystem.variantMetadataOrNull(path: Path): FileMetadata? {
return memScoped {
val stat = alloc<stat>()
if (lstat(path.toString(), stat.ptr) != 0) {
if (errno == ENOENT) return null
throw errnoToIOException(errno)
}
return@memScoped FileMetadata(
isRegularFile = stat.st_mode.toInt() and S_IFMT == S_IFREG,
isDirectory = stat.st_mode.toInt() and S_IFMT == S_IFDIR,
symlinkTarget = symlinkTarget(stat, path),
size = stat.st_size,
createdAtMillis = stat.st_ctim.epochMillis,
lastModifiedAtMillis = stat.st_mtim.epochMillis,
lastAccessedAtMillis = stat.st_atim.epochMillis
)
}
}
| okio/src/linuxX64Main/kotlin/okio/-LinuxX64PosixVariant.kt | 252322696 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.wsl.target.wizard
import com.intellij.execution.target.*
import com.intellij.ide.IdeBundle
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.components.BorderLayoutPanel
import org.jetbrains.annotations.Nls
import javax.swing.JComponent
internal class WslTargetLanguageStep(model: WslTargetWizardModel) : WslTargetStepBase(model) {
private lateinit var mainPanel: BorderLayoutPanel
private var languagesPanel: TargetEnvironmentLanguagesPanel? = null
override fun _init() {
super._init()
stepDescription = getStepDescriptionMessage()
removeLanguagesPanel()
val languagesForEditing = model.subject.createMergedLanguagesList(model.languageConfigForIntrospection)
languagesPanel = TargetEnvironmentLanguagesPanel(model.project, model.subject.getTargetType(),
{ model.subject }, languagesForEditing) {
forceMainPanelLayout()
}.also {
mainPanel.addToCenter(it.component)
forceMainPanelLayout()
}
}
@Nls(capitalization = Nls.Capitalization.Sentence)
private fun getStepDescriptionMessage(): String {
val displayName = model.languageConfigForIntrospection?.getRuntimeType()?.displayName ?: model.subject.getTargetType().displayName
return IdeBundle.message("wsl.target.language.step.description", displayName, model.guessName())
}
private fun removeLanguagesPanel() {
languagesPanel?.let {
mainPanel.remove(it.component)
it.disposeUIResources()
languagesPanel = null
}
}
override fun createMainPanel(): JComponent {
return BorderLayoutPanel().also {
it.border = JBUI.Borders.empty(LARGE_VGAP, TargetEnvironmentWizard.defaultDialogInsets().right)
mainPanel = it
}
}
private fun forceMainPanelLayout() {
with(component) {
revalidate()
repaint()
}
}
override fun getPreferredFocusedComponent(): JComponent? {
return languagesPanel?.preferredFocusedComponent
}
override fun getStepId(): Any = ID
override fun getNextStepId(): Any? = null
override fun getPreviousStepId(): Any = WslTargetIntrospectionStep.ID
override fun isComplete(): Boolean = true
override fun doCommit(commitType: CommitType?) {
if (commitType == CommitType.Finish) {
languagesPanel?.let {
it.applyAll()
model.subject.runtimes.replaceAllWith(it.languagesList.resolvedConfigs())
}
model.save()
}
}
companion object {
@JvmStatic
val ID: Any = WslTargetLanguageStep::class
/**
* Assumes that the first language runtime, if present, is previous introspected version and replaces it with the fresh one.
* Assumes that all the languages after the first were added by user and leaves them untouched.
*/
private fun TargetEnvironmentConfiguration.createMergedLanguagesList(introspected: LanguageRuntimeConfiguration?) =
ContributedConfigurationsList(LanguageRuntimeType.EXTENSION_NAME).also { result ->
val resolvedConfigs = this.runtimes.resolvedConfigs()
if (introspected != null) {
result.addConfig(introspected)
resolvedConfigs.drop(1)
}
resolvedConfigs.forEach { next ->
result.addConfig(next)
}
}
}
}
| platform/execution-impl/src/com/intellij/execution/wsl/target/wizard/WslTargetLanguageStep.kt | 358548319 |
package org.techbooster.sample.library_core
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.View
class LibraryCoreActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_librarycore)
val toolbar = findViewById<View>(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
}
companion object {
fun createIntent(context: Context): Intent {
return Intent(context, LibraryCoreActivity::class.java)
}
}
}
| AarDemo/library-core/src/main/java/org/techbooster/sample/library_core/LibraryCoreActivity.kt | 766477378 |
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui.colorpicker
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CustomShortcutSet
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.ui.JBColor
import com.intellij.ui.picker.ColorListener
import com.intellij.util.Function
import com.intellij.util.ui.JBUI
import java.awt.Color
import java.awt.Component
import java.awt.Container
import java.awt.Dimension
import java.awt.event.ActionEvent
import java.awt.event.KeyEvent
import javax.swing.*
val PICKER_BACKGROUND_COLOR = JBColor(Color(252, 252, 252), Color(64, 64, 64))
val PICKER_TEXT_COLOR = Color(186, 186, 186)
const val PICKER_PREFERRED_WIDTH = 300
const val HORIZONTAL_MARGIN_TO_PICKER_BORDER = 14
private val PICKER_BORDER = JBUI.Borders.emptyBottom(10)
private const val SEPARATOR_HEIGHT = 5
/**
* Builder class to help to create customized picker components depends on the requirement.
*/
class ColorPickerBuilder(private val showAlpha: Boolean = false, private val showAlphaAsPercent: Boolean = true) {
private val componentsToBuild = mutableListOf<JComponent>()
val model = ColorPickerModel()
private var originalColor: Color? = null
private var requestFocusWhenDisplay = false
private var focusCycleRoot = false
private var focusedComponentIndex = -1
private val actionMap = mutableMapOf<KeyStroke, Action>()
private val colorListeners = mutableListOf<ColorListenerInfo>()
fun setOriginalColor(originalColor: Color?) = apply { this.originalColor = originalColor }
fun addSaturationBrightnessComponent() = apply { componentsToBuild.add(SaturationBrightnessComponent(model)) }
@JvmOverloads
fun addColorAdjustPanel(colorPipetteProvider: ColorPipetteProvider = GraphicalColorPipetteProvider()) = apply {
componentsToBuild.add(ColorAdjustPanel(model, colorPipetteProvider, showAlpha))
}
fun addColorValuePanel() = apply { componentsToBuild.add(ColorValuePanel(model, showAlpha, showAlphaAsPercent)) }
/**
* If both [okOperation] and [cancelOperation] are null, [IllegalArgumentException] will be raised.
*/
fun addOperationPanel(okOperation: ((Color) -> Unit)?, cancelOperation: ((Color) -> Unit)?) = apply {
componentsToBuild.add(OperationPanel(model, okOperation, cancelOperation))
if (cancelOperation != null) {
addKeyAction(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, true), object : AbstractAction() {
override fun actionPerformed(e: ActionEvent?) = cancelOperation.invoke(model.color)
})
}
}
/**
* Add the custom components in to color picker.
*/
fun addCustomComponent(provider: ColorPickerComponentProvider) = apply { componentsToBuild.add(provider.createComponent(model)) }
fun addSeparator() = apply {
val separator = JSeparator(JSeparator.HORIZONTAL)
separator.border = JBUI.Borders.empty()
separator.preferredSize = JBUI.size(PICKER_PREFERRED_WIDTH, SEPARATOR_HEIGHT)
componentsToBuild.add(separator)
}
/**
* Set if Color Picker should request focus when it is displayed.<br>
*
* The default value is **false**
*/
fun focusWhenDisplay(focusWhenDisplay: Boolean) = apply { requestFocusWhenDisplay = focusWhenDisplay }
/**
* Set if Color Picker is the root of focus cycle.<br>
* Set to true to makes the focus traversal inside this Color Picker only. This is useful when the Color Picker is used in an independent
* window, e.g. a popup component or dialog.<br>
*
* The default value is **false**.
*
* @see Component.isFocusCycleRoot
*/
fun setFocusCycleRoot(focusCycleRoot: Boolean) = apply { this.focusCycleRoot = focusCycleRoot }
/**
* When getting the focus, focus to the last added component.<br>
* If this function is called multiple times, only the last time effects.<br>
* By default, nothing is focused in ColorPicker.
*/
fun withFocus() = apply { focusedComponentIndex = componentsToBuild.size - 1 }
fun addKeyAction(keyStroke: KeyStroke, action: Action) = apply { actionMap[keyStroke] = action }
fun addColorListener(colorListener: ColorListener) = addColorListener(colorListener, true)
fun addColorListener(colorListener: ColorListener, invokeOnEveryColorChange: Boolean) = apply {
colorListeners.add(ColorListenerInfo(colorListener, invokeOnEveryColorChange))
}
fun build(): LightCalloutPopup {
if (componentsToBuild.isEmpty()) {
throw IllegalStateException("The Color Picker should have at least one picking component.")
}
val width: Int = componentsToBuild.map { it.preferredSize.width }.max()!!
val height = componentsToBuild.map { it.preferredSize.height }.sum()
var defaultFocusComponent = componentsToBuild.getOrNull(focusedComponentIndex)
if (defaultFocusComponent is ColorValuePanel) {
defaultFocusComponent = defaultFocusComponent.hexField
}
val panel = object : JPanel() {
override fun requestFocusInWindow() = defaultFocusComponent?.requestFocusInWindow() ?: false
override fun addNotify() {
super.addNotify()
if (requestFocusWhenDisplay) {
requestFocusInWindow()
}
}
}
panel.layout = BoxLayout(panel, BoxLayout.Y_AXIS)
panel.border = PICKER_BORDER
panel.preferredSize = Dimension(width, height)
panel.background = PICKER_BACKGROUND_COLOR
val c = originalColor
if (c != null) {
model.setColor(c, null)
}
for (component in componentsToBuild) {
panel.add(component)
}
panel.isFocusCycleRoot = focusCycleRoot
panel.isFocusTraversalPolicyProvider = true
panel.focusTraversalPolicy = MyFocusTraversalPolicy(defaultFocusComponent)
actionMap.forEach { (keyStroke, action) ->
DumbAwareAction.create {
e: AnActionEvent? -> action.actionPerformed(ActionEvent(e?.inputEvent, 0, ""))
}.registerCustomShortcutSet(CustomShortcutSet(keyStroke), panel)
}
colorListeners.forEach { model.addListener(it.colorListener, it.invokeOnEveryColorChange) }
return LightCalloutPopup(panel,
closedCallback = { model.onClose() },
cancelCallBack = { model.onCancel() })
}
}
private class MyFocusTraversalPolicy(val defaultComponent: Component?) : LayoutFocusTraversalPolicy() {
override fun getDefaultComponent(aContainer: Container?): Component? = defaultComponent
}
private data class ColorListenerInfo(val colorListener: ColorListener, val invokeOnEveryColorChange: Boolean)
| platform/platform-impl/src/com/intellij/ui/colorpicker/ColorPickerBuilder.kt | 247217683 |
package com.trevjonez.ktor_playground.people
import com.trevjonez.ktor_playground.EntityRouter
import com.trevjonez.ktor_playground.Validator
import dagger.Binds
import dagger.Module
import dagger.Provides
import dagger.multibindings.IntoSet
import io.requery.reactivex.KotlinReactiveEntityStore
import io.requery.sql.Configuration
import io.requery.sql.KotlinEntityDataStore
import org.jetbrains.ktor.routing.Routing
@Module(includes = arrayOf(PersonModule.Bindings::class))
class PersonModule {
@Module
abstract class Bindings {
@Binds @IntoSet abstract fun personRoute(impl: PersonRouting): EntityRouter
@Binds abstract fun personRepo(impl: PersonRepoRequery): PersonRepository<PersonEntity>
}
@Provides
fun postValidator(): Validator.Post<Person, PersonEntity> = PersonEntity.PostValidator
@Provides
fun ktEntityStore(config: Configuration) = KotlinEntityDataStore<PersonEntity>(config)
@Provides
fun ktReactiveEntityStore(ktStore: KotlinEntityDataStore<PersonEntity>) = KotlinReactiveEntityStore(ktStore)
} | src/main/kotlin/com/trevjonez/ktor_playground/people/PersonModule.kt | 656723125 |
package jp.takke.cpustats
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class ConfigActivity : AppCompatActivity() {
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_config)
supportFragmentManager
.beginTransaction()
.replace(R.id.settings_container, ConfigFragment())
.commit()
}
}
| app/src/main/java/jp/takke/cpustats/ConfigActivity.kt | 758153833 |
/*
* Copyright 2022 Benoit LETONDOR
*
* 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.benoitletondor.easybudgetapp.view.report
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.benoitletondor.easybudgetapp.R
import com.benoitletondor.easybudgetapp.helper.CurrencyHelper
import com.benoitletondor.easybudgetapp.helper.launchCollect
import com.benoitletondor.easybudgetapp.helper.viewLifecycleScope
import com.benoitletondor.easybudgetapp.parameters.Parameters
import dagger.hilt.android.AndroidEntryPoint
import java.time.LocalDate
import javax.inject.Inject
private const val ARG_FIRST_DAY_OF_MONTH_DATE = "arg_date"
/**
* Fragment that displays monthly report for a given month
*
* @author Benoit LETONDOR
*/
@AndroidEntryPoint
class MonthlyReportFragment : Fragment() {
/**
* The first day of the month
*/
private lateinit var firstDayOfMonth: LocalDate
private val viewModel: MonthlyReportViewModel by viewModels()
@Inject lateinit var parameters: Parameters
// ---------------------------------->
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
firstDayOfMonth = requireArguments().getSerializable(ARG_FIRST_DAY_OF_MONTH_DATE) as LocalDate
// Inflate the layout for this fragment
val v = inflater.inflate(R.layout.fragment_monthly_report, container, false)
val progressBar = v.findViewById<ProgressBar>(R.id.monthly_report_fragment_progress_bar)
val content = v.findViewById<View>(R.id.monthly_report_fragment_content)
val recyclerView = v.findViewById<RecyclerView>(R.id.monthly_report_fragment_recycler_view)
val emptyState = v.findViewById<View>(R.id.monthly_report_fragment_empty_state)
val revenuesAmountTextView = v.findViewById<TextView>(R.id.monthly_report_fragment_revenues_total_tv)
val expensesAmountTextView = v.findViewById<TextView>(R.id.monthly_report_fragment_expenses_total_tv)
val balanceTextView = v.findViewById<TextView>(R.id.monthly_report_fragment_balance_tv)
viewLifecycleScope.launchCollect(viewModel.stateFlow) { state ->
when(state) {
MonthlyReportViewModel.MonthlyReportState.Empty -> {
progressBar.visibility = View.GONE
content.visibility = View.VISIBLE
recyclerView.visibility = View.GONE
emptyState.visibility = View.VISIBLE
revenuesAmountTextView.text = CurrencyHelper.getFormattedCurrencyString(parameters, 0.0)
expensesAmountTextView.text = CurrencyHelper.getFormattedCurrencyString(parameters, 0.0)
balanceTextView.text = CurrencyHelper.getFormattedCurrencyString(parameters, 0.0)
balanceTextView.setTextColor(ContextCompat.getColor(balanceTextView.context, R.color.budget_green))
}
is MonthlyReportViewModel.MonthlyReportState.Loaded -> {
progressBar.visibility = View.GONE
content.visibility = View.VISIBLE
configureRecyclerView(recyclerView, MonthlyReportRecyclerViewAdapter(state.expenses, state.revenues, parameters))
revenuesAmountTextView.text = CurrencyHelper.getFormattedCurrencyString(parameters, state.revenuesAmount)
expensesAmountTextView.text = CurrencyHelper.getFormattedCurrencyString(parameters, state.expensesAmount)
val balance = state.revenuesAmount - state.expensesAmount
balanceTextView.text = CurrencyHelper.getFormattedCurrencyString(parameters, balance)
balanceTextView.setTextColor(ContextCompat.getColor(balanceTextView.context, if (balance >= 0) R.color.budget_green else R.color.budget_red))
}
MonthlyReportViewModel.MonthlyReportState.Loading -> {
progressBar.visibility = View.VISIBLE
content.visibility = View.GONE
}
}
}
viewModel.loadDataForMonth(firstDayOfMonth)
return v
}
/**
* Configure recycler view LayoutManager & adapter
*/
private fun configureRecyclerView(recyclerView: RecyclerView, adapter: MonthlyReportRecyclerViewAdapter) {
recyclerView.layoutManager = LinearLayoutManager(activity)
recyclerView.adapter = adapter
}
companion object {
fun newInstance(firstDayOfMonth: LocalDate): MonthlyReportFragment = MonthlyReportFragment().apply {
arguments = Bundle().apply {
putSerializable(ARG_FIRST_DAY_OF_MONTH_DATE, firstDayOfMonth)
}
}
}
}
| Android/EasyBudget/app/src/main/java/com/benoitletondor/easybudgetapp/view/report/MonthlyReportFragment.kt | 1526648698 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.env.tensorFlow
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.CapturingProcessHandler
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.util.Computable
import com.intellij.psi.PsiElement
import com.intellij.testFramework.UsefulTestCase
import com.jetbrains.env.EnvTestTagsRequired
import com.jetbrains.env.PyEnvTestCase
import com.jetbrains.env.PyExecutionFixtureTestTask
import com.jetbrains.python.PythonFileType
import com.jetbrains.python.PythonTestUtil
import com.jetbrains.python.psi.PyFile
import com.jetbrains.python.psi.PyReferenceExpression
import com.jetbrains.python.psi.PyUtil
import com.jetbrains.python.psi.resolve.PyResolveContext
import com.jetbrains.python.psi.types.TypeEvalContext
import com.jetbrains.python.sdk.PySdkUtil
import com.jetbrains.python.tools.sdkTools.SdkCreationType
import junit.framework.TestCase
import org.junit.Test
import java.nio.file.Files
import java.nio.file.Paths
import java.util.concurrent.TimeUnit
class PyTensorFlowTest : PyEnvTestCase() {
@Test
@EnvTestTagsRequired(tags = ["tensorflow1", "tensorflow_oldpaths"])
fun tensorFlow1ModulesOldPaths() {
runPythonTest(TensorFlowModulesTask("tf1old.txt", setOf("lite")))
}
@Test
@EnvTestTagsRequired(tags = ["tensorflow1", "tensorflow_newpaths"])
fun tensorFlow1ModulesNewPaths() {
runPythonTest(TensorFlowModulesTask("tf1new.txt"))
}
@Test
@EnvTestTagsRequired(tags = ["tensorflow2", "tensorflow_oldpaths"])
fun tensorFlow2ModulesOldPaths() {
runPythonTest(TensorFlowModulesTask("tf2old.txt", setOf("lite")))
}
@Test
@EnvTestTagsRequired(tags = ["tensorflow2", "tensorflow_newpaths"])
fun tensorFlow2ModulesNewPaths() {
runPythonTest(TensorFlowModulesTask("tf2new.txt"))
}
private class TensorFlowModulesTask(private val expectedModulesFile: String,
private val modulesToIgnoreInResolve: Set<String> = emptySet()) : PyExecutionFixtureTestTask(null) {
override fun runTestOn(sdkHome: String, existingSdk: Sdk?) {
val actualModules = loadActualModules(createTempSdk(sdkHome, SdkCreationType.SDK_PACKAGES_AND_SKELETONS))
val expectedModules = loadModules(Files.readAllLines(Paths.get(PythonTestUtil.getTestDataPath(), "tensorflow", expectedModulesFile)))
TestCase.assertEquals(expectedModules, actualModules)
runCompletion(actualModules.keys)
runResolve(actualModules)
}
private fun loadActualModules(sdk: Sdk): Map<String, String> {
val script = Paths.get(PythonTestUtil.getTestDataPath(), "tensorflow", "modules.py").toAbsolutePath().toString()
val env = PySdkUtil.activateVirtualEnv(sdk)
val timeout = TimeUnit.SECONDS.toMillis(30).toInt()
val commandLine = GeneralCommandLine(sdk.homePath).withParameters(script).withEnvironment(env)
return loadModules(CapturingProcessHandler(commandLine).runProcess(timeout, true).stdoutLines)
}
private fun loadModules(lines: List<String>): Map<String, String> {
return lines
.asSequence()
.map { it.split(' ', limit = 2) }
.map { it[0] to it[1] }
.toMap()
}
private fun runCompletion(modules: Collection<String>) {
// `from tensorflow.<m>` completes
// `import tensorflow.<m>` completes
// `tensorflow.<m>` completes
configureAndCompleteAtCaret("from tensorflow.<caret>", modules)
configureAndCompleteAtCaret("import tensorflow.<caret>", modules)
configureAndCompleteAtCaret("import tensorflow\ntensorflow.<caret>", modules)
}
private fun runResolve(modules: Map<String, String>) {
// `from tensorflow.<m>` resolves
// `import tensorflow.<m>` resolves
// `tensorflow.<m>` resolves
// everything resolves to the same element
modules.asSequence().filter { (module, _) -> module !in modulesToIgnoreInResolve }.forEach { (module, path) ->
val first = configureAndResolveAtCaret("from tensorflow.$module<caret> import *")
val second = configureAndResolveAtCaret("import tensorflow.$module<caret>")
val third = configureAndResolveAtCaret("import tensorflow\ntensorflow.$module<caret>")
UsefulTestCase.assertSame("first: ${moduleToPath(first)} vs second: ${moduleToPath(second)}", first, second)
UsefulTestCase.assertSame("first: ${moduleToPath(first)} vs third: ${moduleToPath(third)}", first, third)
TestCase.assertEquals(path, moduleToPath(first))
}
}
private fun configureAndCompleteAtCaret(text: String, modules: Collection<String>) {
myFixture.configureByText(PythonFileType.INSTANCE, text)
myFixture.completeBasic()
UsefulTestCase.assertContainsElements(myFixture.lookupElementStrings!!, modules)
}
private fun configureAndResolveAtCaret(text: String): PsiElement {
val file = myFixture.configureByText(PythonFileType.INSTANCE, text)
return ApplicationManager.getApplication().runReadAction(
Computable {
val reference = myFixture.file.findElementAt(myFixture.caretOffset - 1)!!.parent as PyReferenceExpression
val resolveContext = PyResolveContext.defaultContext().withTypeEvalContext(TypeEvalContext.codeAnalysis(project, file))
PyUtil.turnDirIntoInit(reference.followAssignmentsChain(resolveContext).element)!!
}
)
}
private fun moduleToPath(module: PsiElement): String {
return ApplicationManager.getApplication().runReadAction(
Computable {
var current = (module as PyFile).containingDirectory
val components = mutableListOf<String>()
while (current.name != "site-packages") {
components.add(current.name)
current = current.parent
}
components.asReversed().joinToString(".")
}
)
}
}
}
| python/testSrc/com/jetbrains/env/tensorFlow/PyTensorFlowTest.kt | 3561884229 |
// 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 com.intellij.openapi.Disposable
import com.intellij.openapi.progress.util.ProgressWindow
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.components.JBLoadingPanel
import com.intellij.util.ui.ComponentWithEmptyText
import com.intellij.vcs.log.ui.frame.ProgressStripe
import org.jetbrains.plugins.github.util.getName
import java.awt.BorderLayout
import java.awt.event.KeyEvent
import javax.swing.JComponent
import javax.swing.KeyStroke
class GHLoadingPanel<T>(private val model: GHLoadingModel,
private val content: T,
parentDisposable: Disposable,
private val textBundle: EmptyTextBundle = EmptyTextBundle.Default)
: JBLoadingPanel(BorderLayout(), parentDisposable, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS)
where T : JComponent, T : ComponentWithEmptyText {
private val updateLoadingPanel =
ProgressStripe(content, parentDisposable, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS).apply {
isOpaque = false
}
var errorHandler: GHLoadingErrorHandler? = null
init {
isOpaque = false
add(updateLoadingPanel, BorderLayout.CENTER)
model.addStateChangeListener(object : GHLoadingModel.StateChangeListener {
override fun onLoadingStarted() = update()
override fun onLoadingCompleted() = update()
override fun onReset() = update()
})
update()
}
private fun update() {
if (model.loading) {
isFocusable = true
content.emptyText.clear()
if (model.resultAvailable) {
updateLoadingPanel.startLoading()
}
else {
startLoading()
}
}
else {
stopLoading()
updateLoadingPanel.stopLoading()
if (model.resultAvailable) {
isFocusable = false
resetKeyboardActions()
content.emptyText.text = textBundle.empty
}
else {
val error = model.error
if (error != null) {
val emptyText = content.emptyText
emptyText.clear()
.appendText(textBundle.errorPrefix, SimpleTextAttributes.ERROR_ATTRIBUTES)
.appendSecondaryText(error.message ?: "Unknown error", SimpleTextAttributes.ERROR_ATTRIBUTES, null)
errorHandler?.getActionForError(error)?.let {
emptyText.appendSecondaryText(" ${it.getName()}", SimpleTextAttributes.LINK_PLAIN_ATTRIBUTES, it)
registerKeyboardAction(it, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_FOCUSED)
}
}
else content.emptyText.text = textBundle.default
}
}
}
interface EmptyTextBundle {
val default: String
val empty: String
val errorPrefix: String
class Simple(override val default: String, override val errorPrefix: String, override val empty: String = "") : EmptyTextBundle
object Default : EmptyTextBundle {
override val default: String = ""
override val empty: String = ""
override val errorPrefix: String = "Can't load data"
}
}
} | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/GHLoadingPanel.kt | 1523882948 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.progress.impl
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.Clock
import com.intellij.openapi.util.registry.Registry
import org.jetbrains.annotations.TestOnly
/**
* It is used to check if [ProgressManager.checkCanceled] is invoked often enough - at least once per a threshold ms.
*
* For global usage [CancellationCheck.runWithCancellationCheck] could be used:
* - it has to be enabled with a registry key `ide.cancellation.check.enabled`, it is disabled by default
* - threshold (in ms) is specified with a registry key `ide.cancellation.check.threshold`, default is 500
*/
class CancellationCheck private constructor(val thresholdMs: () -> Long, val checkEnabled: () -> Boolean) {
@TestOnly
internal constructor(thresholdMs: Long): this(thresholdMs = { thresholdMs }, checkEnabled = { true })
private val statusRecord = ThreadLocal.withInitial { CanceledStatusRecord() }
private val hook = CoreProgressManager.CheckCanceledHook { indicator ->
checkCancellationDiff(statusRecord.get())
return@CheckCanceledHook indicator != null
}
private fun checkCancellationDiff(record: CanceledStatusRecord) {
if (record.enabled) {
val now = Clock.getTime()
val diff = now - record.timestamp
if (diff > thresholdMs()) {
LOG.error("${Thread.currentThread().name} last checkCanceled was $diff ms ago")
}
record.timestamp = now
}
}
private fun enableCancellationTimer(record: CanceledStatusRecord, enabled: Boolean) {
val progressManagerImpl = ProgressManager.getInstance() as ProgressManagerImpl
if (enabled) progressManagerImpl.addCheckCanceledHook(hook) else progressManagerImpl.removeCheckCanceledHook(hook)
record.enabled = enabled
record.timestamp = Clock.getTime()
}
fun <T> withCancellationCheck(block: () -> T): T {
if (!checkEnabled()) return block()
val record = statusRecord.get()
if (record.enabled) return block()
enableCancellationTimer(record, true)
try {
return block()
} finally {
try {
checkCancellationDiff(record)
}
finally {
enableCancellationTimer(record,false)
}
}
}
private data class CanceledStatusRecord(var enabled: Boolean = false, var timestamp: Long = Clock.getTime())
companion object {
private val LOG = Logger.getInstance(CancellationCheck::class.java)
@JvmStatic
private val INSTANCE: CancellationCheck =
CancellationCheck(
thresholdMs = { Registry.intValue("ide.cancellation.check.threshold").toLong() },
checkEnabled = { Registry.`is`("ide.cancellation.check.enabled") }
)
@JvmStatic
fun <T> runWithCancellationCheck(block: () -> T): T =
INSTANCE.withCancellationCheck(block)
}
}
| platform/platform-impl/src/com/intellij/openapi/progress/impl/CancellationCheck.kt | 1174668274 |
@file:Suppress("UNUSED_ANONYMOUS_PARAMETER", "unused")
package com.github.windchopper.tools.password.drop.ui
import com.github.windchopper.common.fx.cdi.form.Form
import com.github.windchopper.tools.password.drop.Application
import com.github.windchopper.tools.password.drop.book.*
import com.github.windchopper.tools.password.drop.crypto.CryptoEngine
import com.github.windchopper.tools.password.drop.crypto.Salt
import com.github.windchopper.tools.password.drop.misc.*
import jakarta.enterprise.context.ApplicationScoped
import jakarta.enterprise.event.Event
import jakarta.enterprise.event.Observes
import jakarta.inject.Inject
import javafx.application.Platform
import javafx.beans.binding.Bindings.createBooleanBinding
import javafx.beans.binding.Bindings.not
import javafx.beans.binding.BooleanBinding
import javafx.event.ActionEvent
import javafx.fxml.FXML
import javafx.geometry.Dimension2D
import javafx.geometry.Insets
import javafx.scene.Parent
import javafx.scene.Scene
import javafx.scene.control.*
import javafx.scene.effect.DropShadow
import javafx.scene.image.Image
import javafx.scene.image.WritableImage
import javafx.scene.input.ClipboardContent
import javafx.scene.input.DataFormat
import javafx.scene.input.TransferMode
import javafx.scene.layout.Background
import javafx.scene.layout.BackgroundFill
import javafx.scene.layout.CornerRadii
import javafx.scene.paint.Color
import javafx.scene.paint.Paint
import javafx.scene.text.Text
import javafx.stage.FileChooser
import javafx.stage.FileChooser.ExtensionFilter
import javafx.stage.Modality
import javafx.stage.Screen
import javafx.stage.StageStyle
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.net.URL
import java.nio.file.Path
import java.nio.file.Paths
import javax.imageio.ImageIO
import kotlin.math.abs
import kotlin.reflect.KClass
@ApplicationScoped @Form(Application.FXML_MAIN) class MainController: Controller() {
@Inject private lateinit var bookCase: BookCase
@Inject private lateinit var treeEditEvent: Event<TreeEdit<BookPart>>
@Inject private lateinit var treeSelectionEvent: Event<TreeSelection<BookPart>>
@Inject private lateinit var mainHideEvent: Event<MainHide>
@FXML private lateinit var bookView: TreeView<BookPart>
@FXML private lateinit var newPageMenuItem: MenuItem
@FXML private lateinit var newParagraphMenuItem: MenuItem
@FXML private lateinit var newPhraseMenuItem: MenuItem
@FXML private lateinit var editMenuItem: MenuItem
@FXML private lateinit var deleteMenuItem: MenuItem
@FXML private lateinit var stayOnTopMenuItem: CheckMenuItem
@FXML private lateinit var reloadBookMenuItem: MenuItem
private var trayIcon: java.awt.TrayIcon? = null
private var openBook: Book? = null
override fun preferredStageSize(): Dimension2D {
return Screen.getPrimary().visualBounds
.let { Dimension2D(it.width / 6, it.height / 3) }
}
override fun afterLoad(form: Parent, parameters: MutableMap<String, *>, formNamespace: MutableMap<String, *>) {
super.afterLoad(form, parameters, formNamespace)
with (stage) {
initStyle(StageStyle.UTILITY)
title = Application.messages["main.head"]
isAlwaysOnTop = Application.stayOnTop.load().value?:false
stayOnTopMenuItem.isSelected = isAlwaysOnTop
setOnCloseRequest {
mainHideEvent.fire(MainHide())
}
with (scene) {
fill = Color.TRANSPARENT
}
}
with (bookView) {
with (selectionModel) {
selectionMode = SelectionMode.SINGLE
selectedItemProperty().addListener { selectedItemProperty, oldSelection, newSelection ->
treeSelectionEvent.fire(TreeSelection(this@MainController, oldSelection, newSelection))
}
}
setOnDragDetected { event ->
selectionModel.selectedItem?.value
?.let { bookPart ->
if (bookPart is Phrase) {
val content = ClipboardContent()
content[DataFormat.PLAIN_TEXT] = bookPart.text?:""
val dragBoard = bookView.startDragAndDrop(TransferMode.COPY)
dragBoard.setContent(content)
fun invertPaint(fill: Paint): Color = if (fill is Color) {
fill.invert()
} else {
Color.WHITE
}
val label = Label(bookPart.name)
.also {
it.background = Background(BackgroundFill(Color.TRANSPARENT, CornerRadii.EMPTY, Insets.EMPTY))
it.effect = DropShadow(3.0, invertPaint(it.textFill))
}
val textBounds = Text(bookPart.name)
.let {
it.font = label.font
it.boundsInLocal
}
dragBoard.dragView = WritableImage(textBounds.width.toInt(), textBounds.height.toInt())
.also { image ->
Scene(label)
.also { it.fill = Color.TRANSPARENT }
.snapshot(image)
}
event.consume()
}
}
}
}
addMenuItemBindings()
addTrayIcon(stage.icons)
GlobalScope.launch {
openBook = Application.openBookPath.load()
?.value
?.let(bookCase::readBook)
?:buildNewBook()
fillBookViewFromBook()
prepareEncryptEngine()
}
}
fun buildNewBook(): Book {
return Book().also { book ->
book.name = Application.messages["book.unnamed"]
book.newPage().also { page ->
page.newParagraph().also { paragraph ->
paragraph.newPhrase()
}
}
}
}
suspend fun fillBookViewFromBook() {
openBook?.let { loadedBook ->
runWithFxThread {
reloadBookMenuItem.isDisable = loadedBook.path == null
val rootItem = TreeItem<BookPart>(openBook)
.also {
bookView.root = it
it.isExpanded = true
}
loadedBook.pages.forEach { page ->
val pageItem = TreeItem<BookPart>(page)
.also {
rootItem.children.add(it)
it.isExpanded = true
}
page.paragraphs.forEach { paragraph ->
val paragraphItem = TreeItem<BookPart>(paragraph)
.also {
pageItem.children.add(it)
it.isExpanded = true
}
paragraph.phrases.forEach { word ->
TreeItem<BookPart>(word)
.also {
paragraphItem.children.add(it)
}
}
}
}
}
}
}
suspend fun prepareEncryptEngine() {
openBook?.let { book ->
if (book.path != null && book.saltRaw == null) {
return
}
val (alertChoice, passwordProperty) = runWithFxThread {
val passwordAlert = prepareAlert(PasswordAlert(book.path == null), Modality.APPLICATION_MODAL)
Pair(passwordAlert.showAndWait(), passwordAlert.passwordProperty)
}
alertChoice
.filter { it == ButtonType.OK }
.ifPresent {
book.cryptoEngine = CryptoEngine(passwordProperty.get(), Salt(book.saltRaw)
.also { book.saltRaw = it.saltRaw })
}
}
}
fun addMenuItemBindings() {
with (bookView.selectionModel) {
fun selectedItemIs(type: KClass<*>): BooleanBinding {
return createBooleanBinding(
{
selectedItem?.value
?.let { type.isInstance(it) }
?:false
},
selectedItemProperty())
}
newPageMenuItem.disableProperty().bind(selectedItemProperty().isNull.or(selectedItemIs(Book::class).not()))
newParagraphMenuItem.disableProperty().bind(selectedItemProperty().isNull.or(selectedItemIs(Page::class).not()))
newPhraseMenuItem.disableProperty().bind(selectedItemProperty().isNull.or(selectedItemIs(Paragraph::class).not()))
editMenuItem.disableProperty().bind(selectedItemProperty().isNull)
deleteMenuItem.disableProperty().bind(selectedItemProperty().isNull.and(not(selectedItemIs(InternalBookPart::class))))
}
}
fun addTrayIcon(images: List<Image>) {
if (java.awt.SystemTray.isSupported()) {
val systemTray = java.awt.SystemTray.getSystemTray()
val trayIconImage = ImageIO.read(URL(
images.map { abs(systemTray.trayIconSize.width - it.width) to it.url }.minByOrNull { it.first }
!!.second))
trayIcon = java.awt.TrayIcon(trayIconImage, Application.messages["tray.head"])
.also { icon ->
systemTray.add(icon)
val openAction = java.awt.event.ActionListener {
Platform.runLater {
with (stage) {
show()
toFront()
}
}
}
icon.addActionListener(openAction)
icon.popupMenu = java.awt.PopupMenu()
.also { menu ->
menu.add(java.awt.MenuItem(Application.messages["tray.show"])
.also { item ->
item.addActionListener(openAction)
item.font = java.awt.Font.decode(null)
.deriveFont(java.awt.Font.BOLD)
})
menu.add(java.awt.MenuItem(Application.messages["tray.exit"])
.also { item ->
item.addActionListener {
Platform.exit()
}
})
}
}
}
}
@FXML fun newPage(event: ActionEvent) {
with (bookView) {
selectionModel.selectedItem.let { item ->
(item.value as Book).newPage().also {
item.children.add(TreeItem(it))
}
}
}
}
@FXML fun newParagraph(event: ActionEvent) {
with (bookView) {
selectionModel.selectedItem.let { item ->
(item.value as Page).newParagraph().also {
item.children.add(TreeItem(it))
}
}
}
}
@FXML fun newPhrase(event: ActionEvent) {
with (bookView) {
selectionModel.selectedItem.let { item ->
(item.value as Paragraph).newPhrase().also {
item.children.add(TreeItem(it))
}
}
}
}
@FXML fun edit(event: ActionEvent) {
treeEditEvent.fire(TreeEdit(this, bookView.selectionModel.selectedItem))
}
@FXML fun delete(event: ActionEvent) {
with (bookView.selectionModel.selectedItem) {
value.let {
if (it is InternalBookPart<*>) {
parent.children.remove(this)
it.removeFromParent()
}
}
}
}
fun prepareFileChooser(): FileChooser {
return FileChooser()
.also {
it.initialDirectory = (Application.openBookPath.load().value?.parent?:Paths.get(System.getProperty("user.home"))).toFile()
it.extensionFilters.add(ExtensionFilter(Application.messages["books"], "*.book.xml"))
}
}
@FXML fun open(event: ActionEvent) {
prepareFileChooser().showOpenDialog(stage)
?.let { file ->
loadBook(file.toPath())
}
}
fun loadBook(path: Path) {
GlobalScope.launch {
exceptionally {
openBook = bookCase.readBook(path)
runBlocking {
fillBookViewFromBook()
prepareEncryptEngine()
}
}
}
}
@FXML fun reload(event: ActionEvent) {
}
@FXML fun save(event: ActionEvent) {
openBook?.let { book ->
if (book.path == null) {
book.path = FileChooser()
.let {
it.initialDirectory = (Application.openBookPath.load().value?:Paths.get(System.getProperty("user.home"))).toFile()
it.extensionFilters.add(ExtensionFilter(Application.messages["books"], "*.book.xml"))
it.showSaveDialog(stage)?.toPath()
}
}
book.path?.let {
bookCase.saveBook(book, it)
Application.openBookPath.save(it)
}
}
}
@FXML fun toggleStayOnTop(event: ActionEvent) {
stage.isAlwaysOnTop = stayOnTopMenuItem.isSelected
Application.stayOnTop.save(stayOnTopMenuItem.isSelected)
}
@FXML fun exit(event: ActionEvent) {
Platform.exit()
}
fun update(@Observes event: TreeUpdateRequest) {
bookView.refresh()
}
fun afterExit(@Observes event: Exit) {
trayIcon?.let { icon ->
java.awt.SystemTray.getSystemTray().remove(icon)
}
}
} | src/main/kotlin/com/github/windchopper/tools/password/drop/ui/MainController.kt | 3982294763 |
import kotlin.test.*
fun box() {
val data = hashMapOf<String, Int>()
assertTrue { data.none() }
assertEquals(data.size, 0)
}
| backend.native/tests/external/stdlib/collections/MapTest/sizeAndEmpty.kt | 3650070103 |
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlinx.cinterop
import konan.internal.ExportForCppRuntime
// TODO: it it actually not related to cinterop.
@ExportTypeInfo("theNSArrayListTypeInfo")
internal class NSArrayList : AbstractList<Any?> {
// FIXME: override methods of Any.
@konan.internal.ExportForCppRuntime("Kotlin_NSArrayList_constructor")
constructor() : super()
override val size: Int get() = getSize()
@SymbolName("Kotlin_NSArrayList_getSize")
private external fun getSize(): Int
@SymbolName("Kotlin_NSArrayList_getElement")
external override fun get(index: Int): Any?
}
@ExportForCppRuntime private fun Kotlin_List_get(list: List<*>, index: Int): Any? = list.get(index)
@ExportForCppRuntime private fun Kotlin_List_getSize(list: List<*>): Int = list.size
| Interop/Runtime/src/native/kotlin/kotlinx/cinterop/ObjectiveCExportImpl.kt | 2421038036 |
/*
* Copyright (c) 2015 Andre Tietz
*
* 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.andretietz.retroauth
import android.accounts.AbstractAccountAuthenticator
import android.accounts.Account
import android.accounts.AccountAuthenticatorResponse
import android.accounts.AccountManager
import android.accounts.NetworkErrorException
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
/**
* This AccountAuthenticator is a very basic implementation of Android's
* [AbstractAccountAuthenticator]. This implementation is intentional as empty as it is. Cause of this is, that
* it's executed in a different process, which makes it difficult to provide login endpoints from
* the app process in here.
*
* NOTE: This class cannot be replaced with a kotlin version yet, since Android cannot load Authenticators
* that are non java once
*/
class AccountAuthenticator(
context: Context,
internal val action: String,
private val cleanupUserData: (account: Account) -> Unit
) : AbstractAccountAuthenticator(context) {
override fun addAccount(
response: AccountAuthenticatorResponse,
accountType: String,
authCredentialType: String?,
requiredFeatures: Array<String>?,
options: Bundle
) = createAuthBundle(response, action, accountType, authCredentialType, null)
override fun getAuthToken(
response: AccountAuthenticatorResponse,
account: Account,
authTokenType: String,
options: Bundle
) = createAuthBundle(response, action, account.type, authTokenType, account.name)
/**
* Creates an Intent to open the Activity to login.
*
* @param response needed parameter
* @param accountType The account Type
* @param credentialType The requested credential-type
* @param accountName The name of the account
* @return a bundle to open the activity
*/
private fun createAuthBundle(
response: AccountAuthenticatorResponse,
action: String,
accountType: String,
credentialType: String?,
accountName: String?
): Bundle? = Bundle().apply {
putParcelable(
AccountManager.KEY_INTENT,
Intent(action).apply {
putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response)
putExtra(AccountManager.KEY_ACCOUNT_TYPE, accountType)
putExtra(KEY_CREDENTIAL_TYPE, credentialType)
accountName?.let {
putExtra(AccountManager.KEY_ACCOUNT_NAME, it)
}
})
}
override fun confirmCredentials(
response: AccountAuthenticatorResponse,
account: Account,
options: Bundle?
) = null
override fun editProperties(response: AccountAuthenticatorResponse, accountType: String) = null
override fun getAuthTokenLabel(authCredentialType: String) = null
override fun updateCredentials(
response: AccountAuthenticatorResponse,
account: Account,
authCredentialType: String,
options: Bundle
): Bundle? = null
override fun hasFeatures(
response: AccountAuthenticatorResponse,
account: Account,
features: Array<String>
) = null
@SuppressLint("CheckResult")
@Throws(NetworkErrorException::class)
override fun getAccountRemovalAllowed(response: AccountAuthenticatorResponse, account: Account): Bundle? {
val result = super.getAccountRemovalAllowed(response, account)
if (
result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT) &&
result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
try {
cleanupUserData(account)
} catch (exception: Exception) {
Log.w("AuthenticationService", "Your cleanup method threw an exception:", exception)
}
}
return result
}
companion object {
internal const val KEY_CREDENTIAL_TYPE = "account_credential_type"
}
}
| retroauth-android/src/main/java/com/andretietz/retroauth/AccountAuthenticator.kt | 1723230711 |
actual typealias <!LINE_MARKER("descr='Has declaration in common module'")!>Expect<!> = String
interface Derived : Base {
override fun <!LINE_MARKER("descr='Overrides function in 'Base''")!>expectInReturnType<!>(): Expect
override fun <!LINE_MARKER("descr='Overrides function in 'Base''")!>expectInArgument<!>(e: Expect)
override fun Expect.<!LINE_MARKER("descr='Overrides function in 'Base''")!>expectInReceiver<!>()
override val <!LINE_MARKER("descr='Overrides property in 'Base''")!>expectVal<!>: Expect
override var <!LINE_MARKER("descr='Overrides property in 'Base''")!>expectVar<!>: Expect
}
| plugins/kotlin/idea/tests/testData/multiplatform/overrideExpect/jvm/jvm.kt | 505100014 |
fun mainUsage(m: Main) {
m.prop
} | plugins/kotlin/refIndex/tests/testData/compilerIndex/properties/constructorParameter/hierarchy/MainUsage.kt | 1792955013 |
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.fir.low.level.api.api
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.fir.FirElement
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.fir.declarations.builder.buildPropertyAccessorCopy
import org.jetbrains.kotlin.fir.declarations.builder.buildPropertyCopy
import org.jetbrains.kotlin.fir.declarations.builder.buildSimpleFunctionCopy
import org.jetbrains.kotlin.fir.expressions.FirReturnExpression
import org.jetbrains.kotlin.fir.resolve.FirTowerDataContext
import org.jetbrains.kotlin.fir.symbols.impl.FirNamedFunctionSymbol
import org.jetbrains.kotlin.fir.visitors.FirVisitorVoid
import org.jetbrains.kotlin.idea.fir.low.level.api.FirModuleResolveStateForCompletion
import org.jetbrains.kotlin.idea.fir.low.level.api.FirModuleResolveStateImpl
import org.jetbrains.kotlin.idea.fir.low.level.api.element.builder.FirTowerDataContextCollector
import org.jetbrains.kotlin.idea.fir.low.level.api.providers.FirIdeProvider
import org.jetbrains.kotlin.idea.fir.low.level.api.providers.firIdeProvider
import org.jetbrains.kotlin.idea.util.getElementTextInContext
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtProperty
object LowLevelFirApiFacadeForCompletion {
fun getResolveStateForCompletion(originalState: FirModuleResolveState): FirModuleResolveState {
check(originalState is FirModuleResolveStateImpl)
return FirModuleResolveStateForCompletion(originalState.project, originalState)
}
fun recordCompletionContextForFunction(
firFile: FirFile,
fakeElement: KtNamedFunction,
originalElement: KtNamedFunction,
state: FirModuleResolveState,
) {
val firIdeProvider = firFile.session.firIdeProvider
val originalFunction = state.getOrBuildFirFor(originalElement) as FirSimpleFunction
val copyFunction = buildFunctionCopyForCompletion(firIdeProvider, fakeElement, originalFunction, state)
state.lazyResolveDeclarationForCompletion(copyFunction, firFile, firIdeProvider, FirResolvePhase.BODY_RESOLVE)
state.recordPsiToFirMappingsForCompletionFrom(copyFunction, firFile, fakeElement.containingKtFile)
}
fun recordCompletionContextForProperty(
firFile: FirFile,
fakeElement: KtProperty,
originalElement: KtProperty,
state: FirModuleResolveState,
) {
val firIdeProvider = firFile.session.firIdeProvider
val originalProperty = state.getOrBuildFirFor(originalElement) as FirProperty
val copyProperty = buildPropertyCopyForCompletion(firIdeProvider, fakeElement, originalProperty, state)
state.lazyResolveDeclarationForCompletion(copyProperty, firFile, firIdeProvider, FirResolvePhase.BODY_RESOLVE)
state.recordPsiToFirMappingsForCompletionFrom(copyProperty, firFile, fakeElement.containingKtFile)
}
private fun buildFunctionCopyForCompletion(
firIdeProvider: FirIdeProvider,
element: KtNamedFunction,
originalFunction: FirSimpleFunction,
state: FirModuleResolveState
): FirSimpleFunction {
val builtFunction = firIdeProvider.buildFunctionWithBody(element, originalFunction)
// right now we can't resolve builtFunction header properly, as it built right in air,
// without file, which is now required for running stages other then body resolve, so we
// take original function header (which is resolved) and copy replacing body with body from builtFunction
return buildSimpleFunctionCopy(originalFunction) {
body = builtFunction.body
symbol = builtFunction.symbol as FirNamedFunctionSymbol
resolvePhase = minOf(originalFunction.resolvePhase, FirResolvePhase.DECLARATIONS)
source = builtFunction.source
session = state.rootModuleSession
}.apply { reassignAllReturnTargets (builtFunction) }
}
private fun buildPropertyCopyForCompletion(
firIdeProvider: FirIdeProvider,
element: KtProperty,
originalProperty: FirProperty,
state: FirModuleResolveState
): FirProperty {
val builtProperty = firIdeProvider.buildPropertyWithBody(element, originalProperty)
val originalSetter = originalProperty.setter
val builtSetter = builtProperty.setter
// setter has a header with `value` parameter, and we want it type to be resolved
val copySetter = if (originalSetter != null && builtSetter != null) {
buildPropertyAccessorCopy(originalSetter) {
body = builtSetter.body
symbol = builtSetter.symbol
resolvePhase = minOf(builtSetter.resolvePhase, FirResolvePhase.DECLARATIONS)
source = builtSetter.source
session = state.rootModuleSession
}.apply { reassignAllReturnTargets(builtSetter) }
} else {
builtSetter
}
return buildPropertyCopy(originalProperty) {
symbol = builtProperty.symbol
initializer = builtProperty.initializer
getter = builtProperty.getter
setter = copySetter
resolvePhase = minOf(originalProperty.resolvePhase, FirResolvePhase.DECLARATIONS)
source = builtProperty.source
session = state.rootModuleSession
}
}
private fun FirFunction<*>.reassignAllReturnTargets(from: FirFunction<*>) {
this.accept(object : FirVisitorVoid() {
override fun visitElement(element: FirElement) {
if (element is FirReturnExpression && element.target.labeledElement == from) {
element.target.bind(this@reassignAllReturnTargets)
}
element.acceptChildren(this)
}
})
}
}
| plugins/kotlin/fir-low-level-api/src/org/jetbrains/kotlin/idea/fir/low/level/api/api/LowLevelFirApiFacadeForCompletion.kt | 2400664860 |
// "Replace with assignment (original is empty)" "false"
// TOOL: org.jetbrains.kotlin.idea.inspections.SuspiciousCollectionReassignmentInspection
// ACTION: Change type to mutable
// ACTION: Replace overloaded operator with function call
// ACTION: Replace with ordinary assignment
// WITH_STDLIB
fun test(otherList: Set<Int>) {
var list = setOf<Int>(1, 2, 3)
foo()
bar()
list <caret>+= otherList
}
fun foo() {}
fun bar() {} | plugins/kotlin/idea/tests/testData/quickfix/suspiciousCollectionReassignment/replaceWithAssignment/setOf.kt | 3440349887 |
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtClass
// OPTIONS: derivedInterfaces
open class B : A() {
}
open class C : Y {
}
open class Z : A() {
}
open class U : Z() {
}
interface D : Y {}
| plugins/kotlin/idea/tests/testData/findUsages/kotlin/findClassUsages/kotlinInterfaceDerivedInterfaces.1.kt | 1374343799 |
fun test(b: Boolean): Int {
loop@ while (true) {
<caret>return when (b) {
true -> 1
else -> break@loop
}
}
return 0
} | plugins/kotlin/idea/tests/testData/intentions/branched/unfolding/returnToWhen/whenWithBreak.kt | 4136873871 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.codeInsight.testIntegration
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.search.FilenameIndex
import com.intellij.psi.util.PsiTreeUtil
import com.jetbrains.python.codeInsight.testIntegration.PyTestCreationModel.Companion.createByElement
import com.jetbrains.python.psi.PyClass
import com.jetbrains.python.psi.PyFile
import com.jetbrains.python.psi.PyFunction
import com.jetbrains.python.testing.PythonUnitTestDetectorsBasedOnSettings
/**
* Created with [createByElement], then modified my user and provided to [PyTestCreator.createTest] to create test
*/
class PyTestCreationModel(var fileName: String,
var targetDir: String,
var className: String,
var methods: List<String>) {
init {
assert(className.isNotEmpty() || methods.isNotEmpty()) { "Either class or at least one method must be provided" }
}
companion object {
private val String.asFunName
get():String {
return replace(Regex("([a-z])([A-Z])"), "$1_$2").toLowerCase()
}
/**
* @return model of null if no test could be created for this element
*/
fun createByElement(element: PsiElement): PyTestCreationModel? {
if (PythonUnitTestDetectorsBasedOnSettings.isTestElement(element, null)) return null //Can't create tests for tests
val fileUnderTest = element.containingFile as? PyFile ?: return null
val classUnderTest = PsiTreeUtil.getParentOfType(element, PyClass::class.java, false)
val functionUnderTest = PsiTreeUtil.getParentOfType(element, PyFunction::class.java, false)
val elementsUnderTest: Sequence<PsiNamedElement> = when {
functionUnderTest != null -> listOf(functionUnderTest)
classUnderTest != null -> classUnderTest.methods.asList()
else -> (fileUnderTest.topLevelFunctions + fileUnderTest.topLevelClasses)
}.asSequence().filterIsInstance<PsiNamedElement>().filterNot { PythonUnitTestDetectorsBasedOnSettings.isTestElement(it, null) }
/**
* [PyTestCreationModel] has optional field "class" and list of methods.
* For unitTest we need "class" field to filled by test name.
* For pytest we may leave it empty, but we need at least one method.
*/
val testFunctionNames = elementsUnderTest
.mapNotNull { it.name }
.filterNot { it.startsWith("__") }
.map { "test_${it.asFunName}" }.toMutableList()
val nameOfClassUnderTest = classUnderTest?.name
// True for unitTest
val testCaseClassRequired = PythonUnitTestDetectorsBasedOnSettings.isTestCaseClassRequired(fileUnderTest)
if (testFunctionNames.isEmpty()) {
when {
// No class, no function, what to generate?
classUnderTest == null -> return null
// For UnitTest we can generate test class. For pytest we need at least one function
!testCaseClassRequired -> testFunctionNames.add("test_" + (nameOfClassUnderTest?.asFunName ?: "fun"))
}
}
return PyTestCreationModel(fileName = "test_${fileUnderTest.name}",
targetDir = getTestFolder(element).path,
className = if (testCaseClassRequired) "Test${nameOfClassUnderTest ?: ""}" else "",
methods = testFunctionNames)
}
private fun getTestFolder(element: PsiElement): VirtualFile =
ModuleUtil.findModuleForPsiElement(element)?.let { module ->
// No need to create tests in site-packages (aka classes root)
val fileIndex = ProjectFileIndex.getInstance(element.project)
return@let FilenameIndex.getVirtualFilesByName("tests", module.moduleContentScope).firstOrNull { possibleRoot ->
possibleRoot.isDirectory && !fileIndex.isInLibrary(possibleRoot)
}
} ?: element.containingFile.containingDirectory.virtualFile
}
}
| python/src/com/jetbrains/python/codeInsight/testIntegration/PyTestCreationModel.kt | 2691776466 |
package pl.droidsonroids.droidsmap.feature.room.api
import io.reactivex.Observable
import pl.droidsonroids.droidsmap.feature.room.business_logic.RoomEntityHolder
interface RoomDataEndpoint {
fun getRoomData(): Observable<RoomEntityHolder>
companion object {
fun create(): RoomDataEndpoint {
return RoomDataInteractor()
}
}
} | app/src/main/java/pl/droidsonroids/droidsmap/feature/room/api/RoomDataEndpoint.kt | 3128321826 |
package com.example.testModule15
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.example.common.anotherSampleTestMethod
import com.example.common.ignoredTest
import com.example.common.testSampleMethod
import org.junit.Ignore
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class ModuleTests2 {
@Test
fun sampleTestModule15AdvancedTest() {
testSampleMethod()
anotherSampleTestMethod()
}
@Test
fun sampleTestModule15AdvancedTest2() {
anotherSampleTestMethod()
testSampleMethod()
}
@Test
@Ignore("For testing #818")
fun sampleIgnoredTest3() {
ignoredTest()
}
}
| test_projects/android/multi-modules/testModule15/src/androidTest/java/com/example/testModule15/ModuleTests2.kt | 2073764783 |
package technology.mainthread.apps.gatekeeper.data
const val DOOR_OPENED = "door-opened"
const val DOOR_CLOSED = "door-closed"
const val HANDSET_ACTIVATED = "handset-activated"
const val HANDSET_DEACTIVATED = "handset-deactivated"
const val PRIMED = "primed"
const val UNPRIMED = "unprimed"
const val UNLOCKED = "unlocked"
| mobile/src/main/java/technology/mainthread/apps/gatekeeper/data/FCMTopics.kt | 394865497 |
package com.cout970.modeler.core.export.project
import com.cout970.modeler.api.animation.IAnimation
import com.cout970.modeler.api.animation.InterpolationMethod
import com.cout970.modeler.api.model.IModel
import com.cout970.modeler.api.model.ITransformation
import com.cout970.modeler.api.model.`object`.*
import com.cout970.modeler.api.model.material.IMaterial
import com.cout970.modeler.api.model.material.IMaterialRef
import com.cout970.modeler.api.model.mesh.IMesh
import com.cout970.modeler.api.model.selection.IObjectRef
import com.cout970.modeler.core.animation.Animation
import com.cout970.modeler.core.animation.Channel
import com.cout970.modeler.core.animation.Keyframe
import com.cout970.modeler.core.animation.ref
import com.cout970.modeler.core.export.*
import com.cout970.modeler.core.model.Model
import com.cout970.modeler.core.model.`object`.*
import com.cout970.modeler.core.model.material.ColoredMaterial
import com.cout970.modeler.core.model.material.MaterialNone
import com.cout970.modeler.core.model.material.TexturedMaterial
import com.cout970.modeler.core.model.mesh.FaceIndex
import com.cout970.modeler.core.model.mesh.Mesh
import com.cout970.modeler.core.model.toImmutable
import com.cout970.modeler.core.project.ProjectProperties
import com.cout970.modeler.core.resource.ResourcePath
import com.cout970.vector.api.IQuaternion
import com.cout970.vector.api.IVector2
import com.cout970.vector.api.IVector3
import com.google.gson.*
import kotlinx.collections.immutable.ImmutableMap
import kotlinx.collections.immutable.toImmutableMap
import java.lang.reflect.Type
import java.net.URI
import java.util.*
import java.util.zip.ZipFile
object ProjectLoaderV12 {
const val VERSION = "1.2"
val gson = GsonBuilder()
.setExclusionStrategies(ProjectExclusionStrategy())
.setPrettyPrinting()
.enableComplexMapKeySerialization()
.registerTypeAdapter(UUID::class.java, UUIDSerializer())
.registerTypeAdapter(IVector3::class.java, Vector3Serializer())
.registerTypeAdapter(IVector2::class.java, Vector2Serializer())
.registerTypeAdapter(IQuaternion::class.java, QuaternionSerializer())
.registerTypeAdapter(IGroupRef::class.java, GroupRefSerializer())
.registerTypeAdapter(IMaterialRef::class.java, MaterialRefSerializer())
.registerTypeAdapter(IObjectRef::class.java, ObjectRefSerializer())
.registerTypeAdapter(ITransformation::class.java, TransformationSerializer())
.registerTypeAdapter(BiMultimap::class.java, BiMultimapSerializer())
.registerTypeAdapter(ImmutableMap::class.java, ImmutableMapSerializer())
.registerTypeAdapter(IModel::class.java, ModelSerializer())
.registerTypeAdapter(IMaterial::class.java, MaterialSerializer())
.registerTypeAdapter(IObject::class.java, ObjectSerializer())
.registerTypeAdapter(IGroupTree::class.java, GroupTreeSerializer())
.registerTypeAdapter(IGroup::class.java, serializerOf<Group>())
.registerTypeAdapter(IMesh::class.java, MeshSerializer())
.registerTypeAdapter(IAnimation::class.java, AnimationSerializer())
.create()!!
fun loadProject(zip: ZipFile, path: String): ProgramSave {
val properties = zip.load<ProjectProperties>("project.json", gson)
?: throw IllegalStateException("Missing file 'project.json' inside '$path'")
val model = zip.load<IModel>("model.json", gson)
?: throw IllegalStateException("Missing file 'model.json' inside '$path'")
val animation = zip.load<IAnimation>("animation.json", gson)
?: throw IllegalStateException("Missing file 'animation.json' inside '$path'")
checkIntegrity(listOf(model.objectMap, model.materialMap, model.groupMap, model.tree))
checkIntegrity(listOf(animation))
return ProgramSave(VERSION, properties, model.addAnimation(animation), emptyList())
}
class ModelSerializer : JsonDeserializer<IModel> {
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): IModel {
val obj = json.asJsonObject
val objects: Map<IObjectRef, IObject> = context.deserializeT(obj["objectMap"])
return Model.of(
objectMap = objects,
materialMap = context.deserializeT(obj["materialMap"]),
groupMap = context.deserializeT(obj["groupMap"]),
groupTree = MutableGroupTree(RootGroupRef, objects.keys.toMutableList()).toImmutable()
)
}
}
class MaterialSerializer : JsonDeserializer<IMaterial> {
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): IMaterial {
val obj = json.asJsonObject
if (obj.has("type")) {
return when (obj["type"].asString) {
"texture" -> {
val id = context.deserialize<UUID>(obj["id"], UUID::class.java)
TexturedMaterial(obj["name"].asString, ResourcePath(URI(obj["path"].asString)), id)
}
"color" -> {
val id = context.deserialize<UUID>(obj["id"], UUID::class.java)
ColoredMaterial(obj["name"].asString, context.deserializeT(obj["color"]), id)
}
else -> MaterialNone
}
}
return when {
obj["name"].asString == "noTexture" -> MaterialNone
else -> {
val id = context.deserialize<UUID>(obj["id"], UUID::class.java)
TexturedMaterial(obj["name"].asString, ResourcePath(URI(obj["path"].asString)), id)
}
}
}
}
class ObjectSerializer : JsonDeserializer<IObject> {
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): IObject {
val obj = json.asJsonObject
return when (obj["class"].asString) {
"ObjectCube" -> {
ObjectCube(
name = context.deserialize(obj["name"], String::class.java),
transformation = context.deserialize(obj["transformation"], ITransformation::class.java),
material = context.deserialize(obj["material"], IMaterialRef::class.java),
textureOffset = context.deserialize(obj["textureOffset"], IVector2::class.java),
textureSize = context.deserialize(obj["textureSize"], IVector2::class.java),
mirrored = context.deserialize(obj["mirrored"], Boolean::class.java),
visible = context.deserialize(obj["visible"], Boolean::class.java),
id = context.deserialize(obj["id"], UUID::class.java)
)
}
"Object" -> Object(
name = context.deserialize(obj["name"], String::class.java),
mesh = context.deserialize(obj["mesh"], IMesh::class.java),
material = context.deserialize(obj["material"], IMaterialRef::class.java),
visible = context.deserialize(obj["visible"], Boolean::class.java),
id = context.deserialize(obj["id"], UUID::class.java)
)
else -> throw IllegalStateException("Unknown Class: ${obj["class"]}")
}
}
}
class GroupTreeSerializer : JsonSerializer<IGroupTree>, JsonDeserializer<IGroupTree> {
data class Aux(val key: IGroupRef, val value: Set<IGroupRef>)
data class Aux2(val key: IGroupRef, val value: IGroupRef)
override fun serialize(src: IGroupTree, typeOfSrc: Type, context: JsonSerializationContext): JsonElement {
val tree = src as GroupTree
return JsonObject().apply {
add("childMap", JsonArray().also { array ->
tree.childMap.map { Aux(it.key, it.value) }.map { context.serializeT(it) }.forEach { it -> array.add(it) }
})
add("parentMap", JsonArray().also { array ->
tree.parentMap.map { Aux2(it.key, it.value) }.map { context.serializeT(it) }.forEach { it -> array.add(it) }
})
}
}
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): IGroupTree {
if (json.isJsonNull) return GroupTree.emptyTree()
val obj = json.asJsonObject
val childMapArray = obj["childMap"].asJsonArray
val parentMapArray = obj["parentMap"].asJsonArray
val childMap = childMapArray
.map { context.deserialize(it, Aux::class.java) as Aux }
.map { it.key to it.value }
.toMap()
.toImmutableMap()
val parentMap = parentMapArray
.map { context.deserialize(it, Aux2::class.java) as Aux2 }
.map { it.key to it.value }
.toMap()
.toImmutableMap()
return GroupTree(parentMap, childMap)
}
}
class MeshSerializer : JsonSerializer<IMesh>, JsonDeserializer<IMesh> {
override fun serialize(src: IMesh, typeOfSrc: Type?, context: JsonSerializationContext): JsonElement {
val pos = context.serializeT(src.pos)
val tex = context.serializeT(src.tex)
val faces = JsonArray().apply {
src.faces.forEach { face ->
add(JsonArray().apply {
repeat(face.vertexCount) {
add(JsonArray().apply {
add(face.pos[it]); add(face.tex[it])
})
}
})
}
}
return JsonObject().apply {
add("pos", pos)
add("tex", tex)
add("faces", faces)
}
}
override fun deserialize(json: JsonElement, typeOfT: Type?, context: JsonDeserializationContext): IMesh {
val obj = json.asJsonObject
val pos = context.deserializeT<List<IVector3>>(obj["pos"])
val tex = context.deserializeT<List<IVector2>>(obj["tex"])
val faces = obj["faces"].asJsonArray.map { face ->
val vertex = face.asJsonArray
val posIndices = ArrayList<Int>(vertex.size())
val texIndices = ArrayList<Int>(vertex.size())
repeat(vertex.size()) {
val pair = vertex[it].asJsonArray
posIndices.add(pair[0].asInt)
texIndices.add(pair[1].asInt)
}
FaceIndex.from(posIndices, texIndices)
}
return Mesh(pos, tex, faces)
}
}
class AnimationSerializer : JsonDeserializer<IAnimation> {
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): IAnimation {
if (json.isJsonNull) return Animation.of()
val obj = json.asJsonObject
val channelsObj = obj["channels"]
val channels = if (!channelsObj.isJsonArray) emptyList() else channelsObj.asJsonArray.map { it ->
val channel = it.asJsonObject
val interName = channel["interpolation"].asString
val keyframesJson = channel["keyframes"].asJsonArray
val keyframes = keyframesJson.map { it.asJsonObject }.map {
Keyframe(
time = it["time"].asFloat,
value = context.deserializeT(it["value"])
)
}
Channel(
name = channel["name"].asString,
interpolation = InterpolationMethod.valueOf(interName),
enabled = channel["enabled"].asBoolean,
keyframes = keyframes,
id = context.deserializeT(channel["id"])
)
}
return Animation(
channels = channels.associateBy { it.ref },
timeLength = obj["timeLength"].asFloat,
channelMapping = emptyMap(),
name = "animation"
)
}
}
class BiMultimapSerializer : JsonDeserializer<BiMultimap<IGroupRef, IObjectRef>> {
data class Aux(val key: IGroupRef, val value: List<IObjectRef>)
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): BiMultimap<IGroupRef, IObjectRef> {
if (json.isJsonNull || (json.isJsonArray && json.asJsonArray.size() == 0))
return emptyBiMultimap()
val array = json.asJsonArray
val list = array.map { context.deserialize(it, Aux::class.java) as Aux }
return biMultimapOf(*list.map { it.key to it.value }.toTypedArray())
}
}
} | src/main/kotlin/com/cout970/modeler/core/export/project/ProjectLoaderV12.kt | 4084604040 |
package org.telegram.tl.builder
import java.util.ArrayList
import java.io.File
import java.nio.charset.Charset
import java.util.HashMap
/**
* Created with IntelliJ IDEA.
* User: ex3ndr
* Date: 23.10.13
* Time: 13:09
*/
fun convertToJavaModel(model: TLModel): JavaModel
{
var javaTypes = HashMap<String, JavaTypeObject>()
for (t in model.types)
{
if (t is TLCombinedTypeDef)
{
var combinedType = t as TLCombinedTypeDef
javaTypes.put(combinedType.name, JavaTypeObject(combinedType))
}
}
var javaMethods = ArrayList<JavaRpcMethod>()
for (t in model.methods) {
javaMethods.add(JavaRpcMethod(t))
}
for (t in javaTypes.values())
{
for (p in t.commonParameters)
{
p.reference = mapReference(javaTypes, p.tlParameterDef.typeDef)
}
for (c in t.constructors)
{
for (p in c.parameters)
{
p.reference = mapReference(javaTypes, p.tlParameterDef.typeDef)
}
}
}
for (m in javaMethods)
{
m.returnReference = mapReference(javaTypes, m.tlMethod.returnType)
for (p in m.parameters)
{
p.reference = mapReference(javaTypes, p.tlParameterDef.typeDef)
}
}
return JavaModel(javaTypes, javaMethods)
}
fun mapReference(javaTypes: HashMap<String, JavaTypeObject>, tlType: TLTypeDef): JavaTypeReference
{
return if (tlType is TLCombinedTypeDef) {
JavaTypeTlReference(tlType, javaTypes.get((tlType as TLCombinedTypeDef).name)!!);
} else if (tlType is TLBuiltInTypeDef)
{
JavaTypeBuiltInReference(tlType);
} else if (tlType is TLBuiltInGenericTypeDef)
{
var generic = tlType as TLBuiltInGenericTypeDef
if (generic.name != "Vector")
{
throw RuntimeException("Only Vector built-in generics are supported")
}
JavaTypeVectorReference(tlType, mapReference(javaTypes, (tlType as TLBuiltInGenericTypeDef).basic));
}
else if (tlType is TLBuiltInTypeDef)
{
JavaTypeBuiltInReference(tlType)
}
else if (tlType is TLAnyTypeDef) {
JavaTypeAnyReference(tlType)
}
else if (tlType is TLFunctionalTypeDef) {
JavaTypeFunctionalReference(tlType)
}
else {
JavaTypeUnknownReference(tlType)
}
}
fun buildSerializer(parameters: List<JavaParameter>): String
{
if (parameters.size() == 0)
{
return ""
}
var serializer = "";
for (p in parameters)
{
if (p.reference is JavaTypeTlReference)
{
serializer += JavaSerializeObject.replace("{int}", p.internalName);
}
else if (p.reference is JavaTypeVectorReference)
{
serializer += JavaSerializeVector.replace("{int}", p.internalName);
} else if (p.reference is JavaTypeBuiltInReference)
{
if (p.tlParameterDef.typeDef.name == "int")
{
serializer += JavaSerializeInt.replace("{int}", p.internalName);
} else if (p.tlParameterDef.typeDef.name == "Bool")
{
serializer += JavaSerializeBoolean.replace("{int}", p.internalName);
} else if (p.tlParameterDef.typeDef.name == "long")
{
serializer += JavaSerializeLong.replace("{int}", p.internalName);
} else if (p.tlParameterDef.typeDef.name == "double")
{
serializer += JavaSerializeDouble.replace("{int}", p.internalName);
} else if (p.tlParameterDef.typeDef.name == "string")
{
serializer += JavaSerializeString.replace("{int}", p.internalName);
} else if (p.tlParameterDef.typeDef.name == "bytes")
{
serializer += JavaSerializeBytes.replace("{int}", p.internalName);
} else throw RuntimeException("Unknown internal type: " + p.tlParameterDef.typeDef.name)
} else if (p.reference is JavaTypeFunctionalReference) {
serializer += JavaSerializeFunctional.replace("{int}", p.internalName);
} else if (p.reference is JavaTypeAnyReference) {
serializer += JavaSerializeObject.replace("{int}", p.internalName);
}
else
{
throw RuntimeException("Unknown type: " + p.tlParameterDef.typeDef.name)
}
}
return JavaSerializeTemplate.replace("{body}", serializer)
}
fun buildDeserializer(parameters: List<JavaParameter>): String
{
if (parameters.size() == 0)
{
return ""
}
var serializer = "";
for (p in parameters)
{
if (p.reference is JavaTypeTlReference)
{
serializer += JavaDeserializeObject.replace("{int}", p.internalName)
.replace("{type}", (p.reference as JavaTypeTlReference).javaName);
}
else if (p.reference is JavaTypeVectorReference)
{
if ((p.reference as JavaTypeVectorReference).internalReference is JavaTypeBuiltInReference)
{
var intReference = (p.reference as JavaTypeVectorReference).internalReference as JavaTypeBuiltInReference;
if (intReference.javaName == "int")
{
serializer += JavaDeserializeIntVector.replace("{int}", p.internalName);
} else if (intReference.javaName == "long")
{
serializer += JavaDeserializeLongVector.replace("{int}", p.internalName);
}
else if (intReference.javaName == "String")
{
serializer += JavaDeserializeStringVector.replace("{int}", p.internalName);
}
else {
serializer += JavaDeserializeVector.replace("{int}", p.internalName);
}
}
else {
serializer += JavaDeserializeVector.replace("{int}", p.internalName);
}
} else if (p.reference is JavaTypeBuiltInReference)
{
if (p.tlParameterDef.typeDef.name == "int")
{
serializer += JavaDeserializeInt.replace("{int}", p.internalName);
} else if (p.tlParameterDef.typeDef.name == "Bool")
{
serializer += JavaDeserializeBoolean.replace("{int}", p.internalName);
} else if (p.tlParameterDef.typeDef.name == "long")
{
serializer += JavaDeserializeLong.replace("{int}", p.internalName);
} else if (p.tlParameterDef.typeDef.name == "double")
{
serializer += JavaDeserializeDouble.replace("{int}", p.internalName);
} else if (p.tlParameterDef.typeDef.name == "string")
{
serializer += JavaDeserializeString.replace("{int}", p.internalName);
} else if (p.tlParameterDef.typeDef.name == "bytes")
{
serializer += JavaDeserializeBytes.replace("{int}", p.internalName);
} else throw RuntimeException("Unknown internal type: " + p.tlParameterDef.typeDef.name)
}
else if (p.reference is JavaTypeFunctionalReference) {
serializer += JavaDeserializeFunctional.replace("{int}", p.internalName);
} else if (p.reference is JavaTypeAnyReference) {
serializer += JavaDeserializeObject.replace("{int}", p.internalName)
.replace("{type}", "TLObject");
}
else
{
throw RuntimeException("Unknown type: " + p.tlParameterDef.typeDef.name)
}
}
return JavaDeserializeTemplate.replace("{body}", serializer)
}
fun writeJavaClasses(model: JavaModel, path: String)
{
for (t in model.types.values()) {
if (t.constructors.size == 1 && !IgnoreUniting.any {(x) -> x == t.tlType.name })
{
var generatedFile = JavaClassTemplate;
generatedFile = generatedFile
.replace("{name}", t.javaTypeName)
.replace("{package}", t.javaPackage)
.replace("{class_id}", "0x" + Integer.toHexString(t.constructors.first!!.tlConstructor.id))
.replace("{to_string}",
JavaToStringTemplate.replace("{value}", t.constructors.first!!.tlConstructor.name + "#" + Integer.toHexString(t.constructors.first!!.tlConstructor.id)));
var fields = "";
for (p in t.constructors.get(0).parameters)
{
fields += JavaFieldTemplate
.replace("{type}", p.reference!!.javaName)
.replace("{int}", p.internalName)
}
generatedFile = generatedFile.replace("{fields}", fields)
var getterSetter = "";
for (p in t.constructors.get(0).parameters)
{
getterSetter += JavaGetterSetterTemplate
.replace("{type}", p.reference!!.javaName)
.replace("{int}", p.internalName)
.replace("{getter}", p.getterName)
.replace("{setter}", p.setterName)
}
if (t.constructors.get(0).parameters.size > 0)
{
var constructorArgs = "";
var constructorBody = "";
for (p in t.constructors.get(0).parameters)
{
if (constructorArgs != "") {
constructorArgs += ", ";
}
constructorArgs += JavaConstructorArgTemplate
.replace("{type}", p.reference!!.javaName)
.replace("{int}", p.internalName)
constructorBody += JavaConstructorBodyTemplate
.replace("{type}", p.reference!!.javaName)
.replace("{int}", p.internalName) + "\n";
}
generatedFile = generatedFile.replace("{constructor}",
JavaConstructorTemplate
.replace("{name}", t.javaTypeName)
.replace("{args}", constructorArgs)
.replace("{body}", constructorBody))
}
else {
generatedFile = generatedFile.replace("{constructor}", "")
}
generatedFile = generatedFile.replace("{getter-setters}", getterSetter)
generatedFile = generatedFile.replace("{serialize}", buildSerializer(t.constructors.get(0).parameters))
generatedFile = generatedFile.replace("{deserialize}", buildDeserializer(t.constructors.get(0).parameters))
var directory = t.javaPackage.split('.').fold(path, {(x, t) -> x + "/" + t });
val destFile = File(directory + "/" + t.javaTypeName + ".java");
File(directory).mkdirs()
destFile.writeText(generatedFile, "utf-8")
} else {
var directory = t.javaPackage.split('.').fold(path, {(x, t) -> x + "/" + t });
run {
var generatedFile = JavaAbsClassTemplate;
generatedFile = generatedFile
.replace("{name}", t.javaTypeName)
.replace("{package}", t.javaPackage);
var fields = "";
for (p in t.commonParameters)
{
fields += JavaFieldTemplate
.replace("{type}", p.reference!!.javaName)
.replace("{int}", p.internalName)
}
generatedFile = generatedFile.replace("{fields}", fields)
var getterSetter = "";
for (p in t.commonParameters)
{
getterSetter += JavaGetterSetterTemplate
.replace("{type}", p.reference!!.javaName)
.replace("{int}", p.internalName)
.replace("{getter}", p.getterName)
.replace("{setter}", p.setterName)
}
generatedFile = generatedFile.replace("{getter-setters}", getterSetter)
val destFile = File(directory + "/" + t.javaTypeName + ".java");
File(directory).mkdirs()
destFile.writeText(generatedFile, "utf-8")
}
for (constr in t.constructors)
{
var generatedFile = JavaChildClassTemplate;
generatedFile = generatedFile
.replace("{name}", constr.javaClassName)
.replace("{base-name}", t.javaTypeName)
.replace("{package}", t.javaPackage)
.replace("{class_id}", "0x" + Integer.toHexString(constr.tlConstructor.id))
.replace("{to_string}",
JavaToStringTemplate.replace("{value}", constr.tlConstructor.name + "#" + Integer.toHexString(constr.tlConstructor.id)));
var fields = "";
for (p in constr.parameters)
{
if (t.commonParameters.any {(x) -> x.internalName == p.internalName })
{
continue
}
fields += JavaFieldTemplate
.replace("{type}", p.reference!!.javaName)
.replace("{int}", p.internalName)
}
generatedFile = generatedFile.replace("{fields}", fields)
var getterSetter = "";
for (p in constr.parameters)
{
if (t.commonParameters.any {(x) -> x.internalName == p.internalName })
{
continue
}
getterSetter += JavaGetterSetterTemplate
.replace("{type}", p.reference!!.javaName)
.replace("{int}", p.internalName)
.replace("{getter}", p.getterName)
.replace("{setter}", p.setterName)
}
if (constr.parameters.size > 0)
{
var constructorArgs = "";
var constructorBody = "";
for (p in constr.parameters)
{
if (constructorArgs != "") {
constructorArgs += ", ";
}
constructorArgs += JavaConstructorArgTemplate
.replace("{type}", p.reference!!.javaName)
.replace("{int}", p.internalName)
constructorBody += JavaConstructorBodyTemplate
.replace("{type}", p.reference!!.javaName)
.replace("{int}", p.internalName) + "\n";
}
var constructor = JavaConstructorTemplate
.replace("{name}", constr.javaClassName)
.replace("{args}", constructorArgs)
.replace("{body}", constructorBody);
generatedFile = generatedFile.replace("{constructor}", constructor)
} else {
generatedFile = generatedFile.replace("{constructor}", "")
}
generatedFile = generatedFile.replace("{getter-setters}", getterSetter)
generatedFile = generatedFile.replace("{serialize}", buildSerializer(constr.parameters))
generatedFile = generatedFile.replace("{deserialize}", buildDeserializer(constr.parameters))
val destFile = File(directory + "/" + constr.javaClassName + ".java");
File(directory).mkdirs()
destFile.writeText(generatedFile, "utf-8")
}
}
}
for (m in model.methods)
{
var generatedFile = JavaMethodTemplate;
var returnTypeName = m.returnReference!!.javaName;
if (returnTypeName == "boolean") {
returnTypeName = "org.telegram.tl.TLBool"
}
generatedFile = generatedFile
.replace("{name}", m.requestClassName)
.replace("{package}", JavaPackage + "." + JavaMethodPackage)
.replace("{class_id}", "0x" + Integer.toHexString(m.tlMethod.id))
.replace("{return_type}", returnTypeName)
.replace("{to_string}",
JavaToStringTemplate.replace("{value}", m.tlMethod.name + "#" + Integer.toHexString(m.tlMethod.id)));
var fields = "";
for (p in m.parameters)
{
fields += JavaFieldTemplate
.replace("{type}", p.reference!!.javaName)
.replace("{int}", p.internalName)
}
generatedFile = generatedFile.replace("{fields}", fields)
var getterSetter = "";
for (p in m.parameters)
{
getterSetter += JavaGetterSetterTemplate
.replace("{type}", p.reference!!.javaName)
.replace("{int}", p.internalName)
.replace("{getter}", p.getterName)
.replace("{setter}", p.setterName)
}
if (m.parameters.size > 0)
{
var constructorArgs = "";
var constructorBody = "";
for (p in m.parameters)
{
if (constructorArgs != "") {
constructorArgs += ", ";
}
constructorArgs += JavaConstructorArgTemplate
.replace("{type}", p.reference!!.javaName)
.replace("{int}", p.internalName)
constructorBody += JavaConstructorBodyTemplate
.replace("{type}", p.reference!!.javaName)
.replace("{int}", p.internalName) + "\n";
}
var constructor = JavaConstructorTemplate
.replace("{name}", m.requestClassName)
.replace("{args}", constructorArgs)
.replace("{body}", constructorBody);
generatedFile = generatedFile.replace("{constructor}", constructor)
} else {
var constructor = JavaConstructorTemplate
.replace("{name}", m.requestClassName)
.replace("{args}", "")
.replace("{body}", "");
generatedFile = generatedFile.replace("{constructor}", constructor)
}
generatedFile = generatedFile.replace("{getter-setters}", getterSetter)
generatedFile = generatedFile.replace("{serialize}", buildSerializer(m.parameters))
generatedFile = generatedFile.replace("{deserialize}", buildDeserializer(m.parameters))
var responseParser = JavaMethodParserTemplate.replace("{return_type}",
returnTypeName);
if (m.returnReference is JavaTypeVectorReference) {
var vectorReference = m.returnReference as JavaTypeVectorReference;
if (vectorReference.internalReference is JavaTypeBuiltInReference) {
var intReference = vectorReference.internalReference as JavaTypeBuiltInReference;
if (intReference.javaName == "int") {
responseParser = responseParser.replace("{body}", JavaMethodParserBodyIntVector)
} else if (intReference.javaName == "long") {
responseParser = responseParser.replace("{body}", JavaMethodParserBodyLongVector)
}
else {
throw RuntimeException("Unsupported vector internal reference")
}
}
else if (vectorReference.internalReference is JavaTypeTlReference) {
var tlReference = vectorReference.internalReference as JavaTypeTlReference;
responseParser = responseParser.replace("{body}",
JavaMethodParserBodyVector.replace("{vector_type}", tlReference.javaName))
} else {
throw RuntimeException("Unsupported built-in reference")
}
}
else if (m.returnReference is JavaTypeTlReference) {
var returnReference = m.returnReference as JavaTypeTlReference;
responseParser = responseParser.replace("{body}",
JavaMethodParserBodyGeneral.replace("{return_type}", returnReference.javaName))
} else if (m.returnReference is JavaTypeBuiltInReference) {
var returnReference = m.returnReference as JavaTypeBuiltInReference;
if (returnReference.javaName != "boolean") {
throw RuntimeException("Only boolean built-in reference allowed as return")
}
responseParser = responseParser.replace("{body}",
JavaMethodParserBodyGeneral.replace("{return_type}", "org.telegram.tl.TLBool"))
}
else {
var functionalParameter: JavaParameter? = null
for (p in m.parameters)
{
if (p.reference is JavaTypeFunctionalReference) {
functionalParameter = p;
break
}
}
if (functionalParameter == null) {
throw RuntimeException("Any reference without functional reference: " + m.methodName)
}
// throw RuntimeException("Unsupported return reference")
responseParser = responseParser.replace("{body}",
JavaMethodParserBodyReference.replace("{return_type}", "TLObject")
.replace("{int}", functionalParameter!!.internalName))
}
generatedFile = generatedFile.replace("{responseParser}", responseParser)
var directory = (JavaPackage + "." + JavaMethodPackage).split('.').fold(path, {(x, t) -> x + "/" + t });
val destFile = File(directory + "/" + m.requestClassName + ".java");
File(directory).mkdirs()
destFile.writeText(generatedFile, "utf-8")
}
var requests = ""
for (m in model.methods) {
var args = "";
var methodArgs = "";
for (p in m.parameters) {
if (args != "") {
args += ", ";
}
if (methodArgs != "") {
methodArgs += ", ";
}
methodArgs += p.internalName;
args += p.reference!!.javaName + " " + p.internalName;
}
var returnTypeName = m.returnReference!!.javaName;
if (returnTypeName == "boolean")
{
returnTypeName = "TLBool";
}
requests += JavaRequesterMethod.replace("{return_type}", returnTypeName)
.replace("{method_name}", m.methodName)
.replace("{method_class}", m.requestClassName)
.replace("{args}", args)
.replace("{method_args}", methodArgs)
}
var directory = JavaPackage.split('.').fold(path, {(x, t) -> x + "/" + t });
val destRequesterFile = File(directory + "/TLApiRequester.java");
File(directory).mkdirs()
destRequesterFile.writeText(JavaRequesterTemplate
.replace("{methods}", requests)
.replace("{package}", JavaPackage), "utf-8")
var contextInit = ""
for (t in model.types.values()) {
if (t.constructors.size == 1 && !IgnoreUniting.any {(x) -> x == t.tlType.name })
{
contextInit += JavaContextIntRecord
.replace("{type}", t.javaPackage + "." + t.javaTypeName)
.replace("{id}", "0x" + Integer.toHexString(t.constructors.first!!.tlConstructor.id));
}
else {
for (c in t.constructors)
{
contextInit += JavaContextIntRecord
.replace("{type}", t.javaPackage + "." + c.javaClassName)
.replace("{id}", "0x" + Integer.toHexString(c.tlConstructor.id));
}
}
}
val destFile = File(directory + "/TLApiContext.java");
File(directory).mkdirs()
destFile.writeText(JavaContextTemplate
.replace("{init}", contextInit)
.replace("{package}", JavaPackage), "utf-8")
} | Builder/src/org/telegram/tl/builder/JavaBuilder.kt | 2598702519 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.base.analysis.api.utils
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiMember
import com.intellij.psi.search.PsiShortNamesCache
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtNamedClassOrObjectSymbol
import org.jetbrains.kotlin.analysis.api.symbols.getSymbolOfTypeSafe
import org.jetbrains.kotlin.idea.stubindex.KotlinClassShortNameIndex
import org.jetbrains.kotlin.idea.stubindex.KotlinFullClassNameIndex
import org.jetbrains.kotlin.idea.stubindex.KotlinFunctionShortNameIndex
import org.jetbrains.kotlin.idea.stubindex.KotlinPropertyShortNameIndex
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtCallableDeclaration
import org.jetbrains.kotlin.psi.KtClassOrObject
class KtSymbolFromIndexProvider(private val project: Project) {
context(KtAnalysisSession)
fun getKotlinClassesByName(
name: Name,
psiFilter: (KtClassOrObject) -> Boolean = { true },
): Sequence<KtNamedClassOrObjectSymbol> {
val scope = analysisScope
return KotlinClassShortNameIndex[name.asString(), project, scope]
.asSequence()
.filter(psiFilter)
.mapNotNull { it.getNamedClassOrObjectSymbol() }
}
context(KtAnalysisSession)
fun getKotlinClassesByNameFilter(
nameFilter: (Name) -> Boolean,
psiFilter: (KtClassOrObject) -> Boolean = { true },
): Sequence<KtNamedClassOrObjectSymbol> {
val scope = analysisScope
val index = KotlinFullClassNameIndex
return index.getAllKeys(project).asSequence()
.filter { fqName -> nameFilter(getShortName(fqName)) }
.flatMap { fqName -> index[fqName, project, scope] }
.filter(psiFilter)
.mapNotNull { it.getNamedClassOrObjectSymbol() }
}
context(KtAnalysisSession)
fun getJavaClassesByNameFilter(
nameFilter: (Name) -> Boolean,
psiFilter: (PsiClass) -> Boolean = { true }
): Sequence<KtNamedClassOrObjectSymbol> {
val names = buildSet<Name> {
forEachNonKotlinCache { cache ->
cache.allClassNames.forEach { nameString ->
if (Name.isValidIdentifier(nameString)) return@forEach
val name = Name.identifier(nameString)
if (nameFilter(name)) {
add(name)
}
}
}
}
return sequence {
names.forEach { name ->
yieldAll(getJavaClassesByName(name, psiFilter))
}
}
}
context(KtAnalysisSession)
fun getJavaClassesByName(
name: Name,
psiFilter: (PsiClass) -> Boolean = { true }
): Sequence<KtNamedClassOrObjectSymbol> {
val scope = analysisScope
val nameString = name.asString()
return sequence {
forEachNonKotlinCache { cache ->
yieldAll(cache.getClassesByName(nameString, scope).iterator())
}
}
.filter(psiFilter)
.mapNotNull { it.getNamedClassSymbol() }
}
context(KtAnalysisSession)
fun getKotlinCallableSymbolsByName(
name: Name,
psiFilter: (KtCallableDeclaration) -> Boolean = { true },
): Sequence<KtCallableSymbol> {
val scope = analysisScope
val nameString = name.asString()
return sequence {
yieldAll(KotlinFunctionShortNameIndex[nameString, project, scope])
yieldAll(KotlinPropertyShortNameIndex[nameString, project, scope])
}
.onEach { ProgressManager.checkCanceled() }
.filter { it is KtCallableDeclaration && psiFilter(it) }
.mapNotNull { it.getSymbolOfTypeSafe<KtCallableSymbol>() }
}
context(KtAnalysisSession)
fun getJavaCallableSymbolsByName(
name: Name,
psiFilter: (PsiMember) -> Boolean = { true }
): Sequence<KtCallableSymbol> {
val scope = analysisScope
val nameString = name.asString()
return sequence {
forEachNonKotlinCache { cache -> yieldAll(cache.getMethodsByName(nameString, scope).iterator()) }
forEachNonKotlinCache { cache -> yieldAll(cache.getFieldsByName(nameString, scope).iterator()) }
}
.filter(psiFilter)
.mapNotNull { it.getCallableSymbol() }
}
private inline fun forEachNonKotlinCache(action: (cache: PsiShortNamesCache) -> Unit) {
for (cache in PsiShortNamesCache.EP_NAME.getExtensions(project)) {
if (cache::class.java.name == "org.jetbrains.kotlin.idea.caches.KotlinShortNamesCache") continue
action(cache)
}
}
private fun getShortName(fqName: String) = Name.identifier(fqName.substringAfterLast('.'))
} | plugins/kotlin/base/analysis-api/analysis-api-utils/src/org/jetbrains/kotlin/idea/base/analysis/api/utils/KtSymbolFromIndexProvider.kt | 1873213399 |
// 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.testIntegration
import com.intellij.CommonBundle
import com.intellij.codeInsight.CodeInsightBundle
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInsight.navigation.NavigationUtil
import com.intellij.ide.util.PropertiesComponent
import com.intellij.lang.java.JavaLanguage
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.*
import com.intellij.psi.search.GlobalSearchScopesCore
import com.intellij.psi.util.PsiUtil
import com.intellij.testIntegration.createTest.CreateTestAction
import com.intellij.testIntegration.createTest.CreateTestUtils.computeTestRoots
import com.intellij.testIntegration.createTest.TestGenerators
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.findFacadeClass
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.actions.JavaToKotlinAction
import org.jetbrains.kotlin.idea.base.util.runWhenSmart
import org.jetbrains.kotlin.idea.base.util.runWithAlternativeResolveEnabled
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.getPackage
import org.jetbrains.kotlin.idea.core.util.toPsiDirectory
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.j2k.j2k
import org.jetbrains.kotlin.idea.util.application.executeCommand
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.hasExpectModifier
import org.jetbrains.kotlin.psi.psiUtil.startOffset
class KotlinCreateTestIntention : SelfTargetingRangeIntention<KtNamedDeclaration>(
KtNamedDeclaration::class.java,
KotlinBundle.lazyMessage("create.test")
) {
override fun applicabilityRange(element: KtNamedDeclaration): TextRange? {
if (element.hasExpectModifier() || element.nameIdentifier == null) return null
if (ModuleUtilCore.findModuleForPsiElement(element) == null) return null
if (element is KtClassOrObject) {
if (element.isLocal) return null
if (element is KtEnumEntry) return null
if (element is KtClass && (element.isAnnotation() || element.isInterface())) return null
if (element.resolveToDescriptorIfAny() == null) return null
val virtualFile = PsiUtil.getVirtualFile(element)
if (virtualFile == null ||
ProjectRootManager.getInstance(element.project).fileIndex.isInTestSourceContent(virtualFile)) return null
return TextRange(
element.startOffset,
element.getSuperTypeList()?.startOffset ?: element.body?.startOffset ?: element.endOffset
)
}
if (element.parent !is KtFile) return null
if (element is KtNamedFunction) {
return TextRange((element.funKeyword ?: element.nameIdentifier!!).startOffset, element.nameIdentifier!!.endOffset)
}
if (element is KtProperty) {
if (element.getter == null && element.delegate == null) return null
return TextRange(element.valOrVarKeyword.startOffset, element.nameIdentifier!!.endOffset)
}
return null
}
override fun startInWriteAction() = false
override fun applyTo(element: KtNamedDeclaration, editor: Editor?) {
if (editor == null) throw IllegalArgumentException("This intention requires an editor")
val lightClass = when (element) {
is KtClassOrObject -> element.toLightClass()
else -> element.containingKtFile.findFacadeClass()
} ?: return
object : CreateTestAction() {
// Based on the com.intellij.testIntegration.createTest.JavaTestGenerator.createTestClass()
private fun findTestClass(targetDirectory: PsiDirectory, className: String): PsiClass? {
val psiPackage = targetDirectory.getPackage() ?: return null
val scope = GlobalSearchScopesCore.directoryScope(targetDirectory, false)
val klass = psiPackage.findClassByShortName(className, scope).firstOrNull() ?: return null
if (!FileModificationService.getInstance().preparePsiElementForWrite(klass)) return null
return klass
}
private fun getTempJavaClassName(project: Project, kotlinFile: VirtualFile): String {
val baseName = kotlinFile.nameWithoutExtension
val psiDir = kotlinFile.parent!!.toPsiDirectory(project)!!
return generateSequence(0) { it + 1 }
.map { "$baseName$it" }
.first { psiDir.findFile("$it.java") == null && findTestClass(psiDir, it) == null }
}
// Based on the com.intellij.testIntegration.createTest.CreateTestAction.CreateTestAction.invoke()
override fun invoke(project: Project, editor: Editor?, element: PsiElement) {
val srcModule = ModuleUtilCore.findModuleForPsiElement(element) ?: return
val propertiesComponent = PropertiesComponent.getInstance()
val testFolders = computeTestRoots(srcModule)
if (testFolders.isEmpty() && !propertiesComponent.getBoolean("create.test.in.the.same.root")) {
if (Messages.showOkCancelDialog(
project,
KotlinBundle.message("test.integration.message.text.create.test.in.the.same.source.root"),
KotlinBundle.message("test.integration.title.no.test.roots.found"),
Messages.getQuestionIcon()
) != Messages.OK
) return
propertiesComponent.setValue("create.test.in.the.same.root", true)
}
val srcClass = getContainingClass(element) ?: return
val srcDir = element.containingFile.containingDirectory
val srcPackage = JavaDirectoryService.getInstance().getPackage(srcDir)
val dialog = KotlinCreateTestDialog(project, text, srcClass, srcPackage, srcModule)
if (!dialog.showAndGet()) return
val existingClass = (findTestClass(dialog.targetDirectory, dialog.className) as? KtLightClass)?.kotlinOrigin
if (existingClass != null) {
// TODO: Override dialog method when it becomes protected
val answer = Messages.showYesNoDialog(
project,
KotlinBundle.message("test.integration.message.text.kotlin.class", existingClass.name.toString()),
CommonBundle.getErrorTitle(),
KotlinBundle.message("test.integration.button.text.rewrite"),
KotlinBundle.message("test.integration.button.text.cancel"),
Messages.getErrorIcon()
)
if (answer == Messages.NO) return
}
val generatedClass = project.executeCommand(CodeInsightBundle.message("intention.create.test"), this) {
val generator = TestGenerators.INSTANCE.forLanguage(dialog.selectedTestFrameworkDescriptor.language)
project.runWithAlternativeResolveEnabled {
if (existingClass != null) {
dialog.explicitClassName = getTempJavaClassName(project, existingClass.containingFile.virtualFile)
}
generator.generateTest(project, dialog)
}
} as? PsiClass ?: return
project.runWhenSmart {
val generatedFile = generatedClass.containingFile as? PsiJavaFile ?: return@runWhenSmart
if (generatedClass.language == JavaLanguage.INSTANCE) {
project.executeCommand<Unit>(
KotlinBundle.message("convert.class.0.to.kotlin", generatedClass.name.toString()),
this
) {
runWriteAction {
generatedClass.methods.forEach {
it.throwsList.referenceElements.forEach { referenceElement -> referenceElement.delete() }
}
}
if (existingClass != null) {
runWriteAction {
val existingMethodNames = existingClass
.declarations
.asSequence()
.filterIsInstance<KtNamedFunction>()
.mapTo(HashSet()) { it.name }
generatedClass
.methods
.filter { it.name !in existingMethodNames }
.forEach { it.j2k()?.let { declaration -> existingClass.addDeclaration(declaration) } }
generatedClass.delete()
}
NavigationUtil.activateFileWithPsiElement(existingClass)
} else {
with(PsiDocumentManager.getInstance(project)) {
getDocument(generatedFile)?.let { doPostponedOperationsAndUnblockDocument(it) }
}
JavaToKotlinAction.convertFiles(
listOf(generatedFile),
project,
srcModule,
false,
forceUsingOldJ2k = true
).singleOrNull()
}
}
}
}
}
}.invoke(element.project, editor, lightClass)
}
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/testIntegration/KotlinCreateTestIntention.kt | 315048529 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.copyright
import com.intellij.configurationStore.schemeManager.SchemeManagerFactoryBase
import com.intellij.testFramework.ProjectRule
import com.intellij.testFramework.assertions.Assertions.assertThat
import com.intellij.testFramework.rules.InMemoryFsRule
import com.intellij.util.io.write
import com.maddyhome.idea.copyright.CopyrightProfile
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
internal class CopyrightManagerTest {
companion object {
@JvmField
@ClassRule
val projectRule = ProjectRule()
}
@JvmField
@Rule
val fsRule = InMemoryFsRule()
@Test
fun serialize() {
val scheme = CopyrightProfile()
scheme.name = "test"
assertThat(scheme.writeScheme()).isEqualTo("""
<copyright>
<option name="myName" value="test" />
</copyright>""".trimIndent())
}
@Test
fun serializeEmpty() {
val scheme = CopyrightProfile()
assertThat(scheme.writeScheme()).isEqualTo("""<copyright />""")
}
@Test
fun loadSchemes() {
val schemeFile = fsRule.fs.getPath("copyright/openapi.xml")
val schemeData = """
<component name="CopyrightManager">
<copyright>
<option name="notice" value="Copyright 2000-&#36;today.year 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." />
<option name="keyword" value="Copyright" />
<option name="allowReplaceKeyword" value="JetBrains" />
<option name="myName" value="openapi" />
<option name="myLocal" value="true" />
</copyright>
</component>""".trimIndent()
schemeFile.write(schemeData)
val schemeManagerFactory = SchemeManagerFactoryBase.TestSchemeManagerFactory(fsRule.fs.getPath(""))
val profileManager = CopyrightManager(projectRule.project, schemeManagerFactory,
isSupportIprProjects = false /* otherwise scheme will be not loaded from our memory fs */)
profileManager.loadSchemes()
val copyrights = profileManager.getCopyrights()
assertThat(copyrights).hasSize(1)
val scheme = copyrights.first()
assertThat(scheme.schemeState).isEqualTo(null)
assertThat(scheme.name).isEqualTo("openapi")
}
@Test
fun `use file name if scheme name missed`() {
val schemeFile = fsRule.fs.getPath("copyright/FooBar.xml")
val schemeData = """
<component name="CopyrightManager">
<copyright>
<option name="notice" value="Copyright (C) &#36;{today.year} - present by FooBar Inc. and the FooBar group of companies Please see distribution for license." />
</copyright>
</component>""".trimIndent()
schemeFile.write(schemeData)
val schemeManagerFactory = SchemeManagerFactoryBase.TestSchemeManagerFactory(fsRule.fs.getPath(""))
val profileManager = CopyrightManager(projectRule.project, schemeManagerFactory,
isSupportIprProjects = false /* otherwise scheme will be not loaded from our memory fs */)
profileManager.loadSchemes()
val copyrights = profileManager.getCopyrights()
assertThat(copyrights).hasSize(1)
assertThat(copyrights.first().name).isEqualTo("FooBar")
}
} | plugins/copyright/testSrc/com/intellij/copyright/CopyrightManagerTest.kt | 3318921916 |
package com.kingz.database.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
//@Entity(tableName = "songs")
@Entity
class SongEntity(
@PrimaryKey
@ColumnInfo(name = "singer")
var singer: String = "",
@ColumnInfo(name = "release_year")
var releaseYear: Int = 0
) : BaseEntity() | database/src/main/java/com/kingz/database/entity/SongEntity.kt | 3477522873 |
// IS_APPLICABLE: true
// WITH_RUNTIME
class Test {
fun test() {
with(Any()) {
val f = { s: String<caret> -> foo(s) }
}
}
}
fun Test.foo(s: String) {} | plugins/kotlin/idea/tests/testData/intentions/convertLambdaToReference/extensionOuterScope.kt | 135305048 |
fun a() {
b({1
<caret>},
{},
{},
)
}
// IGNORE_FORMATTER | plugins/kotlin/idea/tests/testData/indentationOnNewline/LambdaInArguments.after.kt | 2919597066 |
package baz
import foo.*
import bar.*
fun useClass() {
Foo()
}
| plugins/kotlin/jps/jps-plugin/tests/testData/incremental/pureKotlin/moveFileWithChangingPackage/useClass.kt | 1269831941 |
fun test(some: Any?, error: Int) {
val test = some ?:<caret> error
}
// SET_FALSE: CONTINUATION_INDENT_IN_ELVIS | plugins/kotlin/idea/tests/testData/indentationOnNewline/elvis/AfterElvis.kt | 3135585872 |
fun a() {
var b =
<caret>
}
// SET_FALSE: CONTINUATION_INDENT_FOR_EXPRESSION_BODIES | plugins/kotlin/idea/tests/testData/indentationOnNewline/expressionBody/MutableProperty.after.kt | 4200382630 |
/*
* Copyright 2012-2016 Dmitri Pisarenko
*
* WWW: http://altruix.cc
* E-Mail: [email protected]
* Skype: dp118m (voice calls must be scheduled in advance)
*
* Physical address:
*
* 4-i Rostovskii pereulok 2/1/20
* 119121 Moscow
* Russian Federation
*
* This file is part of econsim-tr01.
*
* econsim-tr01 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* econsim-tr01 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with econsim-tr01. If not, see <http://www.gnu.org/licenses/>.
*
*/
package cc.altruix.econsimtr01
import org.joda.time.DateTime
/**
* Created by pisarenko on 04.04.2016.
*/
class Accountant(val foodStorage: DefaultResourceStorage,
val farmer: Farmer,
val logTarget: StringBuilder) : ISensor {
val fire: (DateTime) -> Boolean = dailyAtMidnight()
override fun measure(time: DateTime, agents: List<IAgent>) {
if (fire(time)) {
logMeasurementTime(time)
logPotatoes(time)
logDaysWithoutEating(time)
}
}
private fun logDaysWithoutEating(time: DateTime) {
logTarget.append("daysWithoutEating(${time.secondsSinceT0()}, ${farmer.daysWithoutFood}).")
logTarget.newLine()
}
private fun logPotatoes(time: DateTime) {
logTarget.append("resourceAvailable(${time.secondsSinceT0()}, 'POTATO', ${foodStorage.amount(Resource.POTATO.name)}).")
logTarget.newLine()
}
private fun logMeasurementTime(time: DateTime) {
val dateTimeString = time.toSimulationDateTimeString()
logTarget.append("measurementTime(${time.secondsSinceT0()}, '$dateTimeString').")
logTarget.newLine()
}
}
| src/main/java/cc/altruix/econsimtr01/Accountant.kt | 3432899303 |
fun interface KotlinFace {
fun single()
}
fun useSam(kf: KotlinFace) {}
fun callSam() {
useSam(kf = <caret>KotlinFace {})
} | plugins/kotlin/idea/tests/testData/intentions/samConversionToAnonymousObject/funInterface.kt | 2410541308 |
// WITH_RUNTIME
fun test(list: List<Int>) {
list.<caret>filter { it > 1 }.sumOf { it }
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/convertCallChainIntoSequence/termination/sumOf.kt | 3816338042 |
package pl.srw.billcalculator.settings.di
import dagger.Subcomponent
import pl.srw.billcalculator.settings.SettingsActivity
import pl.srw.billcalculator.settings.details.SettingsDetailsFragment
import pl.srw.billcalculator.settings.details.dialog.InputSettingsDialogFragment
import pl.srw.billcalculator.settings.details.dialog.PickingSettingsDialogFragment
import pl.srw.billcalculator.settings.details.restore.ConfirmRestoreSettingsDialogFragment
import pl.srw.billcalculator.settings.list.SettingsFragment
import pl.srw.mfvp.di.scope.RetainActivityScope
@RetainActivityScope
@Subcomponent
interface SettingsComponent {
fun inject(activity: SettingsActivity)
fun inject(fragment: SettingsFragment)
fun inject(fragment: SettingsDetailsFragment)
fun inject(dialog: ConfirmRestoreSettingsDialogFragment)
fun inject(dialog: InputSettingsDialogFragment)
fun inject(dialog: PickingSettingsDialogFragment)
}
| app/src/main/java/pl/srw/billcalculator/settings/di/SettingsComponent.kt | 3406412553 |
// 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.ide.actions.searcheverywhere.ml
import com.intellij.ide.actions.searcheverywhere.SearchEverywhereFoundElementInfo
import com.intellij.ide.actions.searcheverywhere.SearchRestartReason
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReference
internal class SearchEverywhereMlSessionService {
companion object {
internal const val RECORDER_CODE = "MLSE"
@JvmStatic
fun getInstance(): SearchEverywhereMlSessionService =
ApplicationManager.getApplication().getService(SearchEverywhereMlSessionService::class.java)
}
private val sessionIdCounter = AtomicInteger()
private var activeSession: AtomicReference<SearchEverywhereMLSearchSession?> = AtomicReference()
private val experiment: SearchEverywhereMlExperiment = SearchEverywhereMlExperiment()
fun shouldOrderByML(): Boolean = experiment.shouldOrderByMl()
fun getCurrentSession(): SearchEverywhereMLSearchSession? {
if (experiment.isAllowed) {
return activeSession.get()
}
return null
}
fun onSessionStarted(project: Project?) {
if (experiment.isAllowed) {
activeSession.updateAndGet { SearchEverywhereMLSearchSession(project, sessionIdCounter.incrementAndGet()) }
}
}
fun onSearchRestart(project: Project?,
tabId: String,
reason: SearchRestartReason,
keysTyped: Int,
backspacesTyped: Int,
textLength: Int,
previousElementsProvider: () -> List<SearchEverywhereFoundElementInfo>) {
if (experiment.isAllowed) {
getCurrentSession()?.onSearchRestart(project, previousElementsProvider, reason, tabId, keysTyped, backspacesTyped, textLength)
}
}
fun onItemSelected(project: Project?, indexes: IntArray, closePopup: Boolean, elementsProvider: () -> List<SearchEverywhereFoundElementInfo>) {
if (experiment.isAllowed) {
getCurrentSession()?.onItemSelected(project, experiment, indexes, closePopup, elementsProvider)
}
}
fun onSearchFinished(project: Project?, elementsProvider: () -> List<SearchEverywhereFoundElementInfo>) {
if (experiment.isAllowed) {
getCurrentSession()?.onSearchFinished(project, experiment, elementsProvider)
}
}
fun onDialogClose() {
activeSession.updateAndGet { null }
}
} | platform/lang-impl/src/com/intellij/ide/actions/searcheverywhere/ml/SearchEverywhereMlSessionService.kt | 39403295 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.rename
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.refactoring.rename.naming.AutomaticRenamer
import com.intellij.refactoring.rename.naming.AutomaticTestRenamerFactory
import com.intellij.usageView.UsageInfo
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade
import org.jetbrains.kotlin.asJava.classes.KtLightClassForSourceDeclaration
import org.jetbrains.kotlin.asJava.findFacadeClass
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.load.kotlin.PackagePartClassUtils
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtFile
class KotlinAutomaticTestRenamerFactory : AutomaticTestRenamerFactory() {
private fun getPsiClass(element: PsiElement): PsiClass? {
return when (element) {
is KtLightClassForSourceDeclaration -> element
is KtClassOrObject -> element.toLightClass()
is KtFile -> element.findFacadeClass()
else -> null
}
}
override fun isApplicable(element: PsiElement): Boolean {
val psiClass = getPsiClass(element) ?: return false
return super.isApplicable(psiClass)
}
override fun createRenamer(element: PsiElement, newName: String, usages: MutableCollection<UsageInfo>): AutomaticRenamer {
val psiClass = getPsiClass(element)!!
val newPsiClassName = if (psiClass is KtLightClassForFacade) PackagePartClassUtils.getFilePartShortName(newName) else newName
return super.createRenamer(psiClass, newPsiClassName, usages)
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/KotlinAutomaticTestRenamerFactory.kt | 149150120 |
package alraune.entity
import alraune.*
import aplight.GelFill
import vgrechka.*
@GelFill
@LightEntity(table = "AdHocServantTypeAndParams")
class AdHocServantTypeAndParams : LightEntity0_kotlin() {
var uuid by notNull<String>()
var servantClass by notNull<String>()
@LeJson var params: Any? = null
var params__class: String? = null
object Meta
}
// TODO:vgrechka Generate this shit
val AdHocServantTypeAndParams.Meta.table get() = "AdHocServantTypeAndParams"
val AdHocServantTypeAndParams.Meta.id by myName()
val AdHocServantTypeAndParams.Meta.uuid by myName()
val AdHocServantTypeAndParams.Meta.servantClass by myName()
val AdHocServantTypeAndParams.Meta.params by myName()
val AdHocServantTypeAndParams.Meta.params__class by myName()
| alraune/alraune/src/main/java/alraune/entity/AdHocServantTypeAndParams.kt | 2756406262 |
package com.lepiionut.parcers
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
| app/src/test/java/com/lepiionut/parcers/ExampleUnitTest.kt | 2065246424 |
// 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.klib
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.project.LibraryData
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider
import com.intellij.openapi.externalSystem.service.project.IdeUIModifiableModelsProvider
import com.intellij.openapi.externalSystem.service.project.manage.AbstractProjectDataService
import com.intellij.openapi.externalSystem.util.ExternalSystemConstants
import com.intellij.openapi.externalSystem.util.Order
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.LibraryOrderEntry
import com.intellij.openapi.roots.libraries.Library
import org.jetbrains.kotlin.idea.gradle.configuration.klib.KotlinNativeLibraryNameUtil.KOTLIN_NATIVE_LIBRARY_PREFIX_PLUS_SPACE
// KT-30490. This `ProjectDaaStervice` must be executed immediately after
// `com.intellij.openapi.externalSystem.service.project.manage.LibraryDataService` to clean-up KLIBs before any other actions taken on them.
@Order(ExternalSystemConstants.BUILTIN_LIBRARY_DATA_SERVICE_ORDER + 1) // force order
class KotlinNativeLibraryDataService : AbstractProjectDataService<LibraryData, Library>() {
override fun getTargetDataKey() = ProjectKeys.LIBRARY
// See also `com.intellij.openapi.externalSystem.service.project.manage.LibraryDataService.postProcess()`
override fun postProcess(
toImport: MutableCollection<out DataNode<LibraryData>>,
projectData: ProjectData?,
project: Project,
modelsProvider: IdeModifiableModelsProvider
) {
if (projectData == null || modelsProvider is IdeUIModifiableModelsProvider) return
val librariesModel = modelsProvider.modifiableProjectLibrariesModel
val potentialOrphans = HashMap<String, Library>()
librariesModel.libraries.forEach { library ->
val libraryName = library.name?.takeIf { it.startsWith(KOTLIN_NATIVE_LIBRARY_PREFIX_PLUS_SPACE) } ?: return@forEach
potentialOrphans[libraryName] = library
}
if (potentialOrphans.isEmpty()) return
modelsProvider.modules.forEach { module ->
modelsProvider.getOrderEntries(module).forEach inner@{ orderEntry ->
val libraryOrderEntry = orderEntry as? LibraryOrderEntry ?: return@inner
if (libraryOrderEntry.isModuleLevel) return@inner
val libraryName = (libraryOrderEntry.library?.name ?: libraryOrderEntry.libraryName)
?.takeIf { it.startsWith(KOTLIN_NATIVE_LIBRARY_PREFIX_PLUS_SPACE) } ?: return@inner
potentialOrphans.remove(libraryName)
}
}
potentialOrphans.keys.forEach { libraryName ->
librariesModel.getLibraryByName(libraryName)?.let { librariesModel.removeLibrary(it) }
}
}
}
| plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/klib/KotlinNativeLibraryDataService.kt | 723254508 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.stepping.smartStepInto
import org.jetbrains.org.objectweb.asm.Handle
import org.jetbrains.org.objectweb.asm.Label
import org.jetbrains.org.objectweb.asm.MethodVisitor
import org.jetbrains.org.objectweb.asm.Opcodes
/**
* This class pipes all visit*Insn calls to the [reportOpcode] function. The derived class can process all visited opcodes
* by overriding only [reportOpcode] function.
*/
open class OpcodeReportingMethodVisitor(
private val delegate: OpcodeReportingMethodVisitor? = null
) : MethodVisitor(Opcodes.API_VERSION, delegate) {
protected open fun reportOpcode(opcode: Int) {
delegate?.reportOpcode(opcode)
}
override fun visitInsn(opcode: Int) =
reportOpcode(opcode)
override fun visitLdcInsn(value: Any?) =
reportOpcode(Opcodes.LDC)
override fun visitLookupSwitchInsn(dflt: Label?, keys: IntArray?, labels: Array<out Label>?) =
reportOpcode(Opcodes.LOOKUPSWITCH)
override fun visitMultiANewArrayInsn(descriptor: String?, numDimensions: Int) =
reportOpcode(Opcodes.MULTIANEWARRAY)
override fun visitIincInsn(variable: Int, increment: Int) =
reportOpcode(Opcodes.IINC)
override fun visitIntInsn(opcode: Int, operand: Int) =
reportOpcode(opcode)
override fun visitVarInsn(opcode: Int, variable: Int) =
reportOpcode(opcode)
override fun visitTypeInsn(opcode: Int, type: String?) =
reportOpcode(opcode)
override fun visitFieldInsn(opcode: Int, owner: String?, name: String?, descriptor: String?) =
reportOpcode(opcode)
override fun visitJumpInsn(opcode: Int, label: Label?) =
reportOpcode(opcode)
override fun visitTableSwitchInsn(min: Int, max: Int, dflt: Label?, vararg labels: Label?) =
reportOpcode(Opcodes.TABLESWITCH)
override fun visitMethodInsn(opcode: Int, owner: String, name: String, descriptor: String, isInterface: Boolean) =
reportOpcode(opcode)
override fun visitInvokeDynamicInsn(
name: String?,
descriptor: String?,
bootstrapMethodHandle: Handle?,
vararg bootstrapMethodArguments: Any?
) = reportOpcode(Opcodes.INVOKEDYNAMIC)
}
| plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/stepping/smartStepInto/OpcodeReportingMethodVisitor.kt | 2594500833 |
package com.github.kerubistan.kerub.host.servicemanager.rc
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class RcServiceManagerTest {
@Test
fun disable() {
assertFalse(RcServiceManager.disable("ctld","""
hostname="freebsd10"
ifconfig_re0="DHCP"
ifconfig_re0_ipv6="inet6 accept_rtadv"
sshd_enable="YES"
ntpd_enable="YES"
# Set dumpdev to "AUTO" to enable crash dumps, "NO" to disable
dumpdev="AUTO"
ctld_enable="YES"
""").contains("ctld"))
}
@Test
fun testIsEnabled() {
assertTrue(RcServiceManager.isEnabled("ctld",
"""
hostname="freebsd10"
ifconfig_re0="DHCP"
ifconfig_re0_ipv6="inet6 accept_rtadv"
sshd_enable="YES"
ntpd_enable="YES"
# Set dumpdev to "AUTO" to enable crash dumps, "NO" to disable
dumpdev="AUTO"
ctld_enable="YES"
"""))
assertFalse(RcServiceManager.isEnabled("ctld",
"""
hostname="freebsd10"
ifconfig_re0="DHCP"
ifconfig_re0_ipv6="inet6 accept_rtadv"
sshd_enable="YES"
ntpd_enable="YES"
# Set dumpdev to "AUTO" to enable crash dumps, "NO" to disable
dumpdev="AUTO"
ctld_enable="NO"
"""))
assertFalse(RcServiceManager.isEnabled("ctld",
"""
hostname="freebsd10"
ifconfig_re0="DHCP"
ifconfig_re0_ipv6="inet6 accept_rtadv"
sshd_enable="YES"
ntpd_enable="YES"
# Set dumpdev to "AUTO" to enable crash dumps, "NO" to disable
dumpdev="AUTO"
"""))
}
@Test
fun testDisable() {
}
} | src/test/kotlin/com/github/kerubistan/kerub/host/servicemanager/rc/RcServiceManagerTest.kt | 1775035056 |
package net.serverpeon.discord.event
import net.serverpeon.discord.model.ClientModel
/**
* Fired when all members have been loaded into the model.
*
* This will always be emitted after [ModelReadyEvent] and will only be delayed if the client is a members of a large
* server.
*/
interface MembersLoadedEvent : Event {
val model: ClientModel
} | api/src/main/kotlin/net/serverpeon/discord/event/MembersLoadedEvent.kt | 537941260 |
package com.lytefast.flexinput.adapters
import android.content.ContentResolver
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.content.res.AppCompatResources
import androidx.recyclerview.widget.RecyclerView
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.drawee.view.SimpleDraweeView
import com.facebook.imagepipeline.common.ResizeOptions
import com.facebook.imagepipeline.common.RotationOptions
import com.facebook.imagepipeline.request.ImageRequestBuilder
import com.lytefast.flexinput.R
import com.lytefast.flexinput.model.Attachment
import com.lytefast.flexinput.model.Photo
import com.lytefast.flexinput.utils.SelectionAggregator
typealias SelectionAggregatorProvider<T> = (AttachmentPreviewAdapter<T>) -> SelectionAggregator<T>
/**
* [RecyclerView.Adapter] which, given a list of attachments understands how to display them.
* This can be extended to implement custom previews.
*
* @author Sam Shih
*/
class AttachmentPreviewAdapter<T : Attachment<Any>>
@JvmOverloads constructor(private val contentResolver: ContentResolver,
selectionAggregatorProvider: SelectionAggregatorProvider<T>? = null)
: RecyclerView.Adapter<AttachmentPreviewAdapter<T>.ViewHolder>() {
val selectionAggregator: SelectionAggregator<T> =
selectionAggregatorProvider?.invoke(this) ?: SelectionAggregator(this)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.view_attachment_preview_item, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = selectionAggregator[position]
holder.bind(item)
}
override fun getItemCount(): Int = selectionAggregator.size
fun clear() {
val oldItemCount = itemCount
selectionAggregator.clear()
notifyItemRangeRemoved(0, oldItemCount)
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val draweeView: SimpleDraweeView = itemView as SimpleDraweeView
init {
val tintDrawable = AppCompatResources.getDrawable(itemView.context, R.drawable.ic_file_24dp)
draweeView.hierarchy.setPlaceholderImage(tintDrawable)
}
fun bind(item: T) {
when (item) {
is Photo -> draweeView.setImageURI(item.getThumbnailUri(contentResolver))
else -> {
// Make sure large images don't crash drawee
// http://stackoverflow.com/questions/33676807/fresco-bitmap-too-large-to-be-uploaded-into-a-texture
val height = draweeView.layoutParams.height
val imageRequestBuilder = ImageRequestBuilder.newBuilderWithSource(item.uri)
.setRotationOptions(RotationOptions.autoRotate())
.setResizeOptions(ResizeOptions(height, height))
val controller = Fresco.newDraweeControllerBuilder()
.setOldController(draweeView.controller)
.setAutoPlayAnimations(true)
.setImageRequest(imageRequestBuilder.build())
.build()
draweeView.controller = controller
}
}
itemView.setOnClickListener {
// Let the child delete the item, and notify us
selectionAggregator.unselectItem(item)
}
}
}
}
| flexinput/src/main/java/com/lytefast/flexinput/adapters/AttachmentPreviewAdapter.kt | 2225715432 |
package tracker
import android.content.Context
import android.os.Bundle
internal sealed class EventTrackerImpl : EventTracker {
object Void : EventTrackerImpl() {
override fun init(context: Context) = Unit
override fun trackRecommendationResponse(data: Bundle) = Unit
override fun trackLikeResponse(data: Bundle) = Unit
override fun trackUserProvidedAccount() = Unit
override fun setUserProvidedAccount(value: String?) = Unit
}
}
| event-tracker/src/main/kotlin/tracker/EventTrackerImpl.kt | 2170382221 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.tv.foundation.lazy.list
import android.os.Build
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.focusable
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredHeight
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.layout.requiredSizeIn
import androidx.compose.foundation.layout.requiredWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.text.BasicText
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.testutils.WithTouchSlop
import androidx.compose.testutils.assertPixels
import androidx.compose.testutils.assertShape
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.input.key.NativeKeyEvent
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.layout
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.SemanticsActions
import androidx.compose.ui.semantics.SemanticsProperties
import androidx.compose.ui.test.SemanticsMatcher.Companion.keyIsDefined
import androidx.compose.ui.test.SemanticsMatcher.Companion.keyNotDefined
import androidx.compose.ui.test.assert
import androidx.compose.ui.test.assertHeightIsEqualTo
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.assertIsNotDisplayed
import androidx.compose.ui.test.assertWidthIsEqualTo
import androidx.compose.ui.test.captureToImage
import androidx.compose.ui.test.getUnclippedBoundsInRoot
import androidx.compose.ui.test.junit4.ComposeContentTestRule
import androidx.compose.ui.test.junit4.StateRestorationTester
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performSemanticsAction
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.dp
import androidx.compose.ui.zIndex
import androidx.test.filters.LargeTest
import androidx.test.filters.SdkSuppress
import androidx.tv.foundation.PivotOffsets
import androidx.tv.foundation.lazy.AutoTestFrameClock
import androidx.tv.foundation.lazy.grid.keyPress
import com.google.common.collect.Range
import com.google.common.truth.IntegerSubject
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import java.util.concurrent.CountDownLatch
import kotlin.math.roundToInt
import kotlinx.coroutines.runBlocking
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
@LargeTest
@RunWith(Parameterized::class)
class LazyListTest(orientation: Orientation) : BaseLazyListTestWithOrientation(orientation) {
private val LazyListTag = "LazyListTag"
private val firstItemTag = "firstItemTag"
@Test
fun lazyListShowsCombinedItems() {
val itemTestTag = "itemTestTag"
val items = listOf(1, 2).map { it.toString() }
val indexedItems = listOf(3, 4, 5)
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(Modifier.mainAxisSize(200.dp)) {
item {
Spacer(
Modifier.mainAxisSize(40.dp)
.then(fillParentMaxCrossAxis())
.testTag(itemTestTag)
)
}
items(items) {
Spacer(Modifier.mainAxisSize(40.dp).then(fillParentMaxCrossAxis()).testTag(it))
}
itemsIndexed(indexedItems) { index, item ->
Spacer(
Modifier.mainAxisSize(41.dp).then(fillParentMaxCrossAxis())
.testTag("$index-$item")
)
}
}
}
rule.onNodeWithTag(itemTestTag)
.assertIsDisplayed()
rule.onNodeWithTag("1")
.assertIsDisplayed()
rule.onNodeWithTag("2")
.assertIsDisplayed()
rule.onNodeWithTag("0-3")
.assertIsDisplayed()
rule.onNodeWithTag("1-4")
.assertIsDisplayed()
rule.onNodeWithTag("2-5")
.assertDoesNotExist()
}
@Test
fun lazyListAllowEmptyListItems() {
val itemTag = "itemTag"
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow {
items(emptyList<Any>()) { }
item {
Spacer(Modifier.size(10.dp).testTag(itemTag))
}
}
}
rule.onNodeWithTag(itemTag)
.assertIsDisplayed()
}
@Test
fun lazyListAllowsNullableItems() {
val items = listOf("1", null, "3")
val nullTestTag = "nullTestTag"
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(Modifier.mainAxisSize(200.dp)) {
items(items) {
if (it != null) {
Spacer(
Modifier.mainAxisSize(101.dp)
.then(fillParentMaxCrossAxis())
.testTag(it)
)
} else {
Spacer(
Modifier.mainAxisSize(101.dp).then(fillParentMaxCrossAxis())
.testTag(nullTestTag)
)
}
}
}
}
rule.onNodeWithTag("1")
.assertIsDisplayed()
rule.onNodeWithTag(nullTestTag)
.assertIsDisplayed()
rule.onNodeWithTag("3")
.assertDoesNotExist()
}
@Test
fun lazyListOnlyVisibleItemsAdded() {
val items = (1..4).map { it.toString() }
rule.setContentWithTestViewConfiguration {
Box(Modifier.mainAxisSize(200.dp)) {
LazyColumnOrRow(pivotOffsets = PivotOffsets(parentFraction = 0.4f)) {
items(items) {
Spacer(
Modifier.mainAxisSize(101.dp).then(fillParentMaxCrossAxis()).testTag(it)
)
}
}
}
}
rule.onNodeWithTag("1")
.assertIsDisplayed()
rule.onNodeWithTag("2")
.assertIsDisplayed()
rule.onNodeWithTag("3")
.assertDoesNotExist()
rule.onNodeWithTag("4")
.assertDoesNotExist()
}
@Test
fun lazyListScrollToShowItems123() {
val items = (1..4).map { it.toString() }
rule.setContentWithTestViewConfiguration {
Box(Modifier.mainAxisSize(200.dp)) {
LazyColumnOrRow(
modifier = Modifier.testTag(LazyListTag),
pivotOffsets = PivotOffsets(parentFraction = 0.3f)
) {
items(items) {
Box(
Modifier.mainAxisSize(101.dp).then(fillParentMaxCrossAxis())
.testTag(it).focusable().border(3.dp, Color.Red)
) {
BasicText(it)
}
}
}
}
}
rule.keyPress(3)
rule.onNodeWithTag("1")
.assertIsDisplayed()
rule.onNodeWithTag("2")
.assertIsDisplayed()
rule.onNodeWithTag("3")
.assertIsDisplayed()
rule.onNodeWithTag("4")
.assertIsNotDisplayed()
}
@Test
fun lazyListScrollToHideFirstItem() {
val items = (1..4).map { it.toString() }
rule.setContentWithTestViewConfiguration {
Box(Modifier.mainAxisSize(200.dp)) {
LazyColumnOrRow(modifier = Modifier.testTag(LazyListTag)) {
items(items) {
Box(
Modifier.mainAxisSize(101.dp).then(fillParentMaxCrossAxis())
.testTag(it).focusable()
)
}
}
}
}
rule.keyPress(3)
rule.onNodeWithTag("1")
.assertIsNotDisplayed()
rule.onNodeWithTag("2")
.assertIsDisplayed()
rule.onNodeWithTag("3")
.assertIsDisplayed()
}
@Test
fun lazyListScrollToShowItems234() {
val items = (1..4).map { it.toString() }
rule.setContentWithTestViewConfiguration {
Box(Modifier.mainAxisSize(200.dp)) {
LazyColumnOrRow(
modifier = Modifier.testTag(LazyListTag),
pivotOffsets = PivotOffsets(parentFraction = 0.3f)
) {
items(items) {
Box(
Modifier.mainAxisSize(101.dp).then(fillParentMaxCrossAxis())
.testTag(it).focusable()
)
}
}
}
}
rule.keyPress(4)
rule.onNodeWithTag("1")
.assertIsNotDisplayed()
rule.onNodeWithTag("2")
.assertIsDisplayed()
rule.onNodeWithTag("3")
.assertIsDisplayed()
rule.onNodeWithTag("4")
.assertIsDisplayed()
}
@Test
fun lazyListWrapsContent() = with(rule.density) {
val itemInsideLazyList = "itemInsideLazyList"
val itemOutsideLazyList = "itemOutsideLazyList"
var sameSizeItems by mutableStateOf(true)
rule.setContentWithTestViewConfiguration {
Column {
LazyColumnOrRow(Modifier.testTag(LazyListTag)) {
items(listOf(1, 2)) {
if (it == 1) {
Spacer(Modifier.size(50.dp).testTag(itemInsideLazyList))
} else {
Spacer(Modifier.size(if (sameSizeItems) 50.dp else 70.dp))
}
}
}
Spacer(Modifier.size(50.dp).testTag(itemOutsideLazyList))
}
}
rule.onNodeWithTag(itemInsideLazyList)
.assertIsDisplayed()
rule.onNodeWithTag(itemOutsideLazyList)
.assertIsDisplayed()
var lazyListBounds = rule.onNodeWithTag(LazyListTag).getUnclippedBoundsInRoot()
var mainAxisEndBound = if (vertical) lazyListBounds.bottom else lazyListBounds.right
var crossAxisEndBound = if (vertical) lazyListBounds.right else lazyListBounds.bottom
assertThat(lazyListBounds.left.roundToPx()).isWithin1PixelFrom(0.dp.roundToPx())
assertThat(mainAxisEndBound.roundToPx()).isWithin1PixelFrom(100.dp.roundToPx())
assertThat(lazyListBounds.top.roundToPx()).isWithin1PixelFrom(0.dp.roundToPx())
assertThat(crossAxisEndBound.roundToPx()).isWithin1PixelFrom(50.dp.roundToPx())
rule.runOnIdle {
sameSizeItems = false
}
rule.waitForIdle()
rule.onNodeWithTag(itemInsideLazyList)
.assertIsDisplayed()
rule.onNodeWithTag(itemOutsideLazyList)
.assertIsDisplayed()
lazyListBounds = rule.onNodeWithTag(LazyListTag).getUnclippedBoundsInRoot()
mainAxisEndBound = if (vertical) lazyListBounds.bottom else lazyListBounds.right
crossAxisEndBound = if (vertical) lazyListBounds.right else lazyListBounds.bottom
assertThat(lazyListBounds.left.roundToPx()).isWithin1PixelFrom(0.dp.roundToPx())
assertThat(mainAxisEndBound.roundToPx()).isWithin1PixelFrom(120.dp.roundToPx())
assertThat(lazyListBounds.top.roundToPx()).isWithin1PixelFrom(0.dp.roundToPx())
assertThat(crossAxisEndBound.roundToPx()).isWithin1PixelFrom(70.dp.roundToPx())
}
@Test
fun compositionsAreDisposed_whenNodesAreScrolledOff() {
var composed: Boolean
var disposed = false
// Ten 31dp spacers in a 300dp list
val latch = CountDownLatch(10)
rule.setContentWithTestViewConfiguration {
// Fixed size to eliminate device size as a factor
Box(Modifier.testTag(LazyListTag).mainAxisSize(300.dp)) {
LazyColumnOrRow(Modifier.fillMaxSize()) {
items(50) {
DisposableEffect(NeverEqualObject) {
composed = true
// Signal when everything is done composing
latch.countDown()
onDispose {
disposed = true
}
}
// There will be 10 of these in the 300dp box
Box(Modifier.mainAxisSize(31.dp).focusable()) {
BasicText(it.toString())
}
}
}
}
}
latch.await()
composed = false
assertWithMessage("Compositions were disposed before we did any scrolling")
.that(disposed).isFalse()
// Mostly a validity check, this is not part of the behavior under test
assertWithMessage("Additional composition occurred for no apparent reason")
.that(composed).isFalse()
Thread.sleep(5000L)
rule.keyPress(
if (vertical) NativeKeyEvent.KEYCODE_DPAD_DOWN else NativeKeyEvent.KEYCODE_DPAD_RIGHT,
13
)
Thread.sleep(5000L)
rule.waitForIdle()
assertWithMessage("No additional items were composed after scroll, scroll didn't work")
.that(composed).isTrue()
// We may need to modify this test once we prefetch/cache items outside the viewport
assertWithMessage(
"No compositions were disposed after scrolling, compositions were leaked"
).that(disposed).isTrue()
}
@Test
fun whenItemsAreInitiallyCreatedWith0SizeWeCanScrollWhenTheyExpanded() {
val thirdTag = "third"
val items = (1..3).toList()
var thirdHasSize by mutableStateOf(false)
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(
Modifier.fillMaxCrossAxis()
.mainAxisSize(100.dp)
.testTag(LazyListTag)
) {
items(items) {
if (it == 3) {
Box(
Modifier.testTag(thirdTag)
.then(fillParentMaxCrossAxis())
.mainAxisSize(if (thirdHasSize) 60.dp else 0.dp).focusable()
)
} else {
Box(Modifier.then(fillParentMaxCrossAxis()).mainAxisSize(60.dp).focusable())
}
}
}
}
rule.keyPress(3)
rule.onNodeWithTag(thirdTag)
.assertExists()
.assertIsNotDisplayed()
rule.runOnIdle {
thirdHasSize = true
}
rule.waitForIdle()
rule.keyPress(2)
rule.onNodeWithTag(thirdTag)
.assertIsDisplayed()
}
@Test
fun itemFillingParentWidth() {
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(Modifier.requiredSize(width = 100.dp, height = 150.dp)) {
items(listOf(0)) {
Spacer(
Modifier.fillParentMaxWidth().requiredHeight(50.dp).testTag(firstItemTag)
)
}
}
}
rule.onNodeWithTag(firstItemTag)
.assertWidthIsEqualTo(100.dp)
.assertHeightIsEqualTo(50.dp)
}
@Test
fun itemFillingParentHeight() {
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(Modifier.requiredSize(width = 100.dp, height = 150.dp)) {
items(listOf(0)) {
Spacer(
Modifier.requiredWidth(50.dp).fillParentMaxHeight().testTag(firstItemTag)
)
}
}
}
rule.onNodeWithTag(firstItemTag)
.assertWidthIsEqualTo(50.dp)
.assertHeightIsEqualTo(150.dp)
}
@Test
fun itemFillingParentSize() {
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(Modifier.requiredSize(width = 100.dp, height = 150.dp)) {
items(listOf(0)) {
Spacer(Modifier.fillParentMaxSize().testTag(firstItemTag))
}
}
}
rule.onNodeWithTag(firstItemTag)
.assertWidthIsEqualTo(100.dp)
.assertHeightIsEqualTo(150.dp)
}
@Test
fun itemFillingParentWidthFraction() {
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(Modifier.requiredSize(width = 100.dp, height = 150.dp)) {
items(listOf(0)) {
Spacer(
Modifier.fillParentMaxWidth(0.7f)
.requiredHeight(50.dp)
.testTag(firstItemTag)
)
}
}
}
rule.onNodeWithTag(firstItemTag)
.assertWidthIsEqualTo(70.dp)
.assertHeightIsEqualTo(50.dp)
}
@Test
fun itemFillingParentHeightFraction() {
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(Modifier.requiredSize(width = 100.dp, height = 150.dp)) {
items(listOf(0)) {
Spacer(
Modifier.requiredWidth(50.dp)
.fillParentMaxHeight(0.3f)
.testTag(firstItemTag)
)
}
}
}
rule.onNodeWithTag(firstItemTag)
.assertWidthIsEqualTo(50.dp)
.assertHeightIsEqualTo(45.dp)
}
@Test
fun itemFillingParentSizeFraction() {
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(Modifier.requiredSize(width = 100.dp, height = 150.dp)) {
items(listOf(0)) {
Spacer(Modifier.fillParentMaxSize(0.5f).testTag(firstItemTag))
}
}
}
rule.onNodeWithTag(firstItemTag)
.assertWidthIsEqualTo(50.dp)
.assertHeightIsEqualTo(75.dp)
}
@Test
fun itemFillingParentSizeParentResized() {
var parentSize by mutableStateOf(100.dp)
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(Modifier.requiredSize(parentSize)) {
items(listOf(0)) {
Spacer(Modifier.fillParentMaxSize().testTag(firstItemTag))
}
}
}
rule.runOnIdle {
parentSize = 150.dp
}
rule.onNodeWithTag(firstItemTag)
.assertWidthIsEqualTo(150.dp)
.assertHeightIsEqualTo(150.dp)
}
@Test
fun whenNotAnymoreAvailableItemWasDisplayed() {
var items by mutableStateOf((1..30).toList())
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(modifier = Modifier.requiredSize(100.dp).testTag(LazyListTag)) {
items(items) {
Box(Modifier.requiredSize(20.dp).testTag("$it").focusable())
}
}
}
// after scroll we will display items 16-20
rule.keyPress(17)
rule.runOnIdle {
items = (1..10).toList()
}
// there is no item 16 anymore so we will just display the last items 6-10
rule.onNodeWithTag("6")
.assertStartPositionIsAlmost(0.dp)
}
@Test
fun whenFewDisplayedItemsWereRemoved() {
var items by mutableStateOf((1..10).toList())
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(modifier = Modifier.requiredSize(100.dp).testTag(LazyListTag)) {
items(items) {
Spacer(Modifier.requiredSize(20.dp).testTag("$it").focusable())
}
}
}
// after scroll we will display items 6-10
rule.keyPress(5)
rule.runOnIdle {
items = (1..8).toList()
}
// there are no more items 9 and 10, so we have to scroll back
rule.onNodeWithTag("4")
.assertStartPositionIsAlmost(0.dp)
}
@Test
fun whenItemsBecameEmpty() {
var items by mutableStateOf((1..10).toList())
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(
modifier = Modifier.requiredSizeIn(maxHeight = 100.dp, maxWidth = 100.dp)
.testTag(LazyListTag)
) {
items(items) {
Spacer(Modifier.requiredSize(20.dp).testTag("$it").focusable())
}
}
}
// after scroll we will display items 2-6
rule.keyPress(2)
rule.runOnIdle {
items = emptyList()
}
// there are no more items so the lazy list is zero sized
rule.onNodeWithTag(LazyListTag)
.assertWidthIsEqualTo(0.dp)
.assertHeightIsEqualTo(0.dp)
// and has no children
rule.onNodeWithTag("1")
.assertDoesNotExist()
rule.onNodeWithTag("2")
.assertDoesNotExist()
}
@Test
fun scrollBackAndForth() {
val items by mutableStateOf((1..20).toList())
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(
modifier = Modifier.requiredSize(100.dp).testTag(LazyListTag)
) {
items(items) {
Spacer(Modifier.requiredSize(20.dp).testTag("$it"))
}
}
}
// after scroll we will display items 6-10
rule.keyPress(5)
// and scroll back
rule.keyPress(5, reverseScroll = true)
rule.onNodeWithTag("1")
.assertStartPositionIsAlmost(0.dp)
}
@Test
fun tryToScrollBackwardWhenAlreadyOnTop() {
val items by mutableStateOf((1..20).toList())
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(modifier = Modifier.requiredSize(100.dp).testTag(LazyListTag)) {
items(items) {
Box(Modifier.requiredSize(20.dp).testTag("$it").focusable())
}
}
}
// getting focus to the first element
rule.keyPress(2)
// we already displaying the first item, so this should do nothing
rule.keyPress(4, reverseScroll = true)
rule.onNodeWithTag("1")
.assertStartPositionIsAlmost(0.dp)
rule.onNodeWithTag("2")
.assertStartPositionIsAlmost(20.dp)
rule.onNodeWithTag("3")
.assertStartPositionIsAlmost(40.dp)
rule.onNodeWithTag("4")
.assertStartPositionIsAlmost(60.dp)
rule.onNodeWithTag("5")
.assertStartPositionIsAlmost(80.dp)
}
@Test
fun contentOfNotStableItemsIsNotRecomposedDuringScroll() {
val items = listOf(NotStable(1), NotStable(2))
var firstItemRecomposed = 0
var secondItemRecomposed = 0
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(modifier = Modifier.requiredSize(100.dp).testTag(LazyListTag)) {
items(items) {
if (it.count == 1) {
firstItemRecomposed++
} else {
secondItemRecomposed++
}
Box(Modifier.requiredSize(75.dp).focusable())
}
}
}
rule.runOnIdle {
assertThat(firstItemRecomposed).isEqualTo(1)
assertThat(secondItemRecomposed).isEqualTo(1)
}
rule.keyPress(2)
rule.runOnIdle {
assertThat(firstItemRecomposed).isEqualTo(1)
assertThat(secondItemRecomposed).isEqualTo(1)
}
}
@Test
fun onlyOneMeasurePassForScrollEvent() {
val items by mutableStateOf((1..20).toList())
lateinit var state: TvLazyListState
rule.setContentWithTestViewConfiguration {
state = rememberTvLazyListState()
state.prefetchingEnabled = false
LazyColumnOrRow(
Modifier.requiredSize(100.dp).testTag(LazyListTag),
state = state
) {
items(items) {
Spacer(Modifier.requiredSize(20.dp).testTag("$it"))
}
}
}
val initialMeasurePasses = state.numMeasurePasses
rule.runOnIdle {
with(rule.density) {
state.onScroll(-110.dp.toPx())
}
}
rule.waitForIdle()
assertThat(state.numMeasurePasses).isEqualTo(initialMeasurePasses + 1)
}
@Test
fun onlyOneInitialMeasurePass() {
val items by mutableStateOf((1..20).toList())
lateinit var state: TvLazyListState
rule.setContent {
state = rememberTvLazyListState()
LazyColumnOrRow(
Modifier.requiredSize(100.dp).testTag(LazyListTag),
state = state
) {
items(items) {
Spacer(Modifier.requiredSize(20.dp).testTag("$it"))
}
}
}
rule.runOnIdle {
assertThat(state.numMeasurePasses).isEqualTo(1)
}
}
@Test
fun scroll_makeListSmaller_scroll() {
var items by mutableStateOf((1..100).toList())
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(modifier = Modifier.requiredSize(100.dp).testTag(LazyListTag)) {
items(items) {
Box(Modifier.requiredSize(10.dp).testTag("$it").focusable())
}
}
}
rule.keyPress(30)
rule.runOnIdle {
items = (1..11).toList()
}
rule.waitForIdle()
// try to scroll after the data set has been updated. this was causing a crash previously
rule.keyPress(1, reverseScroll = true)
rule.onNodeWithTag("11")
.assertIsDisplayed()
}
@Test
fun initialScrollIsApplied() {
val items by mutableStateOf((0..20).toList())
lateinit var state: TvLazyListState
val expectedOffset = with(rule.density) { 10.dp.roundToPx() }
rule.setContentWithTestViewConfiguration {
state = rememberTvLazyListState(2, expectedOffset)
LazyColumnOrRow(
Modifier.requiredSize(100.dp).testTag(LazyListTag),
state = state
) {
items(items) {
Spacer(Modifier.requiredSize(20.dp).testTag("$it"))
}
}
}
rule.runOnIdle {
assertThat(state.firstVisibleItemIndex).isEqualTo(2)
assertThat(state.firstVisibleItemScrollOffset).isEqualTo(expectedOffset)
}
rule.onNodeWithTag("2")
.assertStartPositionInRootIsEqualTo((-10).dp)
}
@Test
fun stateIsRestored() {
val restorationTester = StateRestorationTester(rule)
var state: TvLazyListState? = null
restorationTester.setContent {
state = rememberTvLazyListState()
LazyColumnOrRow(
Modifier.requiredSize(100.dp).testTag(LazyListTag),
state = state!!
) {
items(20) {
Spacer(Modifier.requiredSize(20.dp).testTag("$it"))
}
}
}
rule.keyPress(3)
val (index, scrollOffset) = rule.runOnIdle {
state!!.firstVisibleItemIndex to state!!.firstVisibleItemScrollOffset
}
state = null
restorationTester.emulateSavedInstanceStateRestore()
rule.runOnIdle {
assertThat(state!!.firstVisibleItemIndex).isEqualTo(index)
assertThat(state!!.firstVisibleItemScrollOffset).isEqualTo(scrollOffset)
}
}
@Test
fun snapToItemIndex() {
lateinit var state: TvLazyListState
rule.setContentWithTestViewConfiguration {
state = rememberTvLazyListState()
LazyColumnOrRow(
Modifier.requiredSize(100.dp).testTag(LazyListTag),
state = state
) {
items(20) {
Spacer(Modifier.requiredSize(20.dp).testTag("$it"))
}
}
}
rule.runOnIdle {
runBlocking {
state.scrollToItem(3, 10)
}
assertThat(state.firstVisibleItemIndex).isEqualTo(3)
assertThat(state.firstVisibleItemScrollOffset).isEqualTo(10)
}
}
// TODO: Needs to be debugged and fixed for TV surfaces.
/*@Test
fun itemsAreNotRedrawnDuringScroll() {
val items = (0..20).toList()
val redrawCount = Array(6) { 0 }
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(
modifier = Modifier.requiredSize(100.dp).testTag(LazyListTag),
pivotOffsetConfig = PivotOffsets(parentFraction = 0f)
) {
items(items) {
Box(
Modifier.requiredSize(20.dp)
.testTag(it.toString())
.drawBehind {
redrawCount[it]++
if (redrawCount[it] != 1) {
Log.i("REMOVE_ME", Exception("Redrawn").stackTraceToString())
}
}
.focusable()
) {
BasicText(it.toString())
}
}
}
}
rule.keyPress(3)
rule.onNodeWithTag("0").assertIsNotDisplayed()
rule.runOnIdle {
redrawCount.forEachIndexed { index, i ->
assertWithMessage("Item with index $index was redrawn $i times")
.that(i).isEqualTo(1)
}
}
}*/
@Test
fun itemInvalidationIsNotCausingAnotherItemToRedraw() {
val redrawCount = Array(2) { 0 }
var stateUsedInDrawScope by mutableStateOf(false)
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(Modifier.requiredSize(100.dp).testTag(LazyListTag)) {
items(2) {
Spacer(
Modifier.requiredSize(50.dp)
.drawBehind {
redrawCount[it]++
if (it == 1) {
stateUsedInDrawScope.hashCode()
}
}
)
}
}
}
rule.runOnIdle {
stateUsedInDrawScope = true
}
rule.runOnIdle {
assertWithMessage("First items is not expected to be redrawn")
.that(redrawCount[0]).isEqualTo(1)
assertWithMessage("Second items is expected to be redrawn")
.that(redrawCount[1]).isEqualTo(2)
}
}
@Test
fun notVisibleAnymoreItemNotAffectingCrossAxisSize() {
val itemSize = with(rule.density) { 30.toDp() }
val itemSizeMinusOne = with(rule.density) { 29.toDp() }
lateinit var state: TvLazyListState
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(
Modifier.mainAxisSize(itemSizeMinusOne).testTag(LazyListTag),
state = rememberTvLazyListState().also { state = it }
) {
items(2) {
Spacer(
if (it == 0) {
Modifier.crossAxisSize(30.dp).mainAxisSize(itemSizeMinusOne)
} else {
Modifier.crossAxisSize(20.dp).mainAxisSize(itemSize)
}
)
}
}
}
state.scrollBy(itemSize)
rule.onNodeWithTag(LazyListTag)
.assertCrossAxisSizeIsEqualTo(20.dp)
}
@Test
fun itemStillVisibleAfterOverscrollIsAffectingCrossAxisSize() {
val items = (0..2).toList()
val itemSize = with(rule.density) { 30.toDp() }
lateinit var state: TvLazyListState
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(
Modifier.mainAxisSize(itemSize * 1.75f).testTag(LazyListTag),
state = rememberTvLazyListState().also { state = it }
) {
items(items) {
Spacer(
if (it == 0) {
Modifier.crossAxisSize(30.dp).mainAxisSize(itemSize / 2)
} else if (it == 1) {
Modifier.crossAxisSize(20.dp).mainAxisSize(itemSize / 2)
} else {
Modifier.crossAxisSize(20.dp).mainAxisSize(itemSize)
}
)
}
}
}
state.scrollBy(itemSize)
rule.onNodeWithTag(LazyListTag)
.assertCrossAxisSizeIsEqualTo(30.dp)
}
@Test
fun usedWithArray() {
val items = arrayOf("1", "2", "3")
val itemSize = with(rule.density) { 15.toDp() }
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow {
items(items) {
Spacer(Modifier.requiredSize(itemSize).testTag(it))
}
}
}
rule.onNodeWithTag("1")
.assertStartPositionInRootIsEqualTo(0.dp)
rule.onNodeWithTag("2")
.assertStartPositionInRootIsEqualTo(itemSize)
rule.onNodeWithTag("3")
.assertStartPositionInRootIsEqualTo(itemSize * 2)
}
@Test
fun usedWithArrayIndexed() {
val items = arrayOf("1", "2", "3")
val itemSize = with(rule.density) { 15.toDp() }
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow {
itemsIndexed(items) { index, item ->
Spacer(Modifier.requiredSize(itemSize).testTag("$index*$item"))
}
}
}
rule.onNodeWithTag("0*1")
.assertStartPositionInRootIsEqualTo(0.dp)
rule.onNodeWithTag("1*2")
.assertStartPositionInRootIsEqualTo(itemSize)
rule.onNodeWithTag("2*3")
.assertStartPositionInRootIsEqualTo(itemSize * 2)
}
@Test
fun changeItemsCountAndScrollImmediately() {
lateinit var state: TvLazyListState
var count by mutableStateOf(100)
val composedIndexes = mutableListOf<Int>()
rule.setContent {
state = rememberTvLazyListState()
LazyColumnOrRow(Modifier.fillMaxCrossAxis().mainAxisSize(10.dp), state) {
items(count) { index ->
composedIndexes.add(index)
Box(Modifier.size(20.dp))
}
}
}
rule.runOnIdle {
composedIndexes.clear()
count = 10
runBlocking(AutoTestFrameClock()) {
state.scrollToItem(50)
}
composedIndexes.forEach {
assertThat(it).isLessThan(count)
}
assertThat(state.firstVisibleItemIndex).isEqualTo(9)
}
}
@Test
fun overscrollingBackwardFromNotTheFirstPosition() {
val containerTag = "container"
val itemSizePx = 10
val itemSizeDp = with(rule.density) { itemSizePx.toDp() }
val containerSize = itemSizeDp * 5
rule.setContentWithTestViewConfiguration {
Box(
Modifier
.testTag(containerTag)
.size(containerSize)
) {
LazyColumnOrRow(
Modifier
.testTag(LazyListTag)
.background(Color.Blue),
state = rememberTvLazyListState(2, 5)
) {
items(100) {
Box(
Modifier
.fillMaxCrossAxis()
.mainAxisSize(itemSizeDp)
.testTag("$it")
.focusable()
)
}
}
}
}
rule.keyPress(
if (vertical) NativeKeyEvent.KEYCODE_DPAD_UP else NativeKeyEvent.KEYCODE_DPAD_LEFT,
15
)
rule.onNodeWithTag(LazyListTag)
.assertMainAxisSizeIsEqualTo(containerSize)
rule.onNodeWithTag("0")
.assertStartPositionInRootIsEqualTo(0.dp)
rule.onNodeWithTag("4")
.assertStartPositionInRootIsEqualTo(containerSize - itemSizeDp)
}
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
@Test
fun doesNotClipHorizontalOverdraw() {
rule.setContent {
Box(Modifier.size(60.dp).testTag("container").background(Color.Gray)) {
LazyColumnOrRow(
Modifier
.padding(20.dp)
.fillMaxSize(),
rememberTvLazyListState(1)
) {
items(4) {
Box(Modifier.size(20.dp).drawOutsideOfBounds())
}
}
}
}
val horizontalPadding = if (vertical) 0.dp else 20.dp
val verticalPadding = if (vertical) 20.dp else 0.dp
rule.onNodeWithTag("container")
.captureToImage()
.assertShape(
density = rule.density,
shape = RectangleShape,
shapeColor = Color.Red,
backgroundColor = Color.Gray,
horizontalPadding = horizontalPadding,
verticalPadding = verticalPadding
)
}
@Test
fun initialScrollPositionIsCorrectWhenItemsAreLoadedAsynchronously() {
lateinit var state: TvLazyListState
var itemsCount by mutableStateOf(0)
rule.setContent {
state = rememberTvLazyListState(2, 10)
LazyColumnOrRow(Modifier.fillMaxSize(), state) {
items(itemsCount) {
Box(Modifier.size(20.dp))
}
}
}
rule.runOnIdle {
itemsCount = 100
}
rule.runOnIdle {
assertThat(state.firstVisibleItemIndex).isEqualTo(2)
assertThat(state.firstVisibleItemScrollOffset).isEqualTo(10)
}
}
@Test
fun restoredScrollPositionIsCorrectWhenItemsAreLoadedAsynchronously() {
lateinit var state: TvLazyListState
var itemsCount = 100
val recomposeCounter = mutableStateOf(0)
val tester = StateRestorationTester(rule)
tester.setContent {
state = rememberTvLazyListState()
LazyColumnOrRow(Modifier.fillMaxSize(), state) {
recomposeCounter.value
items(itemsCount) {
Box(Modifier.size(20.dp))
}
}
}
rule.runOnIdle {
runBlocking {
state.scrollToItem(2, 10)
}
itemsCount = 0
}
tester.emulateSavedInstanceStateRestore()
rule.runOnIdle {
itemsCount = 100
recomposeCounter.value = 1
}
rule.runOnIdle {
assertThat(state.firstVisibleItemIndex).isEqualTo(2)
assertThat(state.firstVisibleItemScrollOffset).isEqualTo(10)
}
}
@Test
fun animateScrollToItemDoesNotScrollPastItem() {
lateinit var state: TvLazyListState
var target = 0
var reverse = false
rule.setContent {
val listState = rememberTvLazyListState()
SideEffect {
state = listState
}
LazyColumnOrRow(Modifier.fillMaxSize(), listState) {
items(2500) { _ ->
Box(Modifier.size(100.dp))
}
}
if (reverse) {
assertThat(listState.firstVisibleItemIndex).isAtLeast(target)
} else {
assertThat(listState.firstVisibleItemIndex).isAtMost(target)
}
}
// Try a bunch of different targets with varying spacing
listOf(500, 800, 1500, 1600, 1800).forEach {
target = it
rule.runOnIdle {
runBlocking(AutoTestFrameClock()) {
state.animateScrollToItem(target)
}
}
rule.runOnIdle {
assertThat(state.firstVisibleItemIndex).isEqualTo(target)
assertThat(state.firstVisibleItemScrollOffset).isEqualTo(0)
}
}
reverse = true
listOf(1600, 1500, 800, 500, 0).forEach {
target = it
rule.runOnIdle {
runBlocking(AutoTestFrameClock()) {
state.animateScrollToItem(target)
}
}
rule.runOnIdle {
assertThat(state.firstVisibleItemIndex).isEqualTo(target)
assertThat(state.firstVisibleItemScrollOffset).isEqualTo(0)
}
}
}
@Test
fun animateScrollToTheLastItemWhenItemsAreLargerThenTheScreen() {
lateinit var state: TvLazyListState
rule.setContent {
state = rememberTvLazyListState()
LazyColumnOrRow(Modifier.crossAxisSize(150.dp).mainAxisSize(100.dp), state) {
items(20) {
Box(Modifier.size(150.dp))
}
}
}
// Try a bunch of different start indexes
listOf(0, 5, 12).forEach {
val startIndex = it
rule.runOnIdle {
runBlocking(AutoTestFrameClock()) {
state.scrollToItem(startIndex)
state.animateScrollToItem(19)
}
}
rule.runOnIdle {
assertThat(state.firstVisibleItemIndex).isEqualTo(19)
assertThat(state.firstVisibleItemScrollOffset).isEqualTo(0)
}
}
}
@Test
fun recreatingContentLambdaTriggersItemRecomposition() {
val countState = mutableStateOf(0)
rule.setContent {
val count = countState.value
LazyColumnOrRow {
item {
BasicText(text = "Count $count")
}
}
}
rule.onNodeWithText("Count 0")
.assertIsDisplayed()
rule.runOnIdle {
countState.value++
}
rule.onNodeWithText("Count 1")
.assertIsDisplayed()
}
@Test
fun semanticsScroll_isAnimated() {
rule.mainClock.autoAdvance = false
val state = TvLazyListState()
rule.setContent {
LazyColumnOrRow(Modifier.testTag(LazyListTag), state = state) {
items(50) {
Box(Modifier.mainAxisSize(200.dp))
}
}
}
rule.waitForIdle()
assertThat(state.firstVisibleItemIndex).isEqualTo(0)
assertThat(state.firstVisibleItemScrollOffset).isEqualTo(0)
rule.onNodeWithTag(LazyListTag).performSemanticsAction(SemanticsActions.ScrollBy) {
if (vertical) {
it(0f, 100f)
} else {
it(100f, 0f)
}
}
// We haven't advanced time yet, make sure it's still zero
assertThat(state.firstVisibleItemIndex).isEqualTo(0)
assertThat(state.firstVisibleItemScrollOffset).isEqualTo(0)
// Advance and make sure we're partway through
// Note that we need two frames for the animation to actually happen
rule.mainClock.advanceTimeByFrame()
rule.mainClock.advanceTimeByFrame()
// The items are 200dp each, so still the first one, but offset
assertThat(state.firstVisibleItemIndex).isEqualTo(0)
assertThat(state.firstVisibleItemScrollOffset).isGreaterThan(0)
assertThat(state.firstVisibleItemScrollOffset).isLessThan(100)
// Finish the scroll, make sure we're at the target
rule.mainClock.advanceTimeBy(5000)
assertThat(state.firstVisibleItemScrollOffset).isEqualTo(100)
}
@Test
fun maxIntElements() {
val itemSize = with(rule.density) { 15.toDp() }
rule.setContent {
LazyColumnOrRow(
modifier = Modifier.requiredSize(itemSize * 3),
state = TvLazyListState(firstVisibleItemIndex = Int.MAX_VALUE - 3)
) {
items(Int.MAX_VALUE) {
Box(Modifier.size(itemSize).testTag("$it"))
}
}
}
rule.onNodeWithTag("${Int.MAX_VALUE - 3}").assertStartPositionInRootIsEqualTo(0.dp)
rule.onNodeWithTag("${Int.MAX_VALUE - 2}").assertStartPositionInRootIsEqualTo(itemSize)
rule.onNodeWithTag("${Int.MAX_VALUE - 1}").assertStartPositionInRootIsEqualTo(itemSize * 2)
rule.onNodeWithTag("${Int.MAX_VALUE}").assertDoesNotExist()
rule.onNodeWithTag("0").assertDoesNotExist()
}
@Test
fun scrollingByExactlyTheItemSize_switchesTheFirstVisibleItem() {
val itemSize = with(rule.density) { 30.toDp() }
lateinit var state: TvLazyListState
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(
Modifier.mainAxisSize(itemSize * 3),
state = rememberTvLazyListState().also { state = it },
) {
items(5) {
Spacer(
Modifier.size(itemSize).testTag("$it")
)
}
}
}
state.scrollBy(itemSize)
rule.onNodeWithTag("0")
.assertIsNotDisplayed()
rule.runOnIdle {
assertThat(state.firstVisibleItemIndex).isEqualTo(1)
assertThat(state.firstVisibleItemScrollOffset).isEqualTo(0)
}
}
@Test
fun pointerInputScrollingIsAllowedWhenUserScrollingIsEnabled() {
val itemSize = with(rule.density) { 30.toDp() }
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(
Modifier.mainAxisSize(itemSize * 3).testTag(LazyListTag),
userScrollEnabled = true,
) {
items(5) {
Spacer(Modifier.size(itemSize).testTag("$it").focusable())
}
}
}
rule.keyPress(3)
rule.onNodeWithTag("1")
.assertStartPositionInRootIsEqualTo(0.dp)
}
@Test
fun pointerInputScrollingIsDisallowedWhenUserScrollingIsDisabled() {
val itemSize = with(rule.density) { 30.toDp() }
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(
Modifier.mainAxisSize(itemSize * 3).testTag(LazyListTag),
userScrollEnabled = false,
) {
items(5) {
Spacer(Modifier.size(itemSize).testTag("$it"))
}
}
}
rule.keyPress(1)
rule.onNodeWithTag("1")
.assertStartPositionInRootIsEqualTo(itemSize)
}
@Test
fun programmaticScrollingIsAllowedWhenUserScrollingIsDisabled() {
val itemSize = with(rule.density) { 30.toDp() }
lateinit var state: TvLazyListState
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(
Modifier.mainAxisSize(itemSize * 3),
state = rememberTvLazyListState().also { state = it },
userScrollEnabled = false,
) {
items(5) {
Spacer(Modifier.size(itemSize).testTag("$it"))
}
}
}
state.scrollBy(itemSize)
rule.onNodeWithTag("1")
.assertStartPositionInRootIsEqualTo(0.dp)
}
@Test
fun semanticScrollingIsDisallowedWhenUserScrollingIsDisabled() {
val itemSize = with(rule.density) { 30.toDp() }
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(
Modifier.mainAxisSize(itemSize * 3).testTag(LazyListTag),
userScrollEnabled = false,
) {
items(5) {
Spacer(Modifier.size(itemSize).testTag("$it"))
}
}
}
rule.onNodeWithTag(LazyListTag)
.assert(keyNotDefined(SemanticsActions.ScrollBy))
.assert(keyNotDefined(SemanticsActions.ScrollToIndex))
// but we still have a read only scroll range property
.assert(
keyIsDefined(
if (vertical) {
SemanticsProperties.VerticalScrollAxisRange
} else {
SemanticsProperties.HorizontalScrollAxisRange
}
)
)
}
@Test
fun withMissingItems() {
val itemSize = with(rule.density) { 30.toDp() }
lateinit var state: TvLazyListState
rule.setContent {
state = rememberTvLazyListState()
LazyColumnOrRow(
modifier = Modifier.mainAxisSize(itemSize + 1.dp),
state = state
) {
items(4) {
if (it != 1) {
Box(Modifier.size(itemSize).testTag(it.toString()).focusable())
}
}
}
}
rule.onNodeWithTag("0").assertIsDisplayed()
rule.onNodeWithTag("2").assertIsDisplayed()
rule.runOnIdle {
runBlocking {
state.scrollToItem(1)
}
}
rule.onNodeWithTag("0").assertIsNotDisplayed()
rule.onNodeWithTag("2").assertIsDisplayed()
rule.onNodeWithTag("3").assertIsDisplayed()
}
@Test
fun recomposingWithNewComposedModifierObjectIsNotCausingRemeasure() {
var remeasureCount = 0
val layoutModifier = Modifier.layout { measurable, constraints ->
remeasureCount++
val placeable = measurable.measure(constraints)
layout(placeable.width, placeable.height) {
placeable.place(0, 0)
}
}
val counter = mutableStateOf(0)
rule.setContentWithTestViewConfiguration {
counter.value // just to trigger recomposition
LazyColumnOrRow(
// this will return a new object everytime causing Lazy list recomposition
// without causing remeasure
Modifier.composed { layoutModifier }
) {
items(1) {
Spacer(Modifier.size(10.dp))
}
}
}
rule.runOnIdle {
assertThat(remeasureCount).isEqualTo(1)
counter.value++
}
rule.runOnIdle {
assertThat(remeasureCount).isEqualTo(1)
}
}
@Test
fun passingNegativeItemsCountIsNotAllowed() {
var exception: Exception? = null
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow {
try {
items(-1) {
Box(Modifier)
}
} catch (e: Exception) {
exception = e
}
}
}
rule.runOnIdle {
assertThat(exception).isInstanceOf(IllegalArgumentException::class.java)
}
}
@Test
fun scrollingALotDoesntCauseLazyLayoutRecomposition() {
var recomposeCount = 0
lateinit var state: TvLazyListState
rule.setContentWithTestViewConfiguration {
state = rememberTvLazyListState()
LazyColumnOrRow(
Modifier.composed {
recomposeCount++
Modifier
},
state
) {
items(1000) {
Spacer(Modifier.size(10.dp))
}
}
}
rule.runOnIdle {
assertThat(recomposeCount).isEqualTo(1)
runBlocking {
state.scrollToItem(100)
}
}
rule.runOnIdle {
assertThat(recomposeCount).isEqualTo(1)
}
}
@Test
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
fun zIndexOnItemAffectsDrawingOrder() {
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(
Modifier.size(6.dp).testTag(LazyListTag)
) {
items(listOf(Color.Blue, Color.Green, Color.Red)) { color ->
Box(
Modifier
.mainAxisSize(2.dp)
.crossAxisSize(6.dp)
.zIndex(if (color == Color.Green) 1f else 0f)
.drawBehind {
drawRect(
color,
topLeft = Offset(-10.dp.toPx(), -10.dp.toPx()),
size = Size(20.dp.toPx(), 20.dp.toPx())
)
})
}
}
}
rule.onNodeWithTag(LazyListTag)
.captureToImage()
.assertPixels { Color.Green }
}
@Test
fun increasingConstraintsWhenParentMaxSizeIsUsed_correctlyMaintainsThePosition() {
val state = TvLazyListState(1, 10)
var constraints by mutableStateOf(Constraints.fixed(100, 100))
rule.setContentWithTestViewConfiguration {
Layout(content = {
LazyColumnOrRow(state = state) {
items(3) {
Box(Modifier.fillParentMaxSize())
}
}
}) { measurables, _ ->
val placeable = measurables.first().measure(constraints)
layout(constraints.maxWidth, constraints.maxHeight) {
placeable.place(0, 0)
}
}
}
rule.runOnIdle {
constraints = Constraints.fixed(500, 500)
}
rule.runOnIdle {
assertThat(state.firstVisibleItemIndex).isEqualTo(1)
assertThat(state.firstVisibleItemScrollOffset).isEqualTo(10)
}
}
@Test
fun usingFillParentMaxSizeOnInfinityConstraintsIsIgnored() {
rule.setContentWithTestViewConfiguration {
Layout(content = {
LazyColumnOrRow {
items(1) {
Box(
Modifier
.fillParentMaxSize(0.95f)
.testTag("item"))
}
}
}) { measurables, _ ->
val crossInfinityConstraints = if (vertical) {
Constraints(maxWidth = Constraints.Infinity, maxHeight = 100)
} else {
Constraints(maxWidth = 100, maxHeight = Constraints.Infinity)
}
val placeable = measurables.first().measure(crossInfinityConstraints)
layout(placeable.width, placeable.height) {
placeable.place(0, 0)
}
}
}
rule.onNodeWithTag("item")
.assertMainAxisSizeIsEqualTo(with(rule.density) { (100 * 0.95f).roundToInt().toDp() })
.assertCrossAxisSizeIsEqualTo(0.dp)
}
@Test
fun fillingFullSize_nextItemIsNotComposed() {
val state = TvLazyListState()
state.prefetchingEnabled = false
val itemSizePx = 5f
val itemSize = with(rule.density) { itemSizePx.toDp() }
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(
Modifier
.testTag(LazyListTag)
.mainAxisSize(itemSize),
state = state
) {
items(3) { index ->
Box(fillParentMaxMainAxis().crossAxisSize(1.dp).testTag("$index"))
}
}
}
repeat(3) { index ->
rule.onNodeWithTag("$index")
.assertIsDisplayed()
rule.onNodeWithTag("${index + 1}")
.assertDoesNotExist()
rule.runOnIdle {
runBlocking {
state.scrollBy(itemSizePx)
}
}
}
}
@Test
fun fillingFullSize_crossAxisSizeOfVisibleItemIsUsed() {
val state = TvLazyListState()
val itemSizePx = 5f
val itemSize = with(rule.density) { itemSizePx.toDp() }
rule.setContentWithTestViewConfiguration {
LazyColumnOrRow(
Modifier
.testTag(LazyListTag)
.mainAxisSize(itemSize),
state = state
) {
items(5) { index ->
Box(fillParentMaxMainAxis().crossAxisSize(index.dp))
}
}
}
repeat(5) { index ->
rule.onNodeWithTag(LazyListTag)
.assertCrossAxisSizeIsEqualTo(index.dp)
rule.runOnIdle {
runBlocking {
state.scrollBy(itemSizePx)
}
}
}
}
// ********************* END OF TESTS *********************
// Helper functions, etc. live below here
companion object {
@JvmStatic
@Parameterized.Parameters(name = "{0}")
fun params() = arrayOf(Orientation.Vertical, Orientation.Horizontal)
}
}
internal val NeverEqualObject = object {
override fun equals(other: Any?): Boolean {
return false
}
}
private data class NotStable(val count: Int)
internal const val TestTouchSlop = 18f
internal fun IntegerSubject.isWithin1PixelFrom(expected: Int) {
isEqualTo(expected, 1)
}
internal fun IntegerSubject.isEqualTo(expected: Int, tolerance: Int) {
isIn(Range.closed(expected - tolerance, expected + tolerance))
}
internal fun ComposeContentTestRule.setContentWithTestViewConfiguration(
composable: @Composable () -> Unit
) {
this.setContent {
WithTouchSlop(TestTouchSlop, composable)
}
}
| tv/tv-foundation/src/androidTest/java/androidx/tv/foundation/lazy/list/LazyListTest.kt | 1878164103 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.datastore
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import java.io.File
class DataStoreFileTest {
@Test
fun testDataStoreFile() {
val context = ApplicationProvider.getApplicationContext<Context>()
val file = context.dataStoreFile("name")
val expectedFile = File(context.filesDir, "datastore/name")
assertThat(file.absolutePath).isEqualTo(expectedFile.absolutePath)
}
} | datastore/datastore/src/androidAndroidTest/kotlin/androidx/datastore/DataStoreFileTest.kt | 1981941949 |
package org.thoughtcrime.securesms.mediapreview
import org.thoughtcrime.securesms.database.MediaDatabase
import org.thoughtcrime.securesms.mediasend.Media
data class MediaPreviewV2State(
val mediaRecords: List<MediaDatabase.MediaRecord> = emptyList(),
val loadState: LoadState = LoadState.INIT,
val position: Int = 0,
val showThread: Boolean = false,
val allMediaInAlbumRail: Boolean = false,
val leftIsRecent: Boolean = false,
val albums: Map<Long, List<Media>> = mapOf(),
) {
enum class LoadState { INIT, DATA_LOADED, MEDIA_READY }
}
| app/src/main/java/org/thoughtcrime/securesms/mediapreview/MediaPreviewV2State.kt | 506358686 |
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.solver.shortcut.binderprovider
import androidx.room.compiler.processing.XType
import androidx.room.ext.GuavaUtilConcurrentTypeNames
import androidx.room.ext.L
import androidx.room.ext.N
import androidx.room.ext.RoomGuavaTypeNames
import androidx.room.ext.T
import androidx.room.processor.Context
import androidx.room.processor.ProcessorErrors
import androidx.room.solver.shortcut.binder.CallableInsertMethodBinder.Companion.createInsertBinder
import androidx.room.solver.shortcut.binder.InsertOrUpsertMethodBinder
import androidx.room.vo.ShortcutQueryParameter
/**
* Provider for Guava ListenableFuture binders.
*/
class GuavaListenableFutureInsertMethodBinderProvider(
private val context: Context
) : InsertOrUpsertMethodBinderProvider {
private val hasGuavaRoom by lazy {
context.processingEnv.findTypeElement(RoomGuavaTypeNames.GUAVA_ROOM) != null
}
override fun matches(declared: XType): Boolean =
declared.typeArguments.size == 1 &&
declared.rawType.typeName == GuavaUtilConcurrentTypeNames.LISTENABLE_FUTURE
override fun provide(
declared: XType,
params: List<ShortcutQueryParameter>
): InsertOrUpsertMethodBinder {
if (!hasGuavaRoom) {
context.logger.e(ProcessorErrors.MISSING_ROOM_GUAVA_ARTIFACT)
}
val typeArg = declared.typeArguments.first()
val adapter = context.typeAdapterStore.findInsertAdapter(typeArg, params)
return createInsertBinder(typeArg, adapter) { callableImpl, dbField ->
addStatement(
"return $T.createListenableFuture($N, $L, $L)",
RoomGuavaTypeNames.GUAVA_ROOM,
dbField,
"true", // inTransaction
callableImpl
)
}
}
} | room/room-compiler/src/main/kotlin/androidx/room/solver/shortcut/binderprovider/GuavaListenableFutureInsertMethodBinderProvider.kt | 1919032315 |
// FIR_IDENTICAL
fun refs() {
var <warning>a</warning> = 1
val <warning>v</warning> = {
<info>a</info> = 2
}
var <warning>x</warning> = 1
val <warning>b</warning> = object {
fun foo() {
<info>x</info> = 2
}
}
var <warning>y</warning> = 1
fun foo() {
<info>y</info> = 1
}
}
fun refsPlusAssign() {
var a = 1
val <warning>v</warning> = {
<info>a</info> += 2
}
var x = 1
val <warning>b</warning> = object {
fun foo() {
<info>x</info> += 2
}
}
var y = 1
fun foo() {
<info>y</info> += 1
}
}
| plugins/kotlin/idea/tests/testData/checker/infos/WrapIntoRef.kt | 1418652500 |
// WITH_STDLIB
// INTENTION_TEXT: "Remove return@forEach"
fun foo() {
listOf(1,2,3).forEach {
<caret>return@forEach
}
} | plugins/kotlin/idea/tests/testData/intentions/removeLabeledReturnInLambda/unit.kt | 869967471 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.gradleJava.configuration.kpm
import com.intellij.openapi.diagnostic.Logger
import org.jetbrains.kotlin.gradle.kpm.idea.IdeaKpmProject
import org.jetbrains.kotlin.gradle.kpm.idea.serialize.IdeaKpmExtrasSerializationExtension
import org.jetbrains.kotlin.gradle.kpm.idea.serialize.IdeaKpmExtrasSerializer
import org.jetbrains.kotlin.gradle.kpm.idea.serialize.IdeaKpmSerializationContext
import org.jetbrains.kotlin.gradle.kpm.idea.serialize.IdeaKpmSerializationLogger
import org.jetbrains.kotlin.gradle.kpm.idea.serialize.IdeaKpmSerializationLogger.Severity.ERROR
import org.jetbrains.kotlin.gradle.kpm.idea.serialize.IdeaKpmSerializationLogger.Severity.WARNING
import org.jetbrains.kotlin.idea.gradle.configuration.kpm.ExtrasSerializationService
import org.jetbrains.kotlin.idea.gradleTooling.serialization.IdeaKpmProjectDeserializer
import org.jetbrains.kotlin.kpm.idea.proto.IdeaKpmProject
import org.jetbrains.kotlin.tooling.core.Extras
class IdeaKpmProjectDeserializerImpl : IdeaKpmProjectDeserializer {
override fun read(data: ByteArray): IdeaKpmProject? {
return IdeaKpmSerializationContextImpl().IdeaKpmProject(data)
}
}
private class IdeaKpmSerializationContextImpl : IdeaKpmSerializationContext {
override val logger: IdeaKpmSerializationLogger = IntellijIdeaKpmSerializationLogger
override val extrasSerializationExtension: IdeaKpmExtrasSerializationExtension = IdeaKpmCompositeExtrasSerializationExtension(
ExtrasSerializationService.EP_NAME.extensionList.map { it.extension }
)
}
private object IntellijIdeaKpmSerializationLogger : IdeaKpmSerializationLogger {
val logger = Logger.getInstance(IntellijIdeaKpmSerializationLogger::class.java)
override fun report(severity: IdeaKpmSerializationLogger.Severity, message: String, cause: Throwable?) {
when (severity) {
WARNING -> logger.warn(message, cause)
ERROR -> logger.error(message, cause)
else -> logger.warn(message, cause)
}
}
}
private class IdeaKpmCompositeExtrasSerializationExtension(
private val extensions: List<IdeaKpmExtrasSerializationExtension>
) : IdeaKpmExtrasSerializationExtension {
override fun <T : Any> serializer(key: Extras.Key<T>): IdeaKpmExtrasSerializer<T>? {
val serializers = extensions.mapNotNull { it.serializer(key) }
if (serializers.isEmpty()) return null
if (serializers.size == 1) return serializers.single()
IntellijIdeaKpmSerializationLogger.error(
"Conflicting serializers for $key: $serializers"
)
return null
}
}
| plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/kpm/IdeaKpmProjectDeserializerImpl.kt | 3814616323 |
// 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.openapi.ui.validation
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.observable.properties.GraphProperty
import com.intellij.openapi.observable.properties.ObservableProperty
import com.intellij.openapi.observable.properties.PropertyGraph
import com.intellij.openapi.observable.util.whenDisposed
import com.intellij.openapi.observable.util.whenStateChanged
import com.intellij.openapi.observable.util.whenTextChanged
import com.intellij.ui.EditorTextField
import java.awt.ItemSelectable
import javax.swing.text.JTextComponent
val WHEN_TEXT_CHANGED = DialogValidationRequestor.WithParameter<JTextComponent> { textComponent ->
DialogValidationRequestor { parentDisposable, validate ->
textComponent.whenTextChanged(parentDisposable) { validate() }
}
}
val WHEN_TEXT_FIELD_TEXT_CHANGED = DialogValidationRequestor.WithParameter<EditorTextField> { textComponent ->
DialogValidationRequestor { parentDisposable, validate ->
val listener = object : DocumentListener {
override fun documentChanged(event: DocumentEvent) {
validate()
}
}
textComponent.addDocumentListener(listener)
parentDisposable?.whenDisposed { textComponent.removeDocumentListener(listener) }
}
}
val WHEN_STATE_CHANGED = DialogValidationRequestor.WithParameter<ItemSelectable> { component ->
DialogValidationRequestor { parentDisposable, validate ->
component.whenStateChanged(parentDisposable) { validate() }
}
}
val AFTER_GRAPH_PROPAGATION = DialogValidationRequestor.WithParameter<PropertyGraph> { graph ->
DialogValidationRequestor { parentDisposable, validate ->
graph.afterPropagation(parentDisposable, validate)
}
}
val AFTER_PROPERTY_PROPAGATION = DialogValidationRequestor.WithParameter<GraphProperty<*>> { property ->
DialogValidationRequestor { parentDisposable, validate ->
property.afterPropagation(parentDisposable, validate)
}
}
val AFTER_PROPERTY_CHANGE = DialogValidationRequestor.WithParameter<ObservableProperty<*>> { property ->
DialogValidationRequestor { parentDisposable, validate ->
property.afterChange(parentDisposable) { validate() }
}
} | platform/platform-impl/src/com/intellij/openapi/ui/validation/requestors.kt | 2131735358 |
// FIR_COMPARISON
package some
fun other() {
val v = "$somePr<caret>"
}
| plugins/kotlin/completion/tests/testData/handlers/multifile/TopLevelValImportInStringTemplate-1.kt | 2676968503 |
// PROBLEM: none
// LANGUAGE_VERSION: 1.7
import java.io.Serializable
object<caret> Foo : Serializable | plugins/kotlin/idea/tests/testData/inspectionsLocal/convertObjectToDataObject/languageLevelIsTooLow.kt | 3751273155 |