content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
// 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.formatter.trailingComma import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.util.containsLineBreakInChild import org.jetbrains.kotlin.idea.util.isMultiline import org.jetbrains.kotlin.psi.KtDestructuringDeclaration import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFunctionLiteral import org.jetbrains.kotlin.psi.KtWhenEntry import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset enum class TrailingCommaState { /** * The trailing comma is needed and exists */ EXISTS, /** * The trailing comma is needed and doesn't exists */ MISSING, /** * The trailing comma isn't needed and doesn't exists */ NOT_EXISTS, /** * The trailing comma isn't needed, but exists */ REDUNDANT, /** * The trailing comma isn't applicable for this element */ NOT_APPLICABLE, ; companion object { fun stateForElement(element: PsiElement): TrailingCommaState = when { element !is KtElement || !element.canAddTrailingComma() -> NOT_APPLICABLE isMultiline(element) -> if (TrailingCommaHelper.trailingCommaExists(element)) EXISTS else MISSING else -> if (TrailingCommaHelper.trailingCommaExists(element)) REDUNDANT else NOT_EXISTS } } } private fun isMultiline(ktElement: KtElement): Boolean = when { ktElement.parent is KtFunctionLiteral -> isMultiline(ktElement.parent as KtElement) ktElement is KtFunctionLiteral -> ktElement.isMultiline( startOffsetGetter = { valueParameterList?.startOffset }, endOffsetGetter = { arrow?.endOffset }, ) ktElement is KtWhenEntry -> ktElement.isMultiline( startOffsetGetter = { startOffset }, endOffsetGetter = { arrow?.endOffset }, ) ktElement is KtDestructuringDeclaration -> ktElement.isMultiline( startOffsetGetter = { lPar?.startOffset }, endOffsetGetter = { rPar?.endOffset }, ) else -> ktElement.isMultiline() } private fun <T : PsiElement> T.isMultiline( startOffsetGetter: T.() -> Int?, endOffsetGetter: T.() -> Int?, ): Boolean { val startOffset = startOffsetGetter() ?: startOffset val endOffset = endOffsetGetter() ?: endOffset return containsLineBreakInChild(startOffset, endOffset) }
plugins/kotlin/formatter/src/org/jetbrains/kotlin/idea/formatter/trailingComma/TrailingCommaState.kt
4294509083
fun foo() { 1 <caret>foo 1 } fun Int.foo(i: Int) = 1 // DISALLOW_METHOD_CALLS // EXPECTED: null
plugins/kotlin/jvm-debugger/test/testData/selectExpression/disallowMethodCalls/infixCall.kt
1325832155
// 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.intentions import java.io.File abstract class AbstractK1IntentionTest2 : AbstractK1IntentionTest() { override fun intentionFileName() = ".intention2" override fun afterFileNameSuffix(ktFilePath: File) = ".after2" override fun intentionTextDirectiveName() = "INTENTION_TEXT_2" override fun isApplicableDirectiveName() = "IS_APPLICABLE_2" }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/intentions/AbstractK1IntentionTest2.kt
643100829
/* * 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.diagnostic.hprof.visitors import com.intellij.diagnostic.hprof.classstore.ThreadInfo import com.intellij.diagnostic.hprof.navigator.RootReason import com.intellij.diagnostic.hprof.parser.HProfVisitor import com.intellij.diagnostic.hprof.parser.HeapDumpRecordType import it.unimi.dsi.fastutil.longs.Long2ObjectMap import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap class CollectRootReasonsVisitor(private val threadsMap: Long2ObjectMap<ThreadInfo>) : HProfVisitor() { val roots = Long2ObjectOpenHashMap<RootReason>() override fun preVisit() { disableAll() enable(HeapDumpRecordType.RootGlobalJNI) enable(HeapDumpRecordType.RootJavaFrame) enable(HeapDumpRecordType.RootLocalJNI) enable(HeapDumpRecordType.RootMonitorUsed) enable(HeapDumpRecordType.RootNativeStack) enable(HeapDumpRecordType.RootStickyClass) enable(HeapDumpRecordType.RootThreadBlock) enable(HeapDumpRecordType.RootThreadObject) enable(HeapDumpRecordType.RootUnknown) } override fun visitRootUnknown(objectId: Long) { roots.put(objectId, RootReason.rootUnknown) } override fun visitRootGlobalJNI(objectId: Long, jniGlobalRefId: Long) { roots.put(objectId, RootReason.rootGlobalJNI) } override fun visitRootLocalJNI(objectId: Long, threadSerialNumber: Long, frameNumber: Long) { roots.put(objectId, RootReason.rootLocalJNI) } override fun visitRootJavaFrame(objectId: Long, threadSerialNumber: Long, frameNumber: Long) { val rootReason = if (frameNumber >= 0) { RootReason.createJavaFrameReason(threadsMap[threadSerialNumber].frames[frameNumber.toInt()]) } else { RootReason.createJavaFrameReason("Unknown location") } // Java frame has a lower priority - if won't override any other GC-root reasons. if (!roots.containsKey(objectId)) { roots.put(objectId, rootReason) } } override fun visitRootNativeStack(objectId: Long, threadSerialNumber: Long) { roots.put(objectId, RootReason.rootNativeStack) } override fun visitRootStickyClass(objectId: Long) { roots.put(objectId, RootReason.rootStickyClass) } override fun visitRootThreadBlock(objectId: Long, threadSerialNumber: Long) { roots.put(objectId, RootReason.rootThreadBlock) } override fun visitRootThreadObject(objectId: Long, threadSerialNumber: Long, stackTraceSerialNumber: Long) { roots.put(objectId, RootReason.rootThreadObject) } override fun visitRootMonitorUsed(objectId: Long) { roots.put(objectId, RootReason.rootMonitorUsed) } }
platform/platform-impl/src/com/intellij/diagnostic/hprof/visitors/CollectRootReasonsVisitor.kt
1412333296
// "Generate 'hashCode()'" "true" // WITH_STDLIB interface I abstract class A { abstract override fun hashCode(): Int abstract override fun equals(other: Any?): Boolean } class B : A(), I { override fun equals(other: Any?): Boolean { return super.equals(other) } override fun hashCode(): Int { return super.<caret>hashCode() } }
plugins/kotlin/idea/tests/testData/quickfix/specifySuperExplicitly/abstractSuperCallHashCode.kt
999033567
package com.cc.io import com.cc.util.logd import com.cc.util.loge import com.cc.util.logi import com.cc.util.logv import org.apache.tools.tar.TarEntry import org.apache.tools.tar.TarInputStream import java.io.* import java.util.zip.GZIPInputStream /** * Created by clevercong on 2017/10/21. * 压缩/解压缩相关的操作在此。 */ class ZipManager { val fileExtensionGz = "gz" val fileExtensionTarGz = "tar.gz" /** * 解压文件总入口,根据后缀的不同调用不同的私有方法,目前正在完善中 * @param sourceDir 文件的路径 * @param outputDir 解压的路径 * @param extension 文件的后缀 */ fun unzip(sourceDir: String, outputDir: String, extension: String) { logv("unzip, sourceDir:$sourceDir, outputDir:$outputDir, ext:$extension") when (extension) { // 这个地方可能比较奇怪,是因为.tar.gz格式的文件extension字段只能识别为.gz // 所以.gz格式的按照.tar.gz进行解压缩 // 而我又觉得解压缩.gz的代码来之不易(虽然没有调试过)。不想删啊。万一以后用到了呢。 // 2018.09.02:果然用到了,这里根据sourceDir是否包含tar.gz,用来区分tar.gz和gz的区别 fileExtensionGz -> if (sourceDir.indexOf(fileExtensionTarGz) != -1) { // 找到了tar.gz,按照tag.gz的解析 unzipForTarGz(sourceDir, outputDir) } else { // 否则按照.gz的来解析 unzipForGz(sourceDir, outputDir) } } } /** * 解压GZ文件 * 代码来源:http://www.cnblogs.com/scw2901/p/4379143.html * 惊人的发现竟然支持剪贴板Java到Kotlin的自动转换。那就不客气了。 * @param sourceDir 压缩文件路径 * @param outputFile 解压的路径 */ private fun unzipForGz(sourceDir: String, outputFile: String) { //var outputFile: String try { //建立gzip压缩文件输入流 val fin = FileInputStream(sourceDir) //建立gzip解压工作流 val gzin = GZIPInputStream(fin) //建立解压文件输出流 //outputFile = sourceDir.substring(0, sourceDir.lastIndexOf('.')) //outputFile = outputFile.substring(0, outputFile.lastIndexOf('.')) val fout = FileOutputStream(outputFile) val buf = ByteArray(1024) var num: Int = gzin.read(buf, 0, buf.size) while (num != -1) { fout.write(buf, 0, num) num = gzin.read(buf, 0, buf.size) } gzin.close() fout.close() fin.close() } catch (ex: Exception) { ex.printStackTrace() } } /** * 解压TAR_GZ文件 * @param sourceDir 压缩文件路径 * @param outputDir 输出路径 */ private fun unzipForTarGz(sourceDir: String, outputDir: String) { var tarIn: TarInputStream? = null try { tarIn = TarInputStream(GZIPInputStream( BufferedInputStream(FileInputStream(sourceDir))), 1024 * 2) createDirectory(outputDir, null) // 创建输出目录 var entry: TarEntry? = tarIn.nextEntry while (entry != null) { if (entry.isDirectory) { // 是目录 createDirectory(outputDir, entry.name) // 创建空目录 } else { // 是文件 val tmpFile = File(outputDir + "/" + entry.name) createDirectory(tmpFile.parent + "/", null)//创建输出目录 var out: OutputStream? = null try { out = FileOutputStream(tmpFile) val b = ByteArray(2048) var length = tarIn.read(b) while (length != -1) { out.write(b, 0, length) length = tarIn.read(b) } } catch (ex: IOException) { ex.printStackTrace() } finally { if (out != null) { out.close() } } } entry = tarIn.nextEntry } logv("解压缩" + sourceDir + "成功!") } catch (ex: IOException) { // ex.printStackTrace() loge("解压缩" + sourceDir + "失败!, ex = " + ex) } finally { try { if (tarIn != null) { tarIn.close() } } catch (ex: IOException) { // ex.printStackTrace() loge("关闭TarInputStream失败!, ex = " + ex) } } } private fun createDirectory(outputDir: String, subDir: String?) { var file = File(outputDir) if (!(subDir == null || subDir.trim { it <= ' ' } == "")) { // 子目录不为空 file = File("$outputDir/$subDir") } if (!file.exists()) { if (!file.parentFile.exists()) file.parentFile.mkdirs() file.mkdirs() } } }
src/com/cc/io/ZipManager.kt
3177677836
fun check() { println(1.0 <caret>.toString() ) } // SET_FALSE: ALIGN_MULTILINE_PARAMETERS_IN_CALLS
plugins/kotlin/idea/tests/testData/editor/enterHandler/beforeDot/FloatLiteralInFirstPositionAfterParenthesis.after.kt
621481032
/* * SampleSubscription.kt * * This file is part of FareBot. * Learn more at: https://codebutler.github.io/farebot/ * * Copyright (C) 2017 Eric Butler <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.codebutler.farebot.app.core.sample import android.content.res.Resources import com.codebutler.farebot.app.core.kotlin.date import com.codebutler.farebot.transit.Subscription import java.util.Date class SampleSubscription : Subscription() { override fun getId(): Int = 1 override fun getValidFrom(): Date = date(2017, 6) override fun getValidTo(): Date = date(2017, 7) override fun getAgencyName(resources: Resources): String = "Municipal Robot Railway" override fun getShortAgencyName(resources: Resources): String = "Muni" override fun getMachineId(): Int = 1 override fun getSubscriptionName(resources: Resources): String = "Monthly Pass" override fun getActivation(): String = "" }
farebot-app/src/main/java/com/codebutler/farebot/app/core/sample/SampleSubscription.kt
3292039991
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.network.selector import kotlinx.cinterop.* import platform.darwin.* import platform.posix.* import kotlin.Byte internal actual fun pselectBridge( descriptor: Int, readSet: CPointer<fd_set>, writeSet: CPointer<fd_set>, errorSet: CPointer<fd_set> ): Int = pselect(descriptor, readSet, writeSet, errorSet, null, null) internal actual fun inetNtopBridge( type: Int, address: CPointer<*>, addressOf: CPointer<*>, size: Int ) { @Suppress("UNCHECKED_CAST") inet_ntop(type, address, addressOf as CPointer<ByteVarOf<Byte>>, size.convert()) }
ktor-network/darwin/src/io/ktor/network/selector/SelectUtilsDarwin.kt
2979009274
package lt.markmerkk.widgets.settings import lt.markmerkk.JiraClientProvider import lt.markmerkk.Tags import lt.markmerkk.UserSettings import lt.markmerkk.interactors.JiraBasicApi import net.rcarz.jiraclient.JiraApi import org.slf4j.LoggerFactory import rx.Completable import rx.Scheduler import rx.Single import rx.Subscription class OAuthAuthorizator( private val view: View, private val oAuthInteractor: OAuthInteractor, private val jiraClientProvider: JiraClientProvider, private val jiraApi: JiraBasicApi, private val userSettings: UserSettings, private val ioScheduler: Scheduler, private val uiScheduler: Scheduler ) { private var subsCheckConnection: Subscription? = null private var subsAuth1: Subscription? = null private var subsAuth2: Subscription? = null fun onAttach() { val jiraUser = userSettings.jiraUser() if (jiraUser.isEmpty() || userSettings.jiraOAuthCreds().isEmpty()) { view.renderView(AuthViewModel( showContainerWebview = false, showContainerStatus = true, showStatusEmoticon = AuthViewModel.StatusEmoticon.SAD, textStatus = "No user connected!", showButtonSetupNew = true )) } else { view.renderView(AuthViewModel( showContainerWebview = false, showContainerStatus = true, showStatusEmoticon = AuthViewModel.StatusEmoticon.NEUTRAL, textStatus = "Welcome '${jiraUser.displayName}'!", showButtonSetupNew = true )) } } fun onDetach() { subsCheckConnection?.unsubscribe() subsAuth1?.unsubscribe() subsAuth2?.unsubscribe() view.resetWeb() } fun checkAuth() { subsCheckConnection?.unsubscribe() subsCheckConnection = jiraApi.jiraUser() .doOnSuccess { userSettings.changeJiraUser(it.name, it.email, it.displayName, it.accountId) } .doOnError { userSettings.resetUserData() } .subscribeOn(ioScheduler) .observeOn(uiScheduler) .doOnSubscribe { view.showProgress() } .doAfterTerminate { view.hideProgress() } .subscribe({ view.renderView(AuthViewModel( showContainerWebview = false, showContainerStatus = true, showStatusEmoticon = AuthViewModel.StatusEmoticon.HAPPY, textStatus = "Welcome '${it.displayName}'!", showButtonSetupNew = false )) view.accountReady() }, { logger.warn("Error trying to establish connection!", it) view.renderView(AuthViewModel( showContainerWebview = false, showContainerStatus = true, showStatusEmoticon = AuthViewModel.StatusEmoticon.SAD, textStatus = "Error connecting to JIRA. Press 'Show logs' for more details!", showButtonSetupNew = true )) }) } fun setupAuthStep1() { logger.debug("Authorization STEP 1") subsAuth1?.unsubscribe() userSettings.resetUserData() subsAuth1 = oAuthInteractor.generateAuthUrl() .subscribeOn(ioScheduler) .observeOn(uiScheduler) .doOnSubscribe { view.showProgress() } .doOnSuccess { view.hideProgress() } .doOnError { view.hideProgress() } .subscribe({ logger.debug("Loading authorization URL") view.renderView(AuthViewModel( showContainerWebview = true, showContainerStatus = false, showStatusEmoticon = AuthViewModel.StatusEmoticon.NEUTRAL, textStatus = "", showButtonSetupNew = false )) view.loadAuthWeb(it) }, { logger.debug("Error trying to generate token for authorization", it) view.renderView(AuthViewModel( showContainerWebview = false, showContainerStatus = true, showStatusEmoticon = AuthViewModel.StatusEmoticon.SAD, textStatus = "Error generating JIRA token. Press 'Show logs' for more info!", showButtonSetupNew = true )) }) } fun setupAuthStep2(accessTokenKey: String) { subsAuth2?.unsubscribe() view.renderView(AuthViewModel( showContainerWebview = false, showContainerStatus = true, showStatusEmoticon = AuthViewModel.StatusEmoticon.NEUTRAL, textStatus = "Finishing up authorization...", showButtonSetupNew = false )) if (accessTokenKey.isEmpty()) { userSettings.resetUserData() logger.debug("Error getting access token key") view.renderView(AuthViewModel( showContainerWebview = false, showContainerStatus = true, showStatusEmoticon = AuthViewModel.StatusEmoticon.SAD, textStatus = "Error generating JIRA token. Press 'Show logs' for more info", showButtonSetupNew = true )) return } logger.debug("Success finding '$accessTokenKey'") subsAuth2 = oAuthInteractor.generateToken(accessTokenKey) .flatMap { userSettings.changeOAuthCreds( tokenSecret = it.tokenSecret, accessKey = it.accessKey ) Single.just(jiraClientProvider.newClient()) }.flatMap { jiraApi.jiraUser() } .doOnSuccess { userSettings.changeJiraUser(it.name, it.email, it.displayName, it.accountId) } .doOnError { userSettings.resetUserData() } .subscribeOn(ioScheduler) .observeOn(uiScheduler) .doOnSubscribe { view.showProgress() } .doAfterTerminate { view.hideProgress() } .subscribe({ logger.debug("Success running authorization, found projects: $it") view.renderView(AuthViewModel( showContainerWebview = false, showContainerStatus = true, showStatusEmoticon = AuthViewModel.StatusEmoticon.HAPPY, textStatus = "Welcome '${it.displayName}'!", showButtonSetupNew = false )) view.accountReady() }, { logger.warn("Error finalizing JIRA token export!", it) view.renderView(AuthViewModel( showContainerWebview = false, showContainerStatus = true, showStatusEmoticon = AuthViewModel.StatusEmoticon.SAD, textStatus = "Error generating JIRA token. Press 'Show logs' for more info", showButtonSetupNew = true )) }) } interface View { fun accountReady() fun renderView(authViewModel: AuthViewModel) fun showProgress() fun hideProgress() fun loadAuthWeb(url: String) fun resetWeb() } companion object { private val logger = LoggerFactory.getLogger(Tags.JIRA)!! } }
app/src/main/java/lt/markmerkk/widgets/settings/OAuthAuthorizator.kt
2458766811
package com.xiasuhuei321.gankkotlin.base import android.os.Bundle import android.view.LayoutInflater import android.view.View import com.xiasuhuei321.gankkotlin.R import kotlinx.android.synthetic.main.activity_base_toolbar.* open class BaseToolbarActivity : BaseActivity() { override val initBySelf: Boolean get() = true override val hideActionBar: Boolean get() = true var total = 0 var current = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) super.setContentView(R.layout.activity_base_toolbar) setSupportActionBar(toolbar) } override fun setContentView(layoutResID: Int) { val v = LayoutInflater.from(this).inflate(layoutResID, rootLl, false) rootLl.addView(v) initView() } protected fun setBackBtn() { supportActionBar?.setDisplayHomeAsUpEnabled(true) toolbar.setNavigationOnClickListener { onBackPressed() } } protected fun initToolbar(title: String) { supportActionBar?.title = title } protected fun initCountTv(total: Int) { countTv.visibility = View.VISIBLE this.total = total setCurrent(current, total) } protected fun setCurrent(current: Int, total: Int = this.total) { this.current = current countTv.text = "${current} / ${total}" } }
app/src/main/java/com/xiasuhuei321/gankkotlin/base/BaseToolbarActivity.kt
68267703
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.accompanist.insets import android.os.Bundle import androidx.activity.ComponentActivity import androidx.core.view.WindowCompat /** * [ComponentActivity] which automatically requests for the decor not to fit system windows. */ class InsetsTestActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) WindowCompat.setDecorFitsSystemWindows(window, false) } }
insets/src/sharedTest/kotlin/com/google/accompanist/insets/InsetsTestActivity.kt
186969912
package ru.santaev.clipboardtranslator.domain.repository import com.example.santaev.domain.api.IApiService import com.example.santaev.domain.api.LanguagesResponseDto import com.example.santaev.domain.database.ILanguageDao import com.example.santaev.domain.repository.ILanguageRepository import com.example.santaev.domain.repository.ILanguageRepository.LanguagesState.* import com.example.santaev.domain.repository.LanguageRepository import io.reactivex.Single import org.junit.Test import org.mockito.Mockito import java.util.concurrent.TimeUnit class LanguagesRepositoryTest { @Test fun testRequestLanguagesError() { val languagesDao = Mockito.mock(ILanguageDao::class.java) val apiService = Mockito.mock(IApiService::class.java) val error: Single<LanguagesResponseDto> = Single .error<LanguagesResponseDto>(Exception()) .delaySubscription(100, TimeUnit.MILLISECONDS) Mockito .`when`(apiService.getLanguages()) .thenReturn(error) val repository: ILanguageRepository = LanguageRepository(languagesDao, apiService) val testObserver = repository .requestLanguages() .test() testObserver.awaitCount(1) testObserver.assertValue(ERROR) } @Test fun testRequestLanguagesSuccess() { val languagesDao = Mockito.mock(ILanguageDao::class.java) val apiService = Mockito.mock(IApiService::class.java) val success: Single<LanguagesResponseDto> = Single .just(LanguagesResponseDto(listOf(), listOf())) .delaySubscription(100, TimeUnit.MILLISECONDS) Mockito .`when`(apiService.getLanguages()) .thenReturn(success) val repository: ILanguageRepository = LanguageRepository(languagesDao, apiService) val testObserver = repository .requestLanguages() .test() testObserver.awaitCount(1) testObserver.assertValue(SUCCESS) } @Test fun testRequestLanguagesDoubleCall() { val languagesDao = Mockito.mock(ILanguageDao::class.java) val apiService = Mockito.mock(IApiService::class.java) val error: Single<LanguagesResponseDto> = Single .error<LanguagesResponseDto>(Exception()) .delaySubscription(100, TimeUnit.MILLISECONDS) val success: Single<LanguagesResponseDto> = Single .just(LanguagesResponseDto(listOf(), listOf())) .delaySubscription(100, TimeUnit.MILLISECONDS) Mockito .`when`(apiService.getLanguages()) .thenReturn(error) val repository: ILanguageRepository = LanguageRepository(languagesDao, apiService) val testObserver = repository .requestLanguages() .test() testObserver.awaitCount(1) // Retry to load languages Mockito .`when`(apiService.getLanguages()) .thenReturn(success) repository .requestLanguages() .subscribe() testObserver.awaitCount(3) testObserver.assertValues(ERROR, LOADING, SUCCESS) } }
domain/src/test/kotlin/ru/santaev/clipboardtranslator/domain/repository/LanguagesRepositoryTest.kt
2290845642
package com.czbix.v2ex.inject import javax.inject.Scope @Scope @Retention(AnnotationRetention.RUNTIME) annotation class ActivityScoped @Scope @Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.TYPE, AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) annotation class FragmentScoped
app/src/main/kotlin/com/czbix/v2ex/inject/Scoped.kt
3936448427
/* * 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.util.converters import io.ktor.util.reflect.* import kotlin.reflect.* /** * Data conversion service that does serialization and deserialization to/from list of strings */ public interface ConversionService { /** * Deserialize [values] to an instance of [type] */ public fun fromValues(values: List<String>, type: TypeInfo): Any? /** * Serialize a [value] to values list */ public fun toValues(value: Any?): List<String> } /** * The default conversion service that supports only basic types and enums */ public object DefaultConversionService : ConversionService { override fun toValues(value: Any?): List<String> { if (value == null) { return emptyList() } val converted = platformDefaultToValues(value) if (converted != null) { return converted } return when (value) { is Iterable<*> -> value.flatMap { toValues(it) } else -> { when (val klass = value::class) { Int::class, Float::class, Double::class, Long::class, Short::class, Char::class, Boolean::class, String::class -> listOf(value.toString()) else -> throw DataConversionException( "Class $klass is not supported in default data conversion service" ) } } } } override fun fromValues(values: List<String>, type: TypeInfo): Any? { if (values.isEmpty()) { return null } if (type.type == List::class || type.type == MutableList::class) { val argumentType = type.kotlinType?.arguments?.single()?.type?.classifier as? KClass<*> if (argumentType != null) { return values.map { fromValue(it, argumentType) } } } when { values.isEmpty() -> throw DataConversionException("There are no values when trying to construct single value $type") values.size > 1 -> throw DataConversionException("There are multiple values when trying to construct single value $type") else -> return fromValue(values.single(), type.type) } } public fun fromValue(value: String, klass: KClass<*>): Any { val converted = convertPrimitives(klass, value) if (converted != null) { return converted } val platformConverted = platformDefaultFromValues(value, klass) if (platformConverted != null) { return platformConverted } throwConversionException(klass.toString()) } private fun convertPrimitives(klass: KClass<*>, value: String) = when (klass) { Int::class -> value.toInt() Float::class -> value.toFloat() Double::class -> value.toDouble() Long::class -> value.toLong() Short::class -> value.toShort() Char::class -> value.single() Boolean::class -> value.toBoolean() String::class -> value else -> null } private fun throwConversionException(typeName: String): Nothing { throw DataConversionException("Type $typeName is not supported in default data conversion service") } } internal expect fun platformDefaultFromValues(value: String, klass: KClass<*>): Any? internal expect fun platformDefaultToValues(value: Any): List<String>? /** * Thrown when failed to convert value */ public open class DataConversionException(message: String = "Invalid data format") : Exception(message)
ktor-utils/common/src/io/ktor/util/converters/ConversionService.kt
3260056298
package generic import generic.java_generic.bean.Apple import generic.java_generic.bean.Food import generic.java_generic.bean.Fruit import generic.java_generic.bean.Pear /** * Desc: Kotlin泛型协变(out)、逆变(in) * * <p> * * 关于Java泛型的协变、逆变可以查看JavaGenericWildcardTest里面有详细的介绍 * * Kotlin同样也有泛型的协变、逆变,他们之间的概念是一致的,但是在声明上有些差异: * * Java是在声明变量的时候声明泛型协变、逆变的,不能再声明类的时候声明泛型协变、逆变(如Collections.copy函数源码) * * Kotlin是在声明类的时候声明泛型协变和逆变的,然后在类里使用的泛型的时候就不用声明泛型协变了;也可以在声明变量的时候声明泛型协变 * * <p> * * * * Created by Chiclaim on 2018/10/10. */ fun takeFruit(fruits: List<Fruit>) { } fun testGenericNumber2(numbers: MutableList<Number>) { } fun main(args: Array<String>) { val foods: List<Food> = listOf(Food(), Food()) val fruits: List<Fruit> = listOf(Fruit(), Fruit()) val apples: List<Apple> = listOf(Apple(), Apple()) val pears: List<Pear> = listOf(Pear(), Pear()) //public interface List<out E> //out修饰的泛型是 泛型协变 covariant //像这样的类或接口如List,称之为协变(covariant)类(接口) //和Java一样,协变泛型不能传递父类类型,只能传递Fruit或者它的子类 //takeFruit(foods) 编译报错 takeFruit(fruits) takeFruit(apples) takeFruit(pears) //------------------------------------- // 根据上面的介绍发现List是协变类 // 我们在来看下MutableList是否是协变类 val ints2: MutableList<Int> = mutableListOf(1, 3, 4) //并不能成功传递参数,所以MutableList并不是一个协变类(invariant) //testGenericNumber2(ints2) //------------------------------------- //我们分别来看下协变类List和非协变类MutableList的源码声明 //在声明类的时候使用协变、逆变 //Kotlin List是一个泛型协变 //public interface List<out E> //MutableList是一个invariant //public interface MutableList<E> : List<E> //------------------------------------- val foodComparator = Comparator<Food> { e1, e2 -> e1.hashCode() - e2.hashCode() } val fruitComparator = Comparator<Fruit> { e1, e2 -> e1.hashCode() - e2.hashCode() } val appleComparator = Comparator<Apple> { e1, e2 -> e1.hashCode() - e2.hashCode() } val list = listOf(Fruit(), Fruit(), Fruit(), Fruit()) //来看下sortedWith方法的声明sortedWith(comparator: Comparator<in T>) //Comparator声明成了逆变(contravariant),这和Java的泛型通配符super一样的 //所以只能传递Fruit以及Fruit父类的Comparator list.sortedWith(foodComparator) list.sortedWith(fruitComparator) //list.sortedWith(appleComparator) 编译报错 //掌握了Java泛型通配符,也会很快掌握Kotlin的泛型协变和逆变 //不同的是:Java只能在声明变量用到泛型的地方使用泛型变异,称之为use-site variance //Kotlin不仅支持use-site variance还支持 declaration-site variance //declaration-site variance 就是在声明类的时候声明泛型变异,如上面使用的Kotlin List就是在定义类的时候声明泛型变异 //在下面的copyData和sortedWith都是use-site variance,即在用到的时候定义泛型变异 } //也可以在声明泛型变量的时候使用协变、逆变 fun <T> copyData(source: MutableList<out T>, destination: MutableList<T>) { for (item in source) { destination.add(item) } } public fun <T> sortedWith(comparator: Comparator<in T>) { }
language-kotlin/kotlin-sample/kotlin-in-action/src/generic/GenericVariance.kt
2797850623
package eu.kanade.tachiyomi.ui.base.controller import android.os.Bundle import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.viewbinding.ViewBinding import com.bluelinelabs.conductor.Controller import com.bluelinelabs.conductor.ControllerChangeHandler import com.bluelinelabs.conductor.ControllerChangeType import eu.kanade.tachiyomi.util.system.logcat import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.MainScope import kotlinx.coroutines.cancel abstract class BaseController<VB : ViewBinding>(bundle: Bundle? = null) : Controller(bundle) { protected lateinit var binding: VB private set lateinit var viewScope: CoroutineScope init { addLifecycleListener( object : LifecycleListener() { override fun postCreateView(controller: Controller, view: View) { onViewCreated(view) } override fun preCreateView(controller: Controller) { viewScope = MainScope() logcat { "Create view for ${controller.instance()}" } } override fun preAttach(controller: Controller, view: View) { logcat { "Attach view for ${controller.instance()}" } } override fun preDetach(controller: Controller, view: View) { logcat { "Detach view for ${controller.instance()}" } } override fun preDestroyView(controller: Controller, view: View) { viewScope.cancel() logcat { "Destroy view for ${controller.instance()}" } } } ) } abstract fun createBinding(inflater: LayoutInflater): VB override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle?): View { binding = createBinding(inflater) return binding.root } open fun onViewCreated(view: View) {} override fun onChangeStarted(handler: ControllerChangeHandler, type: ControllerChangeType) { if (type.isEnter) { setTitle() setHasOptionsMenu(true) } super.onChangeStarted(handler, type) } open fun getTitle(): String? { return null } fun setTitle(title: String? = null) { var parentController = parentController while (parentController != null) { if (parentController is BaseController<*> && parentController.getTitle() != null) { return } parentController = parentController.parentController } (activity as? AppCompatActivity)?.supportActionBar?.title = title ?: getTitle() } private fun Controller.instance(): String { return "${javaClass.simpleName}@${Integer.toHexString(hashCode())}" } /** * Workaround for buggy menu item layout after expanding/collapsing an expandable item like a SearchView. * This method should be removed when fixed upstream. * Issue link: https://issuetracker.google.com/issues/37657375 */ var expandActionViewFromInteraction = false fun MenuItem.fixExpand(onExpand: ((MenuItem) -> Boolean)? = null, onCollapse: ((MenuItem) -> Boolean)? = null) { setOnActionExpandListener( object : MenuItem.OnActionExpandListener { override fun onMenuItemActionExpand(item: MenuItem): Boolean { return onExpand?.invoke(item) ?: true } override fun onMenuItemActionCollapse(item: MenuItem): Boolean { activity?.invalidateOptionsMenu() return onCollapse?.invoke(item) ?: true } } ) if (expandActionViewFromInteraction) { expandActionViewFromInteraction = false expandActionView() } } /** * Workaround for menu items not disappearing when expanding an expandable item like a SearchView. * [expandActionViewFromInteraction] should be set to true in [onOptionsItemSelected] when the expandable item is selected * This method should be called as part of [MenuItem.OnActionExpandListener.onMenuItemActionExpand] */ open fun invalidateMenuOnExpand(): Boolean { return if (expandActionViewFromInteraction) { activity?.invalidateOptionsMenu() false } else { true } } }
app/src/main/java/eu/kanade/tachiyomi/ui/base/controller/BaseController.kt
3447519447
package se.ltu.emapal.compute.io import org.junit.Assert import org.junit.Test import se.ltu.emapal.compute.ComputeBatch import se.ltu.emapal.compute.ComputeError import se.ltu.emapal.compute.ComputeLambda import se.ltu.emapal.compute.ComputeLogEntry import se.ltu.emapal.compute.util.nio.ByteBufferChannel import java.nio.ByteBuffer class TestComputeChannel { val buffer = ByteBuffer.allocate(ComputeChannel.BUFFER_SIZE) val channel = ComputeChannel(ByteBufferChannel(buffer)) @Test fun shouldTransceiveClientMessages() { transceive(ComputeMessage.ClientBatch(1, ComputeBatch(100, 200, "HELLO".toByteArray()))) transceive(ComputeMessage.ClientError(2, ComputeError(1234, "Noes!"))) transceive(ComputeMessage.ClientExit(3)) transceive(ComputeMessage.ClientLogEntry(4, ComputeLogEntry(111, 222, "Surprise!"))) transceive(ComputeMessage.ClientImAlive(5)) } @Test fun shouldTransceiveServiceMessages() { transceive(ComputeMessage.ServiceBatch(1, ComputeBatch(111, 222, "hello".toByteArray()))) transceive(ComputeMessage.ServiceExit(2)) transceive(ComputeMessage.ServiceLambda(3, ComputeLambda(111, "lcm:register(lambda)"))) transceive(ComputeMessage.ServiceImAlive(4)) } private fun transceive(message: ComputeMessage) { buffer.rewind() channel.write(message) .unwrap() buffer.rewind() val response = channel.read() .unwrap() Assert.assertEquals(message, response) } }
core/src/test/java/se/ltu/emapal/compute/io/TestComputeChannel.kt
11595724
/* * 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.analytics.aggregated.mock import dagger.Reusable import io.reactivex.Single import javax.inject.Inject import org.hisp.dhis.android.core.analytics.AnalyticsException import org.hisp.dhis.android.core.analytics.aggregated.AnalyticsVisualizationsRepository import org.hisp.dhis.android.core.analytics.aggregated.DimensionItem import org.hisp.dhis.android.core.analytics.aggregated.GridAnalyticsResponse import org.hisp.dhis.android.core.arch.helpers.Result @Reusable class MockAnalyticsVisualizationsRepository @Inject constructor() : AnalyticsVisualizationsRepository { override fun withVisualization(visualization: String): AnalyticsVisualizationsRepository { return MockAnalyticsVisualizationsRepository() } override fun withPeriods(periods: List<DimensionItem.PeriodItem>): AnalyticsVisualizationsRepository { return MockAnalyticsVisualizationsRepository() } override fun withOrganisationUnits( orgUnits: List<DimensionItem.OrganisationUnitItem> ): AnalyticsVisualizationsRepository { return MockAnalyticsVisualizationsRepository() } override fun evaluate(): Single<Result<GridAnalyticsResponse, AnalyticsException>> { return Single.fromCallable { blockingEvaluate() } } override fun blockingEvaluate(): Result<GridAnalyticsResponse, AnalyticsException> = Result.Success(GridAnalyticsResponseSamples.sample1) }
core/src/main/java/org/hisp/dhis/android/core/analytics/aggregated/mock/MockAnalyticsVisualizationsRepository.kt
2965913184
// "Remove annotation" "true" // COMPILER_ARGUMENTS: -opt-in=kotlin.RequiresOptIn // WITH_STDLIB @RequiresOptIn @Target(AnnotationTarget.VALUE_PARAMETER) annotation class SomeOptInAnnotation class Foo(<caret>@SomeOptInAnnotation val value: Int) { }
plugins/kotlin/idea/tests/testData/quickfix/optIn/valueParameterAnnotationRemove.kt
1751807267
// 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.groovy.template.expressions import com.intellij.codeInsight.template.ExpressionContext import com.intellij.psi.codeStyle.SuggestedNameInfo class SuggestedParameterNameExpression(private val myNameInfo: SuggestedNameInfo) : ParameterNameExpression() { override fun getNameInfo(context: ExpressionContext): SuggestedNameInfo { return myNameInfo } }
plugins/groovy/src/org/jetbrains/plugins/groovy/template/expressions/SuggestedParameterNameExpression.kt
2629597033
// 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.uast.values class UPhiValue private constructor(val values: Set<UValue>) : UValueBase() { override val dependencies: Set<UDependency> = values.flatMapTo(linkedSetOf()) { it.dependencies } override fun equals(other: Any?): Boolean = other is UPhiValue && values == other.values override fun hashCode(): Int = values.hashCode() override fun toString(): String = values.joinToString(prefix = "Phi(", postfix = ")", separator = ", ") override val reachable: Boolean get() = values.any { it.reachable } companion object { private const val PHI_LIMIT = 4 fun create(values: Iterable<UValue>): UValue { val flattenedValues = values.flatMapTo(linkedSetOf<UValue>()) { (it as? UPhiValue)?.values ?: listOf(it) } if (flattenedValues.size <= 1) { throw AssertionError("UPhiValue should contain two or more values: $flattenedValues") } if (flattenedValues.size > PHI_LIMIT || UUndeterminedValue in flattenedValues) { return UUndeterminedValue } return UPhiValue(flattenedValues) } fun create(vararg values: UValue): UValue = create(values.asIterable()) } }
uast/uast-common/src/org/jetbrains/uast/values/UPhiValue.kt
3719801791
package defaultImplsMangling interface IFoo { val x: Int fun foo() { //Breakpoint! val a = 5 } } class Foo : IFoo { override val x: Int = 1 } fun main() { Foo().foo() } // SHOW_KOTLIN_VARIABLES // PRINT_FRAME // EXPRESSION: x // RESULT: 1: I
plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/frame/defaultImplsMangling.kt
1934818208
// 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.platforms import com.intellij.ProjectTopics import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ModuleRootEvent import com.intellij.openapi.roots.ModuleRootListener import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.impl.libraries.LibraryEx import com.intellij.openapi.roots.libraries.PersistentLibraryKind import com.intellij.util.containers.SoftFactoryMap @Service(Service.Level.PROJECT) class LibraryEffectiveKindProvider(project: Project) { private val effectiveKindMap = object : SoftFactoryMap<LibraryEx, PersistentLibraryKind<*>?>() { override fun create(key: LibraryEx) = detectLibraryKind(key.getFiles(OrderRootType.CLASSES)) } init { project.messageBus.connect().subscribe( ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener { override fun rootsChanged(event: ModuleRootEvent) { effectiveKindMap.clear() } } ) } fun getEffectiveKind(library: LibraryEx): PersistentLibraryKind<*>? { if (library.isDisposed) { return null } return when (val kind = library.kind) { is KotlinLibraryKind -> kind else -> effectiveKindMap.get(library) } } companion object { @JvmStatic fun getInstance(project: Project): LibraryEffectiveKindProvider = project.service() } }
plugins/kotlin/base/platforms/src/org/jetbrains/kotlin/idea/base/platforms/LibraryEffectiveKindProvider.kt
2271702496
package org.amshove.kluent.tests.assertions.time.localdate import org.amshove.kluent.before import org.amshove.kluent.days import org.amshove.kluent.shouldBeAtLeast import java.time.LocalDate import kotlin.test.Test import kotlin.test.assertFails class ShouldBeAtLeastXDaysBeforeShould { val orderDate = LocalDate.of(2017, 6, 15) @Test fun passWhenPassingExactlyXDaysBefore() { val shippingDate = LocalDate.of(2017, 6, 10) shippingDate shouldBeAtLeast 5.days() before orderDate } @Test fun passWhenPassingMoreThanXDaysBefore() { val shippingDate = LocalDate.of(2017, 6, 9) shippingDate shouldBeAtLeast 5.days() before orderDate } @Test fun failWhenPassingLessThanXDaysBefore() { val shippingDate = LocalDate.of(2017, 6, 12) assertFails { shippingDate shouldBeAtLeast 5.days() before orderDate } } }
jvm/src/test/kotlin/org/amshove/kluent/tests/assertions/time/localdate/ShouldBeAtLeastXDaysBeforeShould.kt
1388899146
fun foo(x: Int?) { if (x != null) { println(x) } }
java/ql/test/kotlin/query-tests/AutoBoxing/Test.kt
4194052029
/* * 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.features.main import io.github.dreierf.materialintroscreen.MaterialIntroActivity import io.github.dreierf.materialintroscreen.SlideFragmentBuilder import android.os.Bundle import de.dreier.mytargets.R class IntroActivity : MaterialIntroActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) hideBackButton() enableLastSlideAlphaExitTransition(true) addSlide( SlideFragmentBuilder() .backgroundColor(R.color.introBackground) .buttonsColor(R.color.colorAccent) .image(R.drawable.intro_screen_1) .title(getString(R.string.intro_title_track_training_progress)) .description(getString(R.string.intro_description_track_training_progress)) .build() ) addSlide( SlideFragmentBuilder() .backgroundColor(R.color.introBackground) .buttonsColor(R.color.colorAccent) .image(R.drawable.intro_screen_2) .title(getString(R.string.intro_title_everything_in_one_place)) .description(getString(R.string.intro_description_everything_in_one_place)) .build() ) } }
app/src/main/java/de/dreier/mytargets/features/main/IntroActivity.kt
2237791785
package com.planbase.pdf.lm2.lineWrapping //import kotlin.test.assertEquals import TestManual2.Companion.BULLET_TEXT_STYLE import TestManual2.Companion.a6PortraitBody import TestManuallyPdfLayoutMgr.Companion.letterLandscapeBody import com.planbase.pdf.lm2.PdfLayoutMgr import com.planbase.pdf.lm2.attributes.Orientation.LANDSCAPE import com.planbase.pdf.lm2.attributes.Orientation.PORTRAIT import com.planbase.pdf.lm2.attributes.DimAndPageNums import com.planbase.pdf.lm2.attributes.LineStyle import com.planbase.pdf.lm2.attributes.TextStyle import com.planbase.pdf.lm2.contents.Text import com.planbase.pdf.lm2.contents.WrappedText import com.planbase.pdf.lm2.contents.WrappedTextTest import com.planbase.pdf.lm2.lineWrapping.MultiLineWrapped.Companion.wrapLines import com.planbase.pdf.lm2.utils.CMYK_BLACK import com.planbase.pdf.lm2.utils.Coord import com.planbase.pdf.lm2.utils.Dim import com.planbase.pdf.lm2.utils.RGB_BLACK import junit.framework.TestCase import org.apache.pdfbox.pdmodel.common.PDRectangle import org.apache.pdfbox.pdmodel.common.PDRectangle.LETTER import org.apache.pdfbox.pdmodel.font.PDFont import org.apache.pdfbox.pdmodel.font.PDType1Font import org.apache.pdfbox.pdmodel.graphics.color.PDColor import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceCMYK import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB import org.junit.Assert.assertEquals import org.junit.Test import kotlin.math.nextDown import kotlin.test.assertFalse import kotlin.test.assertTrue class MultiLineWrappedTest { private val floatCloseEnough = 0.000004 @Test fun testLine() { val tStyle1 = TextStyle(PDType1Font.TIMES_ROMAN, 60.0, CMYK_BLACK) val txt1 = Text(tStyle1, "Hello ") val tStyle2 = TextStyle(PDType1Font.TIMES_BOLD, 100.0, CMYK_BLACK) val txt2 = Text(tStyle2, "gruel ") val txt3 = Text(tStyle1, "world!") val wrappedText = MultiLineWrapped() // println("txt1.style().lineHeight(): " + txt1.style().lineHeight()) wrappedText.append(txt1.lineWrapper().getSomething(999.0).item) assertEquals(tStyle1.lineHeight, wrappedText.dim.height, floatCloseEnough) assertEquals(tStyle1.ascent, wrappedText.ascent, 0.0) wrappedText.append(txt2.lineWrapper().getSomething(999.0).item) assertEquals(tStyle2.lineHeight, wrappedText.dim.height, floatCloseEnough) assertEquals(tStyle2.ascent, wrappedText.ascent, 0.0) wrappedText.append(txt3.lineWrapper().getSomething(999.0).item) assertEquals(tStyle2.lineHeight, wrappedText.dim.height, floatCloseEnough) assertEquals(tStyle2.ascent, wrappedText.ascent, 0.0) // This is for the baseline! val pageMgr = PdfLayoutMgr(PDDeviceRGB.INSTANCE, Dim(LETTER)) val lp = pageMgr.startPageGrouping(LANDSCAPE, letterLandscapeBody) val yTop = lp.yBodyTop() // println("yBodyTop=$yTop") val yBottom = yTop - tStyle2.lineHeight val yBaseline = yTop - tStyle2.ascent val ascentDiff = tStyle2.ascent - tStyle1.ascent val top2 = yTop - ascentDiff // println("ascentDiff=$ascentDiff") val upperLeft = Coord(40.0, yTop) lp.drawLine(Coord(0.0, yTop), Coord(lp.pageWidth(), yTop), LineStyle(RGB_BLACK, 0.125)) lp.drawLine(Coord(0.0, top2), Coord(lp.pageWidth(), top2), LineStyle(PDColor(floatArrayOf(0.5f, 0.5f, 0.5f), PDDeviceRGB.INSTANCE), 0.125)) lp.drawLine(Coord(0.0, yBaseline), Coord(lp.pageWidth(), yBaseline), LineStyle(RGB_BLACK, 0.125)) lp.drawLine(Coord(0.0, yBottom), Coord(lp.pageWidth(), yBottom), LineStyle(RGB_BLACK, 0.125)) val dap:DimAndPageNums = wrappedText.render(lp, upperLeft) // println("tStyle1=$tStyle1") // println("tStyle2=$tStyle2") assertEquals(wrappedText.dim, dap.dim) pageMgr.commit() // val os = FileOutputStream("multiLineBaseline.pdf") // pageMgr.save(os) } // @Ignore fun verifyLine(line: LineWrapped, lineHeight:Double, maxWidth:Double, text:String) { // println("line: " + line) assertEquals(lineHeight, line.dim.height, floatCloseEnough) assertTrue(line.dim.width < maxWidth) assertEquals(text, line.items() .fold(StringBuilder(), {acc, item -> if (item is WrappedText) { acc.append(item.string) } else { acc }}) .toString()) } @Test fun testRenderablesToLines() { val tStyle1 = TextStyle(PDType1Font.HELVETICA, 9.375, CMYK_BLACK) val txt1 = Text(tStyle1, "Hello ") val tStyle2 = TextStyle(PDType1Font.HELVETICA_BOLD, 13.54166671, CMYK_BLACK) val txt2 = Text(tStyle2, "there ") val txt3 = Text(tStyle1, "world! This is great stuff.") val maxWidth = 60.0 val wrappedLines: List<LineWrapped> = wrapLines(listOf(txt1, txt2, txt3), maxWidth) // println(wrappedLines) assertEquals(3, wrappedLines.size) verifyLine(wrappedLines[0], tStyle2.lineHeight, maxWidth, "Hello there") verifyLine(wrappedLines[1], tStyle1.lineHeight, maxWidth, "world! This is") verifyLine(wrappedLines[2], tStyle1.lineHeight, maxWidth, "great stuff.") } @Test fun testRenderablesToLines2() { val tStyle1 = TextStyle(PDType1Font.HELVETICA, 9.0, CMYK_BLACK) val txt1 = Text(tStyle1, "Hello ") val tStyle2 = TextStyle(PDType1Font.HELVETICA_BOLD, 13.0, CMYK_BLACK) val txt2 = Text(tStyle2, "there ") val txt3 = Text(tStyle1, "world! This is great stuff.") val maxWidth = 90.0 val wrappedLines: List<LineWrapped> = wrapLines(listOf(txt1, txt2, txt3), maxWidth) // println(wrappedLines) assertEquals(2, wrappedLines.size) verifyLine(wrappedLines[0], tStyle2.lineHeight, maxWidth, "Hello there world!") verifyLine(wrappedLines[1], tStyle1.lineHeight, maxWidth, "This is great stuff.") } @Test fun testRenderablesToLines3() { val tStyle1 = TextStyle(PDType1Font.HELVETICA, 9.0, CMYK_BLACK) val txt1 = Text(tStyle1, "Hello there world! This is great stuff.") val maxWidth = 300.0 val wrappedLines: List<LineWrapped> = wrapLines(listOf(txt1), maxWidth) // println(wrappedLines) assertEquals(1, wrappedLines.size) verifyLine(wrappedLines[0], tStyle1.lineHeight, maxWidth, "Hello there world! This is great stuff.") } @Test fun testRenderablesToLinesTerminal() { val tStyle1 = TextStyle(PDType1Font.HELVETICA, 9.0, CMYK_BLACK) val txt1 = Text(tStyle1, "Hello\nthere world! This\nis great stuff.") // This is 300 just like previous test, showing this can fit on one line // So we know the line breaks are due to the \n characters. val maxWidth = 300.0 val wrappedLines: List<LineWrapped> = wrapLines(listOf(txt1), maxWidth) // println(wrappedLines) assertEquals(3, wrappedLines.size) verifyLine(wrappedLines[0], tStyle1.lineHeight, maxWidth, "Hello") verifyLine(wrappedLines[1], tStyle1.lineHeight, maxWidth, "there world! This") verifyLine(wrappedLines[2], tStyle1.lineHeight, maxWidth, "is great stuff.") } @Test fun testRenderablesToLinesTerminal2() { val tStyle1 = TextStyle(PDType1Font.HELVETICA, 9.0, CMYK_BLACK) val txt1 = Text(tStyle1, "Hello\nthere world! This\nis great stuff.\n") // This is 300 just like previous test, showing this can fit on one line // So we know the line breaks are due to the \n characters. val maxWidth = 300.0 val wrappedLines: List<LineWrapped> = wrapLines(listOf(txt1), maxWidth) // println(wrappedLines) assertEquals(4, wrappedLines.size) // println("line3: " + wrappedLines[3]) verifyLine(wrappedLines[0], tStyle1.lineHeight, maxWidth, "Hello") verifyLine(wrappedLines[1], tStyle1.lineHeight, maxWidth, "there world! This") verifyLine(wrappedLines[2], tStyle1.lineHeight, maxWidth, "is great stuff.") // Additional blank line has same height as previous one. verifyLine(wrappedLines[3], tStyle1.lineHeight, maxWidth, "") } @Test fun testRenderablesToLinesMultiReturn() { val tStyle1 = TextStyle(PDType1Font.HELVETICA, 9.0, CMYK_BLACK) val txt1 = Text(tStyle1, " Hello \n\n\n there world! This\n\nis great stuff. \n\n") // This is 300 just like previous test, showing this can fit on one line // So we know the line breaks are due to the \n characters. val maxWidth = 300.0 val wrappedLines: List<LineWrapped> = wrapLines(listOf(txt1), maxWidth) // println(wrappedLines) assertEquals(8, wrappedLines.size) // println("line3: " + wrappedLines[3]) verifyLine(wrappedLines[0], tStyle1.lineHeight, maxWidth, " Hello") verifyLine(wrappedLines[1], tStyle1.lineHeight, maxWidth, "") verifyLine(wrappedLines[2], tStyle1.lineHeight, maxWidth, "") verifyLine(wrappedLines[3], tStyle1.lineHeight, maxWidth, " there world! This") verifyLine(wrappedLines[4], tStyle1.lineHeight, maxWidth, "") verifyLine(wrappedLines[5], tStyle1.lineHeight, maxWidth, "is great stuff.") verifyLine(wrappedLines[6], tStyle1.lineHeight, maxWidth, "") verifyLine(wrappedLines[7], tStyle1.lineHeight, maxWidth, "") } /** * Relies on [com.planbase.pdf.lm2.contents.TextLineWrapperTest.testTooLongWordWrapping] working. */ @Test fun testTooLongWordWrapping() { // This tests a too-long line that breaks on a hyphen (not a white-space). // It used to adjust the index wrong and always return index=0 and return the first half of the line. val times8pt = TextStyle(PDType1Font.TIMES_ROMAN, 8.0, CMYK_BLACK) val maxWidth = 130.0 val lineWrapper: LineWrapper = Text(times8pt, "www.c.ymcdn.com/sites/value-eng.site-ym.com/resource/resmgr/Standards_Documents/vmstd.pdf") .lineWrapper() assertTrue(lineWrapper.hasMore()) var something : ConTerm = lineWrapper.getSomething(maxWidth) assertTrue(something is Continuing) assertTrue(something.item is WrappedText) assertEquals(Continuing(WrappedText(times8pt, "www.c.ymcdn.com/sites/value-eng.site-"), hasMore = true), something) assertTrue(something.item.dim.width <= maxWidth) assertTrue(lineWrapper.hasMore()) something = lineWrapper.getSomething(maxWidth) assertTrue(something is Continuing) assertTrue(something.item is WrappedText) assertEquals(Continuing(WrappedText(times8pt, "ym.com/resource/resmgr/"), hasMore = true), something) assertTrue(something.item.dim.width <= maxWidth) assertTrue(lineWrapper.hasMore()) something = lineWrapper.getSomething(maxWidth) assertTrue(something is Continuing) assertTrue(something.item is WrappedText) assertEquals(Continuing(WrappedText(times8pt, "Standards_Documents/vmstd.pdf"), hasMore = false), something) assertTrue(something.item.dim.width <= maxWidth) assertFalse(lineWrapper.hasMore()) } @Test(expected = IllegalArgumentException::class) fun testRenderablesToLinesEx() { wrapLines(listOf(), -1.0) } @Test fun testStuff() { // See: TextTest.testExactLineWrapping() val text = Text(BULLET_TEXT_STYLE, "months showed the possible money and") assertEquals(214.104, text.maxWidth(), 0.0) val wrapped2:List<LineWrapped> = wrapLines(listOf(text), 213.0) //212.63782) // println("\nwrapped2: $wrapped2") assertEquals(2, wrapped2.size) } // Here's what this test looks like with approximate boxes around each font: // _____________________________________________________ _____________________________________ // ^ ^ | ____ _ _ |/ ^ / / / / / / / / / / / / / / / / /| // | | | | _ \(_) /\ | | | | 15.709 difference in ascent. / / | // ascent| | | | |_) |_ __ _ / \ ___ ___ ___ _ __ | |_ |/ v / / / / / / / / / / / / / / / / /| // 20.49 | | | | _ <| |/ _` | / /\ \ / __|/ __/ _ \ '_ \| __| |--_-----------_----------------------| ^ ^ascent // | | | | |_) | | (_| | / ____ \\__ \ (_| __/ | | | |_ _ | |_) . _ | \ _ _ _ _ __ _|_ | | |4.781 // v | |_|____/|_|\__, |_/_/____\_\___/\___\___|_|_|_|\__(_)_|_|_)_|_(_|___|_/(/_ > (_ (/_| | |_ ._| | v // lineHt| | __/ | ^ | __| ^ | | // 33.48 | | |___/ descent = 12.99 v | | | | // v |_____________________________________________________| | | | lineHt // |/ / / / / / / / / / / / / / / / / / / / / / / / / ^ | | | | 40.0 // | / / / / / / / / / / / / / / / / / / / / / / / / / | | descent = 35.219 | | | // |/ / / / / / / / / / / / / / / / / / / / / / / / / | | | | | // | / / / / / / / / / difference in descent = 22.229 | | | | | // |/ / / / / / / / / / / / / / / / / / / / / / / / / | | | | | // | / / / / / / / / / / / / / / / / / / / / / / / / / v | v | v // +-----------------------------------------------------+-------------------------------------+ // // Notice: // - The two sections of text are aligned exactly on their baseline. // - The first takes up more space above the baseline by virtue of bing a bigger font. // - The second takes up more space below due to a very large lineHeight value. // // Raison D'être: // This all works dandy when line-wrapped and rendered mid-page. The problem came at the page break where the // "Big Descent" text ended up top-aligned - wrong! Also the height with the page break should be approximately // double the total height (2 * 55.709 = 111.418), but it's returning an even 80.0. @Test fun testPageBreakingDiffAscentDescent() { val topHeavy = TextStyle(PDType1Font.TIMES_ROMAN, 30.0, CMYK_BLACK, "topHeavy") // Verify our font metrics to ensure a careful and accurate test. TestCase.assertEquals(20.49, topHeavy.ascent) TestCase.assertEquals(33.48, topHeavy.lineHeight) val bottomHeavy = TextStyle(PDType1Font.TIMES_ITALIC, 7.0, CMYK_BLACK, "bottomHeavy", 40.0) // ascent=4.781 lineHeight=12 TestCase.assertEquals(4.781, bottomHeavy.ascent) TestCase.assertEquals(40.0, bottomHeavy.lineHeight) // We expect the ascent to equal the biggest ascent which is topHeavy.ascent = 20.49. // We expect the descent to equal the biggest descent which is // bottomHeavy.lineHeight - bottomHeavy.ascent = 35.219 val biggerDescent = bottomHeavy.lineHeight - bottomHeavy.ascent TestCase.assertEquals(35.219, biggerDescent) // So the total line height is the maxAscent + maxDescent = topHeavy.ascent + biggerDescent = 55.709 val combinedLineHeight = topHeavy.ascent + biggerDescent TestCase.assertEquals(55.709, combinedLineHeight) val multi = MultiLineWrapped(mutableListOf(WrappedText(topHeavy, "Big ascent."), WrappedText(bottomHeavy, "Big descent."))) // println("multi=$multi") // width=167.536, ascent=20.49, lineHeight=55.709, val multiWidth = multi.width // println("multiWidth=$multiWidth") // The bold-italic text showed on the wrong page because the last line wasn't being dealt with as a unit. // A total line height is now calculated for the entire MultiLineWrapped when later inline text has a surprising // default lineHeight. This test maybe belongs in MultiLineWrapped, but better here than nowhere. val pageMgr = PdfLayoutMgr(PDDeviceCMYK.INSTANCE, Dim(PDRectangle.A6)) val lp = pageMgr.startPageGrouping(PORTRAIT, a6PortraitBody) Dim.assertEquals(Dim(multiWidth, combinedLineHeight), multi.dim, 0.0) var ret1:DimAndPageNums // Rendered away from the page break, the dimensions are unchanged. ret1 = lp.add(Coord(0.0, 300.0), multi) Dim.assertEquals(Dim(multiWidth, combinedLineHeight), ret1.dim, 0.0) assertEquals(300.0 - combinedLineHeight, lp.cursorY, 0.000001) ret1 = multi.render(lp, Coord(0.0, 200.0)) Dim.assertEquals(Dim(multiWidth, combinedLineHeight), ret1.dim, 0.0) // This doesn't show up in the output, just going to walk closer and closer to the edge of the page // without going over. ret1 = multi.render(lp, Coord(0.0, 100.0), reallyRender = false) Dim.assertEquals(Dim(multiWidth, combinedLineHeight), ret1.dim, 0.0) val breakPoint: Double = lp.yBodyBottom + combinedLineHeight ret1 = multi.render(lp, Coord(0.0, breakPoint + 1.0), reallyRender = false) Dim.assertEquals(Dim(multiWidth, combinedLineHeight), ret1.dim, 0.0) ret1 = multi.render(lp, Coord(0.0, breakPoint + 0.0001), reallyRender = false) Dim.assertEquals(Dim(multiWidth, combinedLineHeight), ret1.dim, 0.0) ret1 = multi.render(lp, Coord(0.0, breakPoint + 0.0000001), reallyRender = false) Dim.assertEquals(Dim(multiWidth, combinedLineHeight), ret1.dim, 0.0) ret1 = multi.render(lp, Coord(0.0, breakPoint), reallyRender = false) Dim.assertEquals(Dim(multiWidth, combinedLineHeight), ret1.dim, 0.0) // println("breakPoint=$breakPoint") ret1 = multi.render(lp, Coord(0.0, breakPoint.nextDown()), reallyRender = true) // My theory is that we need an adjustment that pushes *both* halves of the line onto the next page and // that they should still be aligned on a common baseline once they get there. // What was actually happening was that they both go to the next page, but they are top-aligned there, // and the amount that pushes them there is 80.0 instead of 111.418. // So, 80.0 - 55.709 = 24.291 Dim.assertEquals(Dim(multiWidth, combinedLineHeight * 2.0), ret1.dim, 0.0) pageMgr.commit() // pageMgr.save(FileOutputStream("testPgBrkDiffAscDesc.pdf")) } /** Relies on [WrappedTextTest.testSpaceBeforeLastWord2] This was a long-standing bug where if there were multiple items on a line (MultiLineWrapped) and the last one was text, and there was room left for one more item on the line, but only by removing the space before that item, it would nuke the last space before the last word. This showed up in Chapter 3 of Alice which this test is taken from. */ @Test fun testSpaceBeforeLastWord() { val titleFont: PDFont = PDType1Font.TIMES_ROMAN val incipit = TextStyle(titleFont, 36.0, CMYK_BLACK) val heading = TextStyle(titleFont, 16.0, CMYK_BLACK) // Bug: there's no space between "a" and "Long". // Width to show bug: Min: 207.9521 Max: 211.9519 // Difference: 3.9998 // Width of a space in right-hand font=4.0 // println("space=" + heading.stringWidthInDocUnits(" ")) val wrappedItems: List<LineWrapped> = wrapLines(listOf(Text(incipit, "3. "), Text(heading, "A Caucus-Race and a Long Tale")), 210.0) // println("wrappedItems=$wrappedItems") TestCase.assertEquals(2, wrappedItems.size) // 2 lines // first line has 2 items: tne number and "A Caucus-Race and a" val firstLine:List<LineWrapped> = wrappedItems[0].items() // println("firstLine=$firstLine") // If this fails with 3 lines here, it's probably due to a missing space between "a" and "Long". // That's the bug this is designed to prevent regression of. They fit without the space, but you can't just // drop the space. See if WrappedTextTest.testSpaceBeforeLastWord2() fails too. TestCase.assertEquals(2, firstLine.size) TestCase.assertEquals("3. ", (firstLine[0] as WrappedText).string) TestCase.assertEquals("A Caucus-Race and a", (firstLine[1] as WrappedText).string) val secondLine:List<LineWrapped> = wrappedItems[1].items() TestCase.assertEquals(1, secondLine.size) TestCase.assertEquals("Long Tale", (secondLine[0] as WrappedText).string) // lp.add(Coord(0.0, a6PortraitBody.topLeft.y), wrappedCell) // pageMgr.commit() // pageMgr.save(FileOutputStream("spaceBeforeLastWord.pdf")) } val textSize = 8.1 val tsRegular = TextStyle(PDType1Font.TIMES_ROMAN, textSize, CMYK_BLACK, "tsRegular") val tsBold = TextStyle(PDType1Font.TIMES_BOLD, textSize, CMYK_BLACK, "tsBold") @Test fun spaceRemovedFromEndOfLine() { // This width is enough for the space at the end of the regular text, but // not long enough for the bold word "Improvement". This test makes sure // That the final space is removed because it looks incredibly ugly with // justfied text otherwise. val wrappedLines: List<LineWrapped> = wrapLines(listOf( Text(tsRegular, "thinking. The first basic pattern is called the "), Text(tsBold, "Improvement") ), 189.69) assertEquals(2, wrappedLines.size) val wrapped1: WrappedText = wrappedLines[0] as WrappedText // Show that the final space is truncated. assertEquals("thinking. The first basic pattern is called the", wrapped1.string) assertEquals(142.6329, wrapped1.width, 0.0005) // This test should be paired with the following... } @Test fun spacePreservedAtEol() { // This test should be paired with the previous // This width is enough for the the bold word "Improvement". This test makes sure // That the final space is before "Improvement" is *preserved*. val wrappedLines: List<LineWrapped> = wrapLines(listOf( Text(tsRegular, "thinking. The first basic pattern is called the "), Text(tsBold, "Improvement") ), 200.0) assertEquals(1, wrappedLines.size) val multiWrapped: LineWrapped = wrappedLines[0] assertEquals(2, multiWrapped.items().size) val wrapped1 = multiWrapped.items()[0] as WrappedText // Show that the final space is preserved (since there's another word on the same line). assertEquals("thinking. The first basic pattern is called the ", wrapped1.string) assertEquals(144.6579, wrapped1.width, 0.0005) } @Test fun showedErroneousExtraLineBelow() { // This should fit two lines, with no extra line below. // This test is the same as the above, with a shorter maximum width. // There was a bug where it added a blank line. val maxWidth = 189.69 val wrappedLines = wrapLines(listOf(Text(tsRegular, "thinking. The first basic pattern is called the "), Text(tsBold, "Improvement")), maxWidth) // println("wrappedLines=$wrappedLines") assertEquals(2, wrappedLines.size) val totalWidth = wrappedLines.sumByDouble { it.dim.width } // Proves it has to be two lines... assertTrue(totalWidth > maxWidth) assertEquals(189.8721, totalWidth, 0.0005) val multiWrapped1: LineWrapped = wrappedLines[0] assertEquals(1, multiWrapped1.items().size) val wrapped1 = multiWrapped1.items()[0] as WrappedText // Show that the final space is removed since it ends the line. assertEquals("thinking. The first basic pattern is called the", wrapped1.string) assertEquals(142.6329, wrapped1.width, 0.0005) val multiWrapped2: LineWrapped = wrappedLines[1] assertEquals(1, multiWrapped2.items().size) val wrapped2 = multiWrapped2.items()[0] as WrappedText // Show that the final space is removed since it ends the line. assertEquals("Improvement", wrapped2.string) assertEquals(47.2392, wrapped2.width, 0.0005) } }
src/test/java/com/planbase/pdf/lm2/lineWrapping/MultiLineWrappedTest.kt
3214176690
/* * Copyright 2014 Cazcade Limited (http://cazcade.com) * * 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 kontrol.api /** * @todo document. * @author <a href="http://uk.linkedin.com/in/neilellis">Neil Ellis</a> */ public trait ComparableTemporalStore<T : Comparable<T>> : TemporalCollection<T>{ fun percentageInRangeInWindow(range: Range<T>, window: Long, key: String = "<default>"): Double fun medianForWindow(window: Long, key: String = "<default>"): T? }
api/src/main/kotlin/kontrol/api/ComparableTemporalStore.kt
170559397
/* * 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.room.dao import androidx.room.Update /** * Basic Dao UPDATE functions for one model * @author Julien Guerinet * @since 4.2.1 */ interface BaseUpdateDao<T> { /** * Updates the [obj] */ @Update fun update(obj: T) }
room/src/main/java/dao/BaseUpdateDao.kt
3850002106
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.codeInsight.daemon import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase class ClassInDefaultPackageHighlightingTest : LightCodeInsightFixtureTestCase() { override fun setUp() { super.setUp() myFixture.addClass(""" public class conflict { }""".trimIndent()) myFixture.addClass(""" package conflict; public class C { }""".trimIndent()) myFixture.addClass(""" public class MyConstants { public static final int CONSTANT = 1; public static class Inner { public static final String INNER_CONSTANT = "const"; }""".trimIndent()) } fun testClassPackageConflictInImport() { doTest(""" package conflict; import conflict.C; class Test { C c = new C(); }""".trimIndent()) } fun testClassPackageConflictInOnDemandImport() { doTest(""" package conflict; import conflict.*; class Test { C c = new C(); }""".trimIndent()) } fun testClassPackageConflictInFQRefs() { doTest(""" class Test {{ new conflict(); new conflict.<error descr="Cannot resolve symbol 'C'">C</error>(); }}""".trimIndent()) } fun testAccessFromDefaultPackage() { doTest(""" class C { private int field = MyConstants.CONSTANT; }""".trimIndent()) } fun testImportsFromDefaultPackage() { doTest(""" import <error descr="Class 'MyConstants' is in the default package">MyConstants</error>; import <error descr="Class 'MyConstants' is in the default package">MyConstants</error>.Inner; import static <error descr="Class 'MyConstants' is in the default package">MyConstants</error>.*; import static <error descr="Class 'MyConstants' is in the default package">MyConstants</error>.Inner.*; import static <error descr="Class 'MyConstants' is in the default package">MyConstants</error>.Inner.INNER_CONSTANT; """.trimIndent()) } fun testAccessFromNormalCode() { doTest(""" package pkg; import <error descr="Class 'MyConstants' is in the default package">MyConstants</error>; import <error descr="Class 'MyConstants' is in the default package">MyConstants</error>.Inner; class C { <error descr="Class 'MyConstants' is in the default package">MyConstants</error> f = null; Object o = new <error descr="Class 'MyConstants' is in the default package">MyConstants</error>.Inner(); int i = <error descr="Class 'MyConstants' is in the default package">MyConstants</error>.CONSTANT; }""".trimIndent()) } private fun doTest(text: String) { myFixture.configureByText("test.java", text) myFixture.checkHighlighting() } }
java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/ClassInDefaultPackageHighlightingTest.kt
123890127
package de.ph1b.audiobook.features.bookOverview.list.header import com.google.common.truth.Truth.assertThat import de.ph1b.audiobook.BookFactory import org.junit.Test class BookOverviewCategoryTest { @Test fun finished() { val book = BookFactory.create().updateContent { updateSettings { val lastChapter = chapters.last() copy(currentFile = lastChapter.file, positionInChapter = lastChapter.duration) } } assertThat(book.category).isEqualTo(BookOverviewCategory.FINISHED) } @Test fun notStarted() { val book = BookFactory.create().updateContent { updateSettings { val firstChapter = chapters.first() copy(currentFile = firstChapter.file, positionInChapter = 0) } } assertThat(book.category).isEqualTo(BookOverviewCategory.NOT_STARTED) } @Test fun current() { val book = BookFactory.create().updateContent { updateSettings { val lastChapter = chapters.last() copy(currentFile = lastChapter.file, positionInChapter = 0) } } assertThat(book.category).isEqualTo(BookOverviewCategory.CURRENT) } }
app/src/test/java/de/ph1b/audiobook/features/bookOverview/list/header/BookOverviewCategoryTest.kt
3316649197
// 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.compiler.configuration import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.project.Project import com.intellij.openapi.util.Comparing import com.intellij.openapi.util.JDOMUtil import com.intellij.util.ReflectionUtil import com.intellij.util.messages.Topic import com.intellij.util.xmlb.Accessor import com.intellij.util.xmlb.SerializationFilterBase import com.intellij.util.xmlb.XmlSerializer import org.jdom.Element import org.jetbrains.kotlin.cli.common.arguments.* import kotlin.reflect.KClass abstract class BaseKotlinCompilerSettings<T : Freezable> protected constructor(private val project: Project) : PersistentStateComponent<Element>, Cloneable { // Based on com.intellij.util.xmlb.SkipDefaultValuesSerializationFilters private object DefaultValuesFilter : SerializationFilterBase() { private val defaultBeans = HashMap<Class<*>, Any>() private fun createDefaultBean(beanClass: Class<Any>): Any { return ReflectionUtil.newInstance(beanClass).apply { if (this is K2JSCompilerArguments) { sourceMapPrefix = "" } } } private fun getDefaultValue(accessor: Accessor, bean: Any): Any? { if (bean is K2JSCompilerArguments && accessor.name == K2JSCompilerArguments::sourceMapEmbedSources.name) { return if (bean.sourceMap) K2JsArgumentConstants.SOURCE_MAP_SOURCE_CONTENT_INLINING else null } val beanClass = bean.javaClass val defaultBean = defaultBeans.getOrPut(beanClass) { createDefaultBean(beanClass) } return accessor.read(defaultBean) } override fun accepts(accessor: Accessor, bean: Any, beanValue: Any?): Boolean { val defValue = getDefaultValue(accessor, bean) return if (defValue is Element && beanValue is Element) { !JDOMUtil.areElementsEqual(beanValue, defValue) } else { !Comparing.equal(beanValue, defValue) } } } @Suppress("LeakingThis") private var _settings: T = createSettings().frozen() private set(value) { field = value.frozen() } var settings: T get() = _settings set(value) { val oldSettings = _settings validateNewSettings(value) _settings = value KotlinCompilerSettingsTracker.getInstance(project).incModificationCount() project.messageBus.syncPublisher(KotlinCompilerSettingsListener.TOPIC).settingsChanged( oldSettings = oldSettings, newSettings = _settings, ) } fun update(changer: T.() -> Unit) { settings = settings.unfrozen().apply { changer() } } protected fun validateInheritedFieldsUnchanged(settings: T) { @Suppress("UNCHECKED_CAST") val inheritedProperties = collectProperties(settings::class as KClass<T>, true) val defaultInstance = createSettings() val invalidFields = inheritedProperties.filter { it.get(settings) != it.get(defaultInstance) } if (invalidFields.isNotEmpty()) { throw IllegalArgumentException("Following fields are expected to be left unchanged in ${settings.javaClass}: ${invalidFields.joinToString { it.name }}") } } protected open fun validateNewSettings(settings: T) {} protected abstract fun createSettings(): T override fun getState() = XmlSerializer.serialize(_settings, DefaultValuesFilter) override fun loadState(state: Element) { _settings = ReflectionUtil.newInstance(_settings.javaClass).apply { if (this is CommonCompilerArguments) { freeArgs = mutableListOf() internalArguments = mutableListOf() } XmlSerializer.deserializeInto(this, state) } KotlinCompilerSettingsTracker.getInstance(project).incModificationCount() project.messageBus.syncPublisher(KotlinCompilerSettingsListener.TOPIC).settingsChanged( oldSettings = null, newSettings = settings, ) } public override fun clone(): Any = super.clone() } interface KotlinCompilerSettingsListener { fun <T> settingsChanged(oldSettings: T?, newSettings: T?) companion object { @Topic.ProjectLevel val TOPIC = Topic.create("KotlinCompilerSettingsListener", KotlinCompilerSettingsListener::class.java) } }
plugins/kotlin/base/compiler-configuration/src/org/jetbrains/kotlin/idea/compiler/configuration/BaseKotlinCompilerSettings.kt
3613234797
// FIX: Convert sealed sub-class to object // WITH_STDLIB sealed class Sealed <caret>class SubSealed : Sealed { constructor() { println("init") } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/convertSealedSubClassToObject/convertSubClassWithSecondaryConstructor.kt
781351412
/** * This file is part of QuickBeer. * Copyright (C) 2017 Antti Poikela <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package quickbeer.android.feature.beerdetails import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.combineTransform import kotlinx.coroutines.flow.filterIsInstance import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.take import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.threeten.bp.ZonedDateTime import quickbeer.android.R import quickbeer.android.data.repository.Accept import quickbeer.android.data.state.State import quickbeer.android.domain.beer.Beer import quickbeer.android.domain.beer.network.BeerTickFetcher import quickbeer.android.domain.beer.repository.BeerRepository import quickbeer.android.domain.brewer.Brewer import quickbeer.android.domain.brewer.repository.BrewerRepository import quickbeer.android.domain.country.Country import quickbeer.android.domain.country.repository.CountryRepository import quickbeer.android.domain.login.LoginManager import quickbeer.android.domain.style.Style import quickbeer.android.domain.style.repository.StyleRepository import quickbeer.android.domain.stylelist.repository.StyleListRepository import quickbeer.android.feature.beerdetails.model.Address import quickbeer.android.network.result.ApiResult import quickbeer.android.util.ResourceProvider import quickbeer.android.util.ToastProvider import quickbeer.android.util.ktx.navId @HiltViewModel class BeerDetailsViewModel @Inject constructor( savedStateHandle: SavedStateHandle, private val loginManager: LoginManager, private val beerRepository: BeerRepository, private val brewerRepository: BrewerRepository, private val styleRepository: StyleRepository, private val styleListRepository: StyleListRepository, private val countryRepository: CountryRepository, private val beerTickFetcher: BeerTickFetcher, private val resourceProvider: ResourceProvider, private val toastProvider: ToastProvider ) : ViewModel() { private val beerId = savedStateHandle.navId() private val _isLoggedIn = MutableStateFlow(false) val isLoggedIn: StateFlow<Boolean> = _isLoggedIn private val _beerState = MutableStateFlow<State<Beer>>(State.Initial) val beerState: Flow<State<Beer>> = _beerState private val _brewerState = MutableStateFlow<State<Brewer>>(State.Initial) val brewerState: Flow<State<Brewer>> = _brewerState private val _styleState = MutableStateFlow<State<Style>>(State.Initial) val styleState: Flow<State<Style>> = _styleState private val _addressState = MutableStateFlow<State<Address>>(State.Initial) val addressState: Flow<State<Address>> = _addressState init { updateAccessedBeer(beerId) viewModelScope.launch(Dispatchers.IO) { beerRepository.getStream(beerId, Beer.DetailsDataValidator()) .collectLatest { _beerState.emit(it) if (it is State.Success) { getBrewer(it.value) getStyle(it.value) getAddress(it.value) } } } viewModelScope.launch(Dispatchers.IO) { loginManager.isLoggedIn.collectLatest { _isLoggedIn.emit(it) } } } private fun updateAccessedBeer(beerId: Int) { viewModelScope.launch(Dispatchers.IO) { beerRepository.getStream(beerId, Accept()) .filterIsInstance<State.Success<Beer>>() .map { it.value } .take(1) .collect { beer -> val accessed = beer.copy(accessed = ZonedDateTime.now()) beerRepository.persist(beer.id, accessed) } } } private fun updateAccessedBrewer(brewerId: Int) { viewModelScope.launch(Dispatchers.IO) { brewerRepository.getStream(brewerId, Accept()) .filterIsInstance<State.Success<Brewer>>() .map { it.value } .take(1) .collect { brewer -> val accessed = brewer.copy(accessed = ZonedDateTime.now()) brewerRepository.persist(brewer.id, accessed) } } } private fun getBrewer(beer: Beer) { if (beer.brewerId == null) return updateAccessedBrewer(beer.brewerId) viewModelScope.launch(Dispatchers.IO) { brewerRepository.getStream(beer.brewerId, Brewer.BasicDataValidator()) .collectLatest(_brewerState::emit) } } private fun getStyle(beer: Beer) { when { beer.styleId != null -> getStyle(beer.styleId) beer.styleName != null -> getStyle(beer.styleName) } } private fun getStyle(styleId: Int) { viewModelScope.launch(Dispatchers.IO) { styleRepository.getStream(styleId, Accept()) .collectLatest(_styleState::emit) } } private fun getStyle(styleName: String) { viewModelScope.launch(Dispatchers.IO) { styleListRepository.getStream(Accept()) .firstOrNull { it is State.Success } ?.let { if (it is State.Success) it.value else null } ?.firstOrNull { style -> style.name == styleName } ?.let { getStyle(it.id) } } } private fun getAddress(beer: Beer) { if (beer.brewerId == null || beer.countryId == null) return val brewer = brewerRepository.getStream(beer.brewerId, Brewer.DetailsDataValidator()) val country = countryRepository.getStream(beer.countryId, Accept()) viewModelScope.launch(Dispatchers.IO) { brewer.combineTransform(country) { b, c -> emit(mergeAddress(b, c)) }.collectLatest { _addressState.emit(it) } } } private fun mergeAddress(brewer: State<Brewer>, country: State<Country>): State<Address> { return if (brewer is State.Success && country is State.Success) { State.Success(Address.from(brewer.value, country.value)) } else State.Loading() } fun tickBeer(tick: Int) { viewModelScope.launch(Dispatchers.IO) { val beer = beerRepository.store.get(beerId) ?: error("No beer found!") val userId = loginManager.userId.first() ?: error("Not logged in!") val fetchKey = BeerTickFetcher.TickKey(beerId, userId, tick) val result = beerTickFetcher.fetch(fetchKey) if (result is ApiResult.Success) { val update = beer.copy(tickValue = tick, tickDate = ZonedDateTime.now()) beerRepository.persist(beerId, update) } val message = when { result !is ApiResult.Success -> resourceProvider.getString(R.string.tick_failure) tick > 0 -> resourceProvider.getString(R.string.tick_success).format(beer.name) else -> resourceProvider.getString(R.string.tick_removed) } withContext(Dispatchers.Main) { toastProvider.showToast(message) } } } }
app/src/main/java/quickbeer/android/feature/beerdetails/BeerDetailsViewModel.kt
1166390902
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.ui.component import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.util.NlsSafe import com.intellij.ui.* import com.intellij.util.castSafelyTo import org.jetbrains.plugins.github.ui.util.GHUIUtil import org.jetbrains.plugins.github.ui.util.getName import org.jetbrains.plugins.github.util.GHGitRepositoryMapping import javax.swing.JList class GHRepositorySelectorComponentFactory { fun create(model: ComboBoxWithActionsModel<GHGitRepositoryMapping>): ComboBox<*> { return ComboBox(model).apply { renderer = object : ColoredListCellRenderer<ComboBoxWithActionsModel.Item<GHGitRepositoryMapping>>() { override fun customizeCellRenderer(list: JList<out ComboBoxWithActionsModel.Item<GHGitRepositoryMapping>>, value: ComboBoxWithActionsModel.Item<GHGitRepositoryMapping>?, index: Int, selected: Boolean, hasFocus: Boolean) { if (value is ComboBoxWithActionsModel.Item.Wrapper) { val mapping = value.wrappee.castSafelyTo<GHGitRepositoryMapping>() ?: return val repositoryName = repositoryName(model, mapping) val remoteName = mapping.remote.remote.name append(repositoryName).append(" ").append(remoteName, SimpleTextAttributes.GRAYED_ATTRIBUTES) } if (value is ComboBoxWithActionsModel.Item.Action) { if (model.size == index) border = IdeBorderFactory.createBorder(SideBorder.TOP) append(value.action.getName()) } } } isUsePreferredSizeAsMinimum = false isOpaque = false isSwingPopup = true }.also { installSpeedSearch(model, it) } } private fun repositoryName(model: ComboBoxWithActionsModel<GHGitRepositoryMapping>, mapping: GHGitRepositoryMapping): @NlsSafe String { val allRepositories = model.items.map(GHGitRepositoryMapping::repository) return GHUIUtil.getRepositoryDisplayName(allRepositories, mapping.repository, true) } private fun installSpeedSearch(model: ComboBoxWithActionsModel<GHGitRepositoryMapping>, comboBox: ComboBox<ComboBoxWithActionsModel.Item<GHGitRepositoryMapping>>) { ComboboxSpeedSearch.installSpeedSearch(comboBox) { when (it) { is ComboBoxWithActionsModel.Item.Wrapper -> repositoryName(model, it.wrappee) is ComboBoxWithActionsModel.Item.Action -> it.action.getName() } } } }
plugins/github/src/org/jetbrains/plugins/github/ui/component/GHRepositorySelectorComponentFactory.kt
3102276510
package com.apollographql.apollo3.compiler.codegen.kotlin import com.apollographql.apollo3.compiler.codegen.ClassNames import com.apollographql.apollo3.compiler.codegen.ClassNames.apolloApiTestPackageName import com.apollographql.apollo3.compiler.codegen.ResolverClassName import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.MemberName /** * A list of constant symbols from apollo-api referenced from codegen. * We don't use reflection so that we can use R8 on the compiler. * * Symbols can be [ClassName] or [MemberName] */ internal object KotlinSymbols { val ObjectType = ClassNames.ObjectType.toKotlinPoetClassName() val InterfaceType = ClassNames.InterfaceType.toKotlinPoetClassName() val JsonReader = ClassNames.JsonReader.toKotlinPoetClassName() val JsonWriter = ClassNames.JsonWriter.toKotlinPoetClassName() val CustomScalarAdapters = ClassNames.CustomScalarAdapters.toKotlinPoetClassName() val Optional = ClassNames.Optional.toKotlinPoetClassName() val Absent = ClassNames.Absent.toKotlinPoetClassName() val Present = ClassNames.Present.toKotlinPoetClassName() val Adapter = ClassNames.Adapter.toKotlinPoetClassName() val CompiledSelection = ClassNames.CompiledSelection.toKotlinPoetClassName() val CompiledType = ClassNames.CompiledType.toKotlinPoetClassName() val CompiledNamedType = ClassNames.CompiledNamedType.toKotlinPoetClassName() val UnionType = ClassNames.UnionType.toKotlinPoetClassName() val Fragment = ClassNames.Fragment.toKotlinPoetClassName() val FragmentData = ClassNames.FragmentData.toKotlinPoetClassName() val Query = ClassNames.Query.toKotlinPoetClassName() val Mutation = ClassNames.Mutation.toKotlinPoetClassName() val Subscription = ClassNames.Subscription.toKotlinPoetClassName() val QueryData = ClassNames.QueryData.toKotlinPoetClassName() val MutationData = ClassNames.MutationData.toKotlinPoetClassName() val SubscriptionData = ClassNames.SubscriptionData.toKotlinPoetClassName() val EnumType = ClassNames.EnumType.toKotlinPoetClassName() val CustomScalarType = ClassNames.CustomScalarType.toKotlinPoetClassName() val True = ClassNames.True.toKotlinPoetClassName() val False = ClassNames.False.toKotlinPoetClassName() val CompiledArgument = ClassNames.CompiledArgument.toKotlinPoetClassName() val CompiledVariable = ClassNames.CompiledVariable.toKotlinPoetClassName() val CompiledCondition = ClassNames.CompiledCondition.toKotlinPoetClassName() val CompiledField = ClassNames.CompiledField.toKotlinPoetClassName() val CompiledFieldBuilder = ClassNames.CompiledFieldBuilder.toKotlinPoetClassName() val CompiledFragment = ClassNames.CompiledFragment.toKotlinPoetClassName() val CompiledFragmentBuilder = ClassNames.CompiledFragmentBuilder.toKotlinPoetClassName() val TestResolver = ClassNames.TestResolver.toKotlinPoetClassName() val DefaultTestResolver = ClassNames.DefaultTestResolver.toKotlinPoetClassName() val MapJsonReader = ClassNames.MapJsonReader.toKotlinPoetClassName() val MapBuilder = ClassNames.MapBuilder.toKotlinPoetClassName() val StubbedProperty = ClassNames.StubbedProperty.toKotlinPoetClassName() val MandatoryTypenameProperty = ClassNames.MandatoryTypenameProperty.toKotlinPoetClassName() /** * Kotlin class names */ val Boolean = ClassName("kotlin", "Boolean") val Int = ClassName("kotlin", "Int") val String = ClassName("kotlin", "String") val Double = ClassName("kotlin", "Double") val Any = ClassName("kotlin", "Any") val Deprecated = ClassName("kotlin", "Deprecated") val Unit = ClassName("kotlin", "Unit") val List = ClassName("kotlin.collections", "List") val Map = ClassName("kotlin.collections", "Map") val Array = ClassName("kotlin", "Array") /** * Adapters */ val AnyAdapter = MemberName(ClassNames.apolloApiPackageName, "AnyAdapter") val BooleanAdapter = MemberName(ClassNames.apolloApiPackageName, "BooleanAdapter") val DoubleAdapter = MemberName(ClassNames.apolloApiPackageName, "DoubleAdapter") val IntAdapter = MemberName(ClassNames.apolloApiPackageName, "IntAdapter") val StringAdapter = MemberName(ClassNames.apolloApiPackageName, "StringAdapter") val NullableAnyAdapter = MemberName(ClassNames.apolloApiPackageName, "NullableAnyAdapter") val NullableBooleanAdapter = MemberName(ClassNames.apolloApiPackageName, "NullableBooleanAdapter") val NullableDoubleAdapter = MemberName(ClassNames.apolloApiPackageName, "NullableDoubleAdapter") val NullableIntAdapter = MemberName(ClassNames.apolloApiPackageName, "NullableIntAdapter") val NullableStringAdapter = MemberName(ClassNames.apolloApiPackageName, "NullableStringAdapter") } fun ResolverClassName.toKotlinPoetClassName(): ClassName = ClassName(packageName, simpleNames) object KotlinMemberNames { val withTestResolver = MemberName(apolloApiTestPackageName, "withTestResolver") }
apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/codegen/kotlin/KotlinSymbols.kt
3121301910
package com.github.vhromada.catalog.mapper.impl import com.github.vhromada.catalog.common.provider.UuidProvider import com.github.vhromada.catalog.domain.Song import com.github.vhromada.catalog.entity.ChangeSongRequest import com.github.vhromada.catalog.mapper.SongMapper import org.springframework.stereotype.Component /** * A class represents implementation of mapper for songs. * * @author Vladimir Hromada */ @Component("songMapper") class SongMapperImpl( /** * Provider for UUID */ private val uuidProvider: UuidProvider ) : SongMapper { override fun mapSong(source: Song): com.github.vhromada.catalog.entity.Song { return com.github.vhromada.catalog.entity.Song( uuid = source.uuid, name = source.name, length = source.length, note = source.note ) } override fun mapSongs(source: List<Song>): List<com.github.vhromada.catalog.entity.Song> { return source.map { mapSong(source = it) } } override fun mapRequest(source: ChangeSongRequest): Song { return Song( id = null, uuid = uuidProvider.getUuid(), name = source.name!!, length = source.length!!, note = source.note ) } }
core/src/main/kotlin/com/github/vhromada/catalog/mapper/impl/SongMapperImpl.kt
3870493452
/* * Copyright (C) 2011 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 okhttp3.internal.cache import okhttp3.internal.assertThreadHoldsLock import okhttp3.internal.cache.DiskLruCache.Editor import okhttp3.internal.closeQuietly import okhttp3.internal.concurrent.Task import okhttp3.internal.concurrent.TaskRunner import okhttp3.internal.deleteContents import okhttp3.internal.deleteIfExists import okhttp3.internal.isCivilized import okhttp3.internal.okHttpName import okhttp3.internal.platform.Platform import okhttp3.internal.platform.Platform.Companion.WARN import okio.BufferedSink import okio.ExperimentalFileSystem import okio.FileNotFoundException import okio.FileSystem import okio.ForwardingFileSystem import okio.ForwardingSource import okio.Path import okio.Sink import okio.Source import okio.blackholeSink import okio.buffer import java.io.Closeable import java.io.EOFException import java.io.Flushable import java.io.IOException /** * A cache that uses a bounded amount of space on a filesystem. Each cache entry has a string key * and a fixed number of values. Each key must match the regex `[a-z0-9_-]{1,64}`. Values are byte * sequences, accessible as streams or files. Each value must be between `0` and `Int.MAX_VALUE` * bytes in length. * * The cache stores its data in a directory on the filesystem. This directory must be exclusive to * the cache; the cache may delete or overwrite files from its directory. It is an error for * multiple processes to use the same cache directory at the same time. * * This cache limits the number of bytes that it will store on the filesystem. When the number of * stored bytes exceeds the limit, the cache will remove entries in the background until the limit * is satisfied. The limit is not strict: the cache may temporarily exceed it while waiting for * files to be deleted. The limit does not include filesystem overhead or the cache journal so * space-sensitive applications should set a conservative limit. * * Clients call [edit] to create or update the values of an entry. An entry may have only one editor * at one time; if a value is not available to be edited then [edit] will return null. * * * When an entry is being **created** it is necessary to supply a full set of values; the empty * value should be used as a placeholder if necessary. * * * When an entry is being **edited**, it is not necessary to supply data for every value; values * default to their previous value. * * Every [edit] call must be matched by a call to [Editor.commit] or [Editor.abort]. Committing is * atomic: a read observes the full set of values as they were before or after the commit, but never * a mix of values. * * Clients call [get] to read a snapshot of an entry. The read will observe the value at the time * that [get] was called. Updates and removals after the call do not impact ongoing reads. * * This class is tolerant of some I/O errors. If files are missing from the filesystem, the * corresponding entries will be dropped from the cache. If an error occurs while writing a cache * value, the edit will fail silently. Callers should handle other problems by catching * `IOException` and responding appropriately. * * @constructor Create a cache which will reside in [directory]. This cache is lazily initialized on * first access and will be created if it does not exist. * @param directory a writable directory. * @param valueCount the number of values per cache entry. Must be positive. * @param maxSize the maximum number of bytes this cache should use to store. */ @OptIn(ExperimentalFileSystem::class) class DiskLruCache( fileSystem: FileSystem, /** Returns the directory where this cache stores its data. */ val directory: Path, private val appVersion: Int, internal val valueCount: Int, /** Returns the maximum number of bytes that this cache should use to store its data. */ maxSize: Long, /** Used for asynchronous journal rebuilds. */ taskRunner: TaskRunner ) : Closeable, Flushable { internal val fileSystem: FileSystem = object : ForwardingFileSystem(fileSystem) { override fun sink(file: Path): Sink { file.parent?.let { // TODO from okhttp3.internal.io.FileSystem if (!exists(it)) { createDirectories(it) } } return super.sink(file) } } /** The maximum number of bytes that this cache should use to store its data. */ @get:Synchronized @set:Synchronized var maxSize: Long = maxSize set(value) { field = value if (initialized) { cleanupQueue.schedule(cleanupTask) // Trim the existing store if necessary. } } /* * This cache uses a journal file named "journal". A typical journal file looks like this: * * libcore.io.DiskLruCache * 1 * 100 * 2 * * CLEAN 3400330d1dfc7f3f7f4b8d4d803dfcf6 832 21054 * DIRTY 335c4c6028171cfddfbaae1a9c313c52 * CLEAN 335c4c6028171cfddfbaae1a9c313c52 3934 2342 * REMOVE 335c4c6028171cfddfbaae1a9c313c52 * DIRTY 1ab96a171faeeee38496d8b330771a7a * CLEAN 1ab96a171faeeee38496d8b330771a7a 1600 234 * READ 335c4c6028171cfddfbaae1a9c313c52 * READ 3400330d1dfc7f3f7f4b8d4d803dfcf6 * * The first five lines of the journal form its header. They are the constant string * "libcore.io.DiskLruCache", the disk cache's version, the application's version, the value * count, and a blank line. * * Each of the subsequent lines in the file is a record of the state of a cache entry. Each line * contains space-separated values: a state, a key, and optional state-specific values. * * o DIRTY lines track that an entry is actively being created or updated. Every successful * DIRTY action should be followed by a CLEAN or REMOVE action. DIRTY lines without a matching * CLEAN or REMOVE indicate that temporary files may need to be deleted. * * o CLEAN lines track a cache entry that has been successfully published and may be read. A * publish line is followed by the lengths of each of its values. * * o READ lines track accesses for LRU. * * o REMOVE lines track entries that have been deleted. * * The journal file is appended to as cache operations occur. The journal may occasionally be * compacted by dropping redundant lines. A temporary file named "journal.tmp" will be used during * compaction; that file should be deleted if it exists when the cache is opened. */ private val journalFile: Path private val journalFileTmp: Path private val journalFileBackup: Path private var size: Long = 0L private var journalWriter: BufferedSink? = null internal val lruEntries = LinkedHashMap<String, Entry>(0, 0.75f, true) private var redundantOpCount: Int = 0 private var hasJournalErrors: Boolean = false private var civilizedFileSystem: Boolean = false // Must be read and written when synchronized on 'this'. private var initialized: Boolean = false internal var closed: Boolean = false private var mostRecentTrimFailed: Boolean = false private var mostRecentRebuildFailed: Boolean = false /** * To differentiate between old and current snapshots, each entry is given a sequence number each * time an edit is committed. A snapshot is stale if its sequence number is not equal to its * entry's sequence number. */ private var nextSequenceNumber: Long = 0 private val cleanupQueue = taskRunner.newQueue() private val cleanupTask = object : Task("$okHttpName Cache") { override fun runOnce(): Long { synchronized(this@DiskLruCache) { if (!initialized || closed) { return -1L // Nothing to do. } try { trimToSize() } catch (_: IOException) { mostRecentTrimFailed = true } try { if (journalRebuildRequired()) { rebuildJournal() redundantOpCount = 0 } } catch (_: IOException) { mostRecentRebuildFailed = true journalWriter = blackholeSink().buffer() } return -1L } } } init { require(maxSize > 0L) { "maxSize <= 0" } require(valueCount > 0) { "valueCount <= 0" } this.journalFile = directory / JOURNAL_FILE this.journalFileTmp = directory / JOURNAL_FILE_TEMP this.journalFileBackup = directory / JOURNAL_FILE_BACKUP } @Synchronized @Throws(IOException::class) fun initialize() { this.assertThreadHoldsLock() if (initialized) { return // Already initialized. } // If a bkp file exists, use it instead. if (fileSystem.exists(journalFileBackup)) { // If journal file also exists just delete backup file. if (fileSystem.exists(journalFile)) { fileSystem.delete(journalFileBackup) } else { fileSystem.atomicMove(journalFileBackup, journalFile) } } civilizedFileSystem = fileSystem.isCivilized(journalFileBackup) // Prefer to pick up where we left off. if (fileSystem.exists(journalFile)) { try { readJournal() processJournal() initialized = true return } catch (journalIsCorrupt: IOException) { Platform.get().log( "DiskLruCache $directory is corrupt: ${journalIsCorrupt.message}, removing", WARN, journalIsCorrupt) } // The cache is corrupted, attempt to delete the contents of the directory. This can throw and // we'll let that propagate out as it likely means there is a severe filesystem problem. try { delete() } finally { closed = false } } rebuildJournal() initialized = true } @Throws(IOException::class) private fun readJournal() { fileSystem.read(journalFile) { val magic = readUtf8LineStrict() val version = readUtf8LineStrict() val appVersionString = readUtf8LineStrict() val valueCountString = readUtf8LineStrict() val blank = readUtf8LineStrict() if (MAGIC != magic || VERSION_1 != version || appVersion.toString() != appVersionString || valueCount.toString() != valueCountString || blank.isNotEmpty()) { throw IOException( "unexpected journal header: [$magic, $version, $valueCountString, $blank]") } var lineCount = 0 while (true) { try { readJournalLine(readUtf8LineStrict()) lineCount++ } catch (_: EOFException) { break // End of journal. } } redundantOpCount = lineCount - lruEntries.size // If we ended on a truncated line, rebuild the journal before appending to it. if (!exhausted()) { rebuildJournal() } else { journalWriter = newJournalWriter() } } } @Throws(FileNotFoundException::class) private fun newJournalWriter(): BufferedSink { val fileSink = fileSystem.appendingSink(journalFile) val faultHidingSink = FaultHidingSink(fileSink) { [email protected]() hasJournalErrors = true } return faultHidingSink.buffer() } @Throws(IOException::class) private fun readJournalLine(line: String) { val firstSpace = line.indexOf(' ') if (firstSpace == -1) throw IOException("unexpected journal line: $line") val keyBegin = firstSpace + 1 val secondSpace = line.indexOf(' ', keyBegin) val key: String if (secondSpace == -1) { key = line.substring(keyBegin) if (firstSpace == REMOVE.length && line.startsWith(REMOVE)) { lruEntries.remove(key) return } } else { key = line.substring(keyBegin, secondSpace) } var entry: Entry? = lruEntries[key] if (entry == null) { entry = Entry(key) lruEntries[key] = entry } when { secondSpace != -1 && firstSpace == CLEAN.length && line.startsWith(CLEAN) -> { val parts = line.substring(secondSpace + 1) .split(' ') entry.readable = true entry.currentEditor = null entry.setLengths(parts) } secondSpace == -1 && firstSpace == DIRTY.length && line.startsWith(DIRTY) -> { entry.currentEditor = Editor(entry) } secondSpace == -1 && firstSpace == READ.length && line.startsWith(READ) -> { // This work was already done by calling lruEntries.get(). } else -> throw IOException("unexpected journal line: $line") } } /** * Computes the initial size and collects garbage as a part of opening the cache. Dirty entries * are assumed to be inconsistent and will be deleted. */ @Throws(IOException::class) private fun processJournal() { fileSystem.deleteIfExists(journalFileTmp) val i = lruEntries.values.iterator() while (i.hasNext()) { val entry = i.next() if (entry.currentEditor == null) { for (t in 0 until valueCount) { size += entry.lengths[t] } } else { entry.currentEditor = null for (t in 0 until valueCount) { fileSystem.deleteIfExists(entry.cleanFiles[t]) fileSystem.deleteIfExists(entry.dirtyFiles[t]) } i.remove() } } } /** * Creates a new journal that omits redundant information. This replaces the current journal if it * exists. */ @Synchronized @Throws(IOException::class) internal fun rebuildJournal() { journalWriter?.close() fileSystem.write(journalFileTmp) { writeUtf8(MAGIC).writeByte('\n'.toInt()) writeUtf8(VERSION_1).writeByte('\n'.toInt()) writeDecimalLong(appVersion.toLong()).writeByte('\n'.toInt()) writeDecimalLong(valueCount.toLong()).writeByte('\n'.toInt()) writeByte('\n'.toInt()) for (entry in lruEntries.values) { if (entry.currentEditor != null) { writeUtf8(DIRTY).writeByte(' '.toInt()) writeUtf8(entry.key) writeByte('\n'.toInt()) } else { writeUtf8(CLEAN).writeByte(' '.toInt()) writeUtf8(entry.key) entry.writeLengths(this) writeByte('\n'.toInt()) } } } if (fileSystem.exists(journalFile)) { fileSystem.atomicMove(journalFile, journalFileBackup) fileSystem.atomicMove(journalFileTmp, journalFile) fileSystem.deleteIfExists(journalFileBackup) } else { fileSystem.atomicMove(journalFileTmp, journalFile) } journalWriter = newJournalWriter() hasJournalErrors = false mostRecentRebuildFailed = false } /** * Returns a snapshot of the entry named [key], or null if it doesn't exist is not currently * readable. If a value is returned, it is moved to the head of the LRU queue. */ @Synchronized @Throws(IOException::class) operator fun get(key: String): Snapshot? { initialize() checkNotClosed() validateKey(key) val entry = lruEntries[key] ?: return null val snapshot = entry.snapshot() ?: return null redundantOpCount++ journalWriter!!.writeUtf8(READ) .writeByte(' '.toInt()) .writeUtf8(key) .writeByte('\n'.toInt()) if (journalRebuildRequired()) { cleanupQueue.schedule(cleanupTask) } return snapshot } /** Returns an editor for the entry named [key], or null if another edit is in progress. */ @Synchronized @Throws(IOException::class) @JvmOverloads fun edit(key: String, expectedSequenceNumber: Long = ANY_SEQUENCE_NUMBER): Editor? { initialize() checkNotClosed() validateKey(key) var entry: Entry? = lruEntries[key] if (expectedSequenceNumber != ANY_SEQUENCE_NUMBER && (entry == null || entry.sequenceNumber != expectedSequenceNumber)) { return null // Snapshot is stale. } if (entry?.currentEditor != null) { return null // Another edit is in progress. } if (entry != null && entry.lockingSourceCount != 0) { return null // We can't write this file because a reader is still reading it. } if (mostRecentTrimFailed || mostRecentRebuildFailed) { // The OS has become our enemy! If the trim job failed, it means we are storing more data than // requested by the user. Do not allow edits so we do not go over that limit any further. If // the journal rebuild failed, the journal writer will not be active, meaning we will not be // able to record the edit, causing file leaks. In both cases, we want to retry the clean up // so we can get out of this state! cleanupQueue.schedule(cleanupTask) return null } // Flush the journal before creating files to prevent file leaks. val journalWriter = this.journalWriter!! journalWriter.writeUtf8(DIRTY) .writeByte(' '.toInt()) .writeUtf8(key) .writeByte('\n'.toInt()) journalWriter.flush() if (hasJournalErrors) { return null // Don't edit; the journal can't be written. } if (entry == null) { entry = Entry(key) lruEntries[key] = entry } val editor = Editor(entry) entry.currentEditor = editor return editor } /** * Returns the number of bytes currently being used to store the values in this cache. This may be * greater than the max size if a background deletion is pending. */ @Synchronized @Throws(IOException::class) fun size(): Long { initialize() return size } @Synchronized @Throws(IOException::class) internal fun completeEdit(editor: Editor, success: Boolean) { val entry = editor.entry check(entry.currentEditor == editor) // If this edit is creating the entry for the first time, every index must have a value. if (success && !entry.readable) { for (i in 0 until valueCount) { if (!editor.written!![i]) { editor.abort() throw IllegalStateException("Newly created entry didn't create value for index $i") } if (!fileSystem.exists(entry.dirtyFiles[i])) { editor.abort() return } } } for (i in 0 until valueCount) { val dirty = entry.dirtyFiles[i] if (success && !entry.zombie) { if (fileSystem.exists(dirty)) { val clean = entry.cleanFiles[i] fileSystem.atomicMove(dirty, clean) val oldLength = entry.lengths[i] // TODO check null behaviour val newLength = fileSystem.metadata(clean).size ?: 0 entry.lengths[i] = newLength size = size - oldLength + newLength } } else { fileSystem.deleteIfExists(dirty) } } entry.currentEditor = null if (entry.zombie) { removeEntry(entry) return } redundantOpCount++ journalWriter!!.apply { if (entry.readable || success) { entry.readable = true writeUtf8(CLEAN).writeByte(' '.toInt()) writeUtf8(entry.key) entry.writeLengths(this) writeByte('\n'.toInt()) if (success) { entry.sequenceNumber = nextSequenceNumber++ } } else { lruEntries.remove(entry.key) writeUtf8(REMOVE).writeByte(' '.toInt()) writeUtf8(entry.key) writeByte('\n'.toInt()) } flush() } if (size > maxSize || journalRebuildRequired()) { cleanupQueue.schedule(cleanupTask) } } /** * We only rebuild the journal when it will halve the size of the journal and eliminate at least * 2000 ops. */ private fun journalRebuildRequired(): Boolean { val redundantOpCompactThreshold = 2000 return redundantOpCount >= redundantOpCompactThreshold && redundantOpCount >= lruEntries.size } /** * Drops the entry for [key] if it exists and can be removed. If the entry for [key] is currently * being edited, that edit will complete normally but its value will not be stored. * * @return true if an entry was removed. */ @Synchronized @Throws(IOException::class) fun remove(key: String): Boolean { initialize() checkNotClosed() validateKey(key) val entry = lruEntries[key] ?: return false val removed = removeEntry(entry) if (removed && size <= maxSize) mostRecentTrimFailed = false return removed } @Throws(IOException::class) internal fun removeEntry(entry: Entry): Boolean { // If we can't delete files that are still open, mark this entry as a zombie so its files will // be deleted when those files are closed. if (!civilizedFileSystem) { if (entry.lockingSourceCount > 0) { // Mark this entry as 'DIRTY' so that if the process crashes this entry won't be used. journalWriter?.let { it.writeUtf8(DIRTY) it.writeByte(' '.toInt()) it.writeUtf8(entry.key) it.writeByte('\n'.toInt()) it.flush() } } if (entry.lockingSourceCount > 0 || entry.currentEditor != null) { entry.zombie = true return true } } entry.currentEditor?.detach() // Prevent the edit from completing normally. for (i in 0 until valueCount) { fileSystem.deleteIfExists(entry.cleanFiles[i]) size -= entry.lengths[i] entry.lengths[i] = 0 } redundantOpCount++ journalWriter?.let { it.writeUtf8(REMOVE) it.writeByte(' '.toInt()) it.writeUtf8(entry.key) it.writeByte('\n'.toInt()) } lruEntries.remove(entry.key) if (journalRebuildRequired()) { cleanupQueue.schedule(cleanupTask) } return true } @Synchronized private fun checkNotClosed() { check(!closed) { "cache is closed" } } /** Force buffered operations to the filesystem. */ @Synchronized @Throws(IOException::class) override fun flush() { if (!initialized) return checkNotClosed() trimToSize() journalWriter!!.flush() } @Synchronized fun isClosed(): Boolean = closed /** Closes this cache. Stored values will remain on the filesystem. */ @Synchronized @Throws(IOException::class) override fun close() { if (!initialized || closed) { closed = true return } // Copying for concurrent iteration. for (entry in lruEntries.values.toTypedArray()) { if (entry.currentEditor != null) { entry.currentEditor?.detach() // Prevent the edit from completing normally. } } trimToSize() journalWriter!!.close() journalWriter = null closed = true } @Throws(IOException::class) fun trimToSize() { while (size > maxSize) { if (!removeOldestEntry()) return } mostRecentTrimFailed = false } /** Returns true if an entry was removed. This will return false if all entries are zombies. */ private fun removeOldestEntry(): Boolean { for (toEvict in lruEntries.values) { if (!toEvict.zombie) { removeEntry(toEvict) return true } } return false } /** * Closes the cache and deletes all of its stored values. This will delete all files in the cache * directory including files that weren't created by the cache. */ @Throws(IOException::class) fun delete() { close() fileSystem.deleteContents(directory) } /** * Deletes all stored values from the cache. In-flight edits will complete normally but their * values will not be stored. */ @Synchronized @Throws(IOException::class) fun evictAll() { initialize() // Copying for concurrent iteration. for (entry in lruEntries.values.toTypedArray()) { removeEntry(entry) } mostRecentTrimFailed = false } private fun validateKey(key: String) { require(LEGAL_KEY_PATTERN.matches(key)) { "keys must match regex [a-z0-9_-]{1,120}: \"$key\"" } } /** * Returns an iterator over the cache's current entries. This iterator doesn't throw * `ConcurrentModificationException`, but if new entries are added while iterating, those new * entries will not be returned by the iterator. If existing entries are removed during iteration, * they will be absent (unless they were already returned). * * If there are I/O problems during iteration, this iterator fails silently. For example, if the * hosting filesystem becomes unreachable, the iterator will omit elements rather than throwing * exceptions. * * **The caller must [close][Snapshot.close]** each snapshot returned by [Iterator.next]. Failing * to do so leaks open files! */ @Synchronized @Throws(IOException::class) fun snapshots(): MutableIterator<Snapshot> { initialize() return object : MutableIterator<Snapshot> { /** Iterate a copy of the entries to defend against concurrent modification errors. */ private val delegate = ArrayList(lruEntries.values).iterator() /** The snapshot to return from [next]. Null if we haven't computed that yet. */ private var nextSnapshot: Snapshot? = null /** The snapshot to remove with [remove]. Null if removal is illegal. */ private var removeSnapshot: Snapshot? = null override fun hasNext(): Boolean { if (nextSnapshot != null) return true synchronized(this@DiskLruCache) { // If the cache is closed, truncate the iterator. if (closed) return false while (delegate.hasNext()) { nextSnapshot = delegate.next()?.snapshot() ?: continue return true } } return false } override fun next(): Snapshot { if (!hasNext()) throw NoSuchElementException() removeSnapshot = nextSnapshot nextSnapshot = null return removeSnapshot!! } override fun remove() { val removeSnapshot = this.removeSnapshot checkNotNull(removeSnapshot) { "remove() before next()" } try { [email protected](removeSnapshot.key()) } catch (_: IOException) { // Nothing useful to do here. We failed to remove from the cache. Most likely that's // because we couldn't update the journal, but the cached entry will still be gone. } finally { this.removeSnapshot = null } } } } /** A snapshot of the values for an entry. */ inner class Snapshot internal constructor( private val key: String, private val sequenceNumber: Long, private val sources: List<Source>, private val lengths: LongArray ) : Closeable { fun key(): String = key /** * Returns an editor for this snapshot's entry, or null if either the entry has changed since * this snapshot was created or if another edit is in progress. */ @Throws(IOException::class) fun edit(): Editor? = [email protected](key, sequenceNumber) /** Returns the unbuffered stream with the value for [index]. */ fun getSource(index: Int): Source = sources[index] /** Returns the byte length of the value for [index]. */ fun getLength(index: Int): Long = lengths[index] override fun close() { for (source in sources) { source.closeQuietly() } } } /** Edits the values for an entry. */ inner class Editor internal constructor(internal val entry: Entry) { internal val written: BooleanArray? = if (entry.readable) null else BooleanArray(valueCount) private var done: Boolean = false /** * Prevents this editor from completing normally. This is necessary either when the edit causes * an I/O error, or if the target entry is evicted while this editor is active. In either case * we delete the editor's created files and prevent new files from being created. Note that once * an editor has been detached it is possible for another editor to edit the entry. */ internal fun detach() { if (entry.currentEditor == this) { if (civilizedFileSystem) { completeEdit(this, false) // Delete it now. } else { entry.zombie = true // We can't delete it until the current edit completes. } } } /** * Returns an unbuffered input stream to read the last committed value, or null if no value has * been committed. */ fun newSource(index: Int): Source? { synchronized(this@DiskLruCache) { check(!done) if (!entry.readable || entry.currentEditor != this || entry.zombie) { return null } return try { fileSystem.source(entry.cleanFiles[index]) } catch (_: FileNotFoundException) { null } } } /** * Returns a new unbuffered output stream to write the value at [index]. If the underlying * output stream encounters errors when writing to the filesystem, this edit will be aborted * when [commit] is called. The returned output stream does not throw IOExceptions. */ fun newSink(index: Int): Sink { synchronized(this@DiskLruCache) { check(!done) if (entry.currentEditor != this) { return blackholeSink() } if (!entry.readable) { written!![index] = true } val dirtyFile = entry.dirtyFiles[index] val sink: Sink try { sink = fileSystem.sink(dirtyFile) } catch (_: FileNotFoundException) { return blackholeSink() } return FaultHidingSink(sink) { synchronized(this@DiskLruCache) { detach() } } } } /** * Commits this edit so it is visible to readers. This releases the edit lock so another edit * may be started on the same key. */ @Throws(IOException::class) fun commit() { synchronized(this@DiskLruCache) { check(!done) if (entry.currentEditor == this) { completeEdit(this, true) } done = true } } /** * Aborts this edit. This releases the edit lock so another edit may be started on the same * key. */ @Throws(IOException::class) fun abort() { synchronized(this@DiskLruCache) { check(!done) if (entry.currentEditor == this) { completeEdit(this, false) } done = true } } } internal inner class Entry internal constructor( internal val key: String ) { /** Lengths of this entry's files. */ internal val lengths: LongArray = LongArray(valueCount) internal val cleanFiles = mutableListOf<Path>() internal val dirtyFiles = mutableListOf<Path>() /** True if this entry has ever been published. */ internal var readable: Boolean = false /** True if this entry must be deleted when the current edit or read completes. */ internal var zombie: Boolean = false /** * The ongoing edit or null if this entry is not being edited. When setting this to null the * entry must be removed if it is a zombie. */ internal var currentEditor: Editor? = null /** * Sources currently reading this entry before a write or delete can proceed. When decrementing * this to zero, the entry must be removed if it is a zombie. */ internal var lockingSourceCount = 0 /** The sequence number of the most recently committed edit to this entry. */ internal var sequenceNumber: Long = 0 init { // The names are repetitive so re-use the same builder to avoid allocations. val fileBuilder = StringBuilder(key).append('.') val truncateTo = fileBuilder.length for (i in 0 until valueCount) { fileBuilder.append(i) cleanFiles += directory / fileBuilder.toString() fileBuilder.append(".tmp") dirtyFiles += directory / fileBuilder.toString() fileBuilder.setLength(truncateTo) } } /** Set lengths using decimal numbers like "10123". */ @Throws(IOException::class) internal fun setLengths(strings: List<String>) { if (strings.size != valueCount) { throw invalidLengths(strings) } try { for (i in strings.indices) { lengths[i] = strings[i].toLong() } } catch (_: NumberFormatException) { throw invalidLengths(strings) } } /** Append space-prefixed lengths to [writer]. */ @Throws(IOException::class) internal fun writeLengths(writer: BufferedSink) { for (length in lengths) { writer.writeByte(' '.toInt()).writeDecimalLong(length) } } @Throws(IOException::class) private fun invalidLengths(strings: List<String>): Nothing { throw IOException("unexpected journal line: $strings") } /** * Returns a snapshot of this entry. This opens all streams eagerly to guarantee that we see a * single published snapshot. If we opened streams lazily then the streams could come from * different edits. */ internal fun snapshot(): Snapshot? { [email protected]() if (!readable) return null if (!civilizedFileSystem && (currentEditor != null || zombie)) return null val sources = mutableListOf<Source>() val lengths = this.lengths.clone() // Defensive copy since these can be zeroed out. try { for (i in 0 until valueCount) { sources += newSource(i) } return Snapshot(key, sequenceNumber, sources, lengths) } catch (_: FileNotFoundException) { // A file must have been deleted manually! for (source in sources) { source.closeQuietly() } // Since the entry is no longer valid, remove it so the metadata is accurate (i.e. the cache // size.) try { removeEntry(this) } catch (_: IOException) { } return null } } private fun newSource(index: Int): Source { val fileSource = fileSystem.source(cleanFiles[index]) if (civilizedFileSystem) return fileSource lockingSourceCount++ return object : ForwardingSource(fileSource) { private var closed = false override fun close() { super.close() if (!closed) { closed = true synchronized(this@DiskLruCache) { lockingSourceCount-- if (lockingSourceCount == 0 && zombie) { removeEntry(this@Entry) } } } } } } } companion object { @JvmField val JOURNAL_FILE = "journal" @JvmField val JOURNAL_FILE_TEMP = "journal.tmp" @JvmField val JOURNAL_FILE_BACKUP = "journal.bkp" @JvmField val MAGIC = "libcore.io.DiskLruCache" @JvmField val VERSION_1 = "1" @JvmField val ANY_SEQUENCE_NUMBER: Long = -1 @JvmField val LEGAL_KEY_PATTERN = "[a-z0-9_-]{1,120}".toRegex() @JvmField val CLEAN = "CLEAN" @JvmField val DIRTY = "DIRTY" @JvmField val REMOVE = "REMOVE" @JvmField val READ = "READ" } }
okhttp/src/main/kotlin/okhttp3/internal/cache/DiskLruCache.kt
1771981182
package org.stepik.android.view.download.ui.activity import android.content.Context import android.content.Intent import android.content.res.ColorStateList import android.os.Bundle import android.view.MenuItem import androidx.activity.viewModels import androidx.core.content.ContextCompat import androidx.core.text.bold import androidx.core.text.buildSpannedString import androidx.core.widget.TextViewCompat import androidx.fragment.app.DialogFragment import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.SimpleItemAnimator import kotlinx.android.synthetic.main.activity_download.* import kotlinx.android.synthetic.main.empty_certificates.goToCatalog import kotlinx.android.synthetic.main.empty_downloading.* import kotlinx.android.synthetic.main.progress_bar_on_empty_screen.* import org.stepic.droid.R import org.stepic.droid.analytic.AmplitudeAnalytic import org.stepic.droid.base.App import org.stepic.droid.base.FragmentActivityBase import org.stepic.droid.persistence.model.DownloadItem import org.stepic.droid.ui.dialogs.LoadingProgressDialogFragment import org.stepic.droid.ui.util.initCenteredToolbar import org.stepic.droid.ui.util.snackbar import org.stepic.droid.util.ProgressHelper import org.stepic.droid.util.TextUtil import org.stepik.android.domain.course.analytic.CourseViewSource import org.stepik.android.model.Course import org.stepik.android.presentation.download.DownloadPresenter import org.stepik.android.presentation.download.DownloadView import org.stepik.android.view.course_content.ui.dialog.RemoveCachedContentDialog import org.stepik.android.view.download.ui.adapter.DownloadedCoursesAdapterDelegate import org.stepik.android.view.ui.delegate.ViewStateDelegate import ru.nobird.android.ui.adapters.DefaultDelegateAdapter import ru.nobird.android.view.base.ui.extension.showIfNotExists import javax.inject.Inject class DownloadActivity : FragmentActivityBase(), DownloadView, RemoveCachedContentDialog.Callback { companion object { private const val MB = 1024 * 1024L fun createIntent(context: Context): Intent = Intent(context, DownloadActivity::class.java) } @Inject internal lateinit var viewModelFactory: ViewModelProvider.Factory private val downloadPresenter: DownloadPresenter by viewModels { viewModelFactory } private val downloadedCoursesAdapter: DefaultDelegateAdapter<DownloadItem> = DefaultDelegateAdapter() private val viewStateDelegate = ViewStateDelegate<DownloadView.State>() private val progressDialogFragment: DialogFragment = LoadingProgressDialogFragment.newInstance() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_download) injectComponent() initCenteredToolbar(R.string.downloads_title, showHomeButton = true) downloadedCoursesAdapter += DownloadedCoursesAdapterDelegate( onItemClick = { screenManager.showCourseModules(this, it.course, CourseViewSource.Downloads) }, onItemRemoveClick = ::showRemoveCourseDialog ) with(downloadsRecyclerView) { (itemAnimator as? SimpleItemAnimator)?.supportsChangeAnimations = false adapter = downloadedCoursesAdapter layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) addItemDecoration(DividerItemDecoration(this@DownloadActivity, LinearLayoutManager.VERTICAL)) } initViewStateDelegate() goToCatalog.setOnClickListener { screenManager.showCatalog(this) } downloadPresenter.fetchStorage() downloadPresenter.fetchDownloadedCourses() TextViewCompat.setCompoundDrawableTintList(downloadsOtherApps, ColorStateList.valueOf(ContextCompat.getColor(this, R.color.color_overlay_yellow))) TextViewCompat.setCompoundDrawableTintList(downloadsStepik, ColorStateList.valueOf(ContextCompat.getColor(this, R.color.color_overlay_green))) TextViewCompat.setCompoundDrawableTintList(downloadsFree, ColorStateList.valueOf(ContextCompat.getColor(this, R.color.color_elevation_overlay_2dp))) } private fun injectComponent() { App.component() .downloadComponentBuilder() .build() .inject(this) } override fun onStart() { super.onStart() downloadPresenter.attachView(this) } override fun onStop() { downloadPresenter.detachView(this) super.onStop() } override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) { android.R.id.home -> { onBackPressed() true } else -> super.onOptionsItemSelected(item) } private fun initViewStateDelegate() { viewStateDelegate.addState<DownloadView.State.Idle>() viewStateDelegate.addState<DownloadView.State.Loading>(loadProgressbarOnEmptyScreen) viewStateDelegate.addState<DownloadView.State.Empty>(emptyDownloading) viewStateDelegate.addState<DownloadView.State.DownloadedCoursesLoaded>(downloadStorageContainer, downloadsRecyclerView, downloadsStorageDivider) } override fun setState(state: DownloadView.State) { viewStateDelegate.switchState(state) if (state is DownloadView.State.DownloadedCoursesLoaded) { downloadedCoursesAdapter.items = state.courses } } override fun setBlockingLoading(isLoading: Boolean) { if (isLoading) { ProgressHelper.activate(progressDialogFragment, supportFragmentManager, LoadingProgressDialogFragment.TAG) } else { ProgressHelper.dismiss(supportFragmentManager, LoadingProgressDialogFragment.TAG) } } override fun setStorageInfo(contentSize: Long, avalableSize: Long, totalSize: Long) { downloadStorageUsed.text = buildSpannedString { bold { append(TextUtil.formatBytes(contentSize, MB)) } append(resources.getString(R.string.downloads_is_used_by_stepik)) } downloadsFree.text = resources.getString(R.string.downloads_free_space, TextUtil.formatBytes(avalableSize, MB)) downloadsStorageProgress.max = (totalSize / MB).toInt() downloadsStorageProgress.progress = ((totalSize - avalableSize) / MB).toInt() downloadsStorageProgress.secondaryProgress = (downloadsStorageProgress.progress + (contentSize / MB)).toInt() } private fun showRemoveCourseDialog(downloadItem: DownloadItem) { RemoveCachedContentDialog .newInstance(course = downloadItem.course) .showIfNotExists(supportFragmentManager, RemoveCachedContentDialog.TAG) } override fun onRemoveCourseDownloadConfirmed(course: Course) { analytic.reportAmplitudeEvent( AmplitudeAnalytic.Downloads.DELETED, mapOf( AmplitudeAnalytic.Downloads.PARAM_CONTENT to AmplitudeAnalytic.Downloads.Values.COURSE, AmplitudeAnalytic.Downloads.PARAM_SOURCE to AmplitudeAnalytic.Downloads.Values.DOWNLOADS ) ) downloadPresenter.removeCourseDownload(course) } override fun showRemoveTaskError() { root.snackbar(messageRes = R.string.downloads_remove_task_error) } }
app/src/main/java/org/stepik/android/view/download/ui/activity/DownloadActivity.kt
2773986314
package json.decoding import io.fluidsonic.json.* @Json class DefaultAnnotatedConstructor( val value: String ) { constructor(value: Int) : this(value.toString()) @Json.Constructor constructor(value: Long) : this(value.toString()) }
annotation-processor/test-cases/1/input/json/decoding/DefaultAnnotatedConstructor.kt
431092594
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.fileTypes.FileTypes import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFilePathWrapper import com.intellij.openapi.vfs.VirtualFileSystem import com.intellij.openapi.vfs.VirtualFileWithoutContent import com.intellij.testFramework.LightVirtualFileBase import org.jetbrains.plugins.github.api.GHRepositoryCoordinates /** * [fileManagerId] is a [org.jetbrains.plugins.github.pullrequest.data.GHPRFilesManagerImpl.id] which is required to differentiate files * between launches of a PR toolwindow. * This is necessary to make the files appear in "Recent Files" correctly. * See [com.intellij.vcs.editor.ComplexPathVirtualFileSystem.ComplexPath.sessionId] for details. */ abstract class GHRepoVirtualFile(protected val fileManagerId: String, val project: Project, val repository: GHRepositoryCoordinates) : LightVirtualFileBase("", null, 0), VirtualFileWithoutContent, VirtualFilePathWrapper { override fun enforcePresentableName() = true override fun getFileSystem(): VirtualFileSystem = GHPRVirtualFileSystem.getInstance() override fun getFileType(): FileType = FileTypes.UNKNOWN override fun getLength() = 0L override fun contentsToByteArray() = throw UnsupportedOperationException() override fun getInputStream() = throw UnsupportedOperationException() override fun getOutputStream(requestor: Any?, newModificationStamp: Long, newTimeStamp: Long) = throw UnsupportedOperationException() override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is GHRepoVirtualFile) return false if (fileManagerId != other.fileManagerId) return false if (project != other.project) return false if (repository != other.repository) return false return true } override fun hashCode(): Int { var result = fileManagerId.hashCode() result = 31 * result + project.hashCode() result = 31 * result + repository.hashCode() return result } }
plugins/github/src/org/jetbrains/plugins/github/pullrequest/GHRepoVirtualFile.kt
3928000376
// 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.util.io import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream import com.intellij.openapi.util.text.StringUtil import com.intellij.util.net.NetUtils import java.io.IOException import java.io.InputStream import java.net.URLConnection import java.nio.charset.Charset import java.util.regex.Pattern private const val BLOCK_SIZE = 16 * 1024 private val CHARSET_PATTERN = Pattern.compile("charset=([^;]+)") object HttpUrlConnectionUtil { @JvmStatic @Throws(IOException::class, ProcessCanceledException::class) fun readBytes(inputStream: InputStream, connection: URLConnection, progressIndicator: ProgressIndicator?): BufferExposingByteArrayOutputStream { val contentLength = connection.contentLength val out = BufferExposingByteArrayOutputStream(if (contentLength > 0) contentLength else BLOCK_SIZE) NetUtils.copyStreamContent(progressIndicator, inputStream, out, contentLength) return out } @JvmStatic @JvmOverloads @Throws(IOException::class, ProcessCanceledException::class) fun readString(inputStream: InputStream, connection: URLConnection, progressIndicator: ProgressIndicator? = null): String { val byteStream = readBytes(inputStream, connection, progressIndicator) return if (byteStream.size() == 0) "" else String(byteStream.internalBuffer, 0, byteStream.size(), getCharset(connection)) } @Throws(IOException::class) @JvmStatic fun getCharset(urlConnection: URLConnection): Charset { val contentType = urlConnection.contentType if (!contentType.isNullOrEmpty()) { val m = CHARSET_PATTERN.matcher(contentType) if (m.find()) { try { return Charset.forName(StringUtil.unquoteString(m.group(1))) } catch (e: IllegalArgumentException) { throw IOException("unknown charset ($contentType)", e) } } } return Charsets.UTF_8 } }
platform/platform-api/src/com/intellij/util/io/HttpUrlConnectionUtil.kt
3875391063
// 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.ide.actions import com.google.common.collect.Sets import com.intellij.ide.IdeBundle import com.intellij.ide.caches.CachesInvalidator import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.text.HtmlChunk import com.intellij.ui.components.Link import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.ui.layout.* import com.intellij.util.ui.JBUI import java.awt.BorderLayout import javax.swing.Action import javax.swing.JCheckBox import javax.swing.JPanel private var Action.text get() = getValue(Action.NAME) set(value) = putValue(Action.NAME, value) class InvalidateCachesDialog( project: Project?, private val canRestart: Boolean, private val invalidators: List<CachesInvalidator>, ) : DialogWrapper(project) { private val JUST_RESTART_CODE = NEXT_USER_EXIT_CODE + 3 private val enabledInvalidators: MutableSet<CachesInvalidator> = Sets.newIdentityHashSet() fun getSelectedInvalidators() : List<CachesInvalidator> { if (!isOK) return emptyList() return invalidators.filter { it.description == null || it in enabledInvalidators } } override fun getHelpId() = "invalidate-cache-restart" init { title = IdeBundle.message("dialog.title.invalidate.caches") setResizable(false) init() okAction.text = when { canRestart -> IdeBundle.message("button.invalidate.and.restart") else -> IdeBundle.message("button.invalidate.and.exit") } cancelAction.text = IdeBundle.message("button.cancel.without.mnemonic") } fun isRestartOnly() = canRestart && exitCode == JUST_RESTART_CODE override fun createSouthAdditionalPanel(): JPanel? { if (!canRestart) return null val link = Link(IdeBundle.message("link.just.restart")) { close(JUST_RESTART_CODE) } val panel = NonOpaquePanel(BorderLayout()) panel.border = JBUI.Borders.emptyLeft(10) panel.add(link) return panel } override fun createCenterPanel() = panel { row { label( HtmlChunk .html() .addText(IdeBundle.message("dialog.message.caches.will.be.invalidated")) .toString() ).growPolicy(GrowPolicy.MEDIUM_TEXT).constraints(CCFlags.growY) } //we keep the original order as it comes from the extensions order val invalidatorsWithDescriptor = invalidators.mapNotNull { it.description?.to(it) } if (invalidatorsWithDescriptor.isNotEmpty()) { row { label(IdeBundle.message("dialog.message.the.following.items")) for ((text, descr) in invalidatorsWithDescriptor) { row { val defaultValue = descr.optionalCheckboxDefaultValue() val updateSelected = { cb: JCheckBox -> when { cb.isSelected -> enabledInvalidators += descr else -> enabledInvalidators -= descr } } val isSelected = defaultValue ?: true checkBox(text, isSelected, comment = descr.comment, actionListener = { _, cb -> updateSelected(cb) } ).component.apply { isEnabled = defaultValue != null updateSelected(this) } } } } } } }
platform/platform-impl/src/com/intellij/ide/actions/InvalidateCachesDialog.kt
3587451516
package org.livingdoc.engine.execution.examples /** * This function executes a before hook, the main function and an after hook in this order. * It ensures, that the after hook is executed even if there was an exception in before or main function * @param before the function that is called before the main part * @param body the main function * @param after the function that is called after the main part */ @Suppress("TooGenericExceptionCaught") fun <T> executeWithBeforeAndAfter(before: () -> Unit, body: () -> T, after: () -> Unit): T { var exception: Throwable? = null val value = try { before.invoke() body.invoke() } catch (e: Throwable) { exception = e null } finally { runAfter(after, exception) } return value ?: throw IllegalStateException() } /** * This function handles the execution of the after hook. It manages occurring exceptions too. * @param after the after hook that should be executed * @param exception a possibly occurred exception in the before or main function */ @Suppress("TooGenericExceptionCaught") private fun runAfter(after: () -> Unit, exception: Throwable?) { var originalException = exception try { after.invoke() } catch (afterException: Throwable) { if (originalException != null) { originalException.addSuppressed(afterException) } else { originalException = afterException } } finally { if (originalException != null) { throw originalException } } }
livingdoc-engine/src/main/kotlin/org/livingdoc/engine/execution/examples/Util.kt
1823493827
@file:Suppress("unused") package com.agoda.kakao.edit import android.content.Context import androidx.annotation.StringRes import androidx.test.espresso.ViewAssertion import androidx.test.espresso.assertion.ViewAssertions import androidx.test.platform.app.InstrumentationRegistry import com.agoda.kakao.common.assertions.BaseAssertions import com.agoda.kakao.common.matchers.TextInputLayoutCounterEnabledMatcher import com.agoda.kakao.common.matchers.TextInputLayoutErrorEnabledMatcher import com.agoda.kakao.common.matchers.TextInputLayoutHintEnabledMatcher import com.agoda.kakao.common.utilities.getResourceString import com.google.android.material.textfield.TextInputLayout /** * Provides assertions for TextInputLayout */ interface TextInputLayoutAssertions : BaseAssertions { /** * Checks if this input layout has given hint * * @param hint - hint text to be checked */ fun hasHint(hint: String) { view.check(ViewAssertion { view, notFoundException -> if (view is TextInputLayout) { if (hint != view.hint) { throw AssertionError( "Expected hint is $hint," + " but actual is ${view.hint}" ) } } else { notFoundException?.let { throw AssertionError(it) } } }) } fun hasHint(@StringRes resId: Int) { hasHint(getResourceString(resId)) } fun isHintEnabled() { view.check(ViewAssertions.matches(TextInputLayoutHintEnabledMatcher(true))) } fun isHintDisabled() { view.check(ViewAssertions.matches(TextInputLayoutHintEnabledMatcher(false))) } fun hasError(@StringRes resId: Int) { hasError(getResourceString(resId)) } fun hasError(error: String) { view.check(ViewAssertion { view, notFoundException -> if (view is TextInputLayout) { if (error != view.error) { throw AssertionError( "Expected error is $error," + " but actual is ${view.error}" ) } } else { notFoundException?.let { throw AssertionError(it) } } }) } fun isErrorEnabled() { view.check(ViewAssertions.matches(TextInputLayoutErrorEnabledMatcher(true))) } fun isErrorDisabled() { view.check(ViewAssertions.matches(TextInputLayoutErrorEnabledMatcher(false))) } fun hasCounterMaxLength(length: Int) { view.check(ViewAssertion { view, notFoundException -> if (view is TextInputLayout) { if (length != view.counterMaxLength) { throw AssertionError( "Expected counter max length is $length," + " but actual is ${view.counterMaxLength}" ) } } else { notFoundException?.let { throw AssertionError(it) } } }) } fun isCounterEnabled() { view.check(ViewAssertions.matches(TextInputLayoutCounterEnabledMatcher(true))) } fun isCounterDisabled() { view.check(ViewAssertions.matches(TextInputLayoutCounterEnabledMatcher(false))) } }
kakao/src/main/kotlin/com/agoda/kakao/edit/TextInputLayoutAssertions.kt
776390973
package com.antyzero.smoksmog.ui.screen.order interface ItemTouchHelperAdapter { fun onItemMove(fromPosition: Int, toPosition: Int) fun onItemDismiss(position: Int) }
app/src/main/kotlin/com/antyzero/smoksmog/ui/screen/order/ItemTouchHelperAdapter.kt
3642379243
package slatekit.providers.datadog import io.micrometer.datadog.DatadogConfig import java.time.* //import org.threeten.bp.Duration /** * Configuration class for datadog */ data class DDConfig(val apiKey:String, val appKey:String, val seconds:Int) : DatadogConfig { override fun apiKey():String = apiKey override fun applicationKey(): String? = appKey override fun step(): Duration = Duration.ofSeconds(10) override fun get(k:String):String? = null }
src/ext/kotlin/slatekit-providers-datadog/src/main/kotlin/slatekit/providers/datadog/DDConfig.kt
1237222653
package runtime.basic.tostring3 import kotlin.test.* fun testByte() { val values = ByteArray(2) values[0] = Byte.MIN_VALUE values[1] = Byte.MAX_VALUE for (v in values) { println(v) } } fun testShort() { val values = ShortArray(2) values[0] = Short.MIN_VALUE values[1] = Short.MAX_VALUE for (v in values) { println(v) } } fun testInt() { val values = IntArray(2) values[0] = Int.MIN_VALUE values[1] = Int.MAX_VALUE for (v in values) { println(v) } } fun testLong() { val values = LongArray(2) values[0] = Long.MIN_VALUE values[1] = Long.MAX_VALUE for (v in values) { println(v) } } fun testFloat() { val values = FloatArray(5) values[0] = Float.MIN_VALUE values[1] = Float.MAX_VALUE values[2] = Float.NEGATIVE_INFINITY values[3] = Float.POSITIVE_INFINITY values[4] = Float.NaN for (v in values) { println(v) } } fun testDouble() { val values = DoubleArray(5) values[0] = Double.MIN_VALUE values[1] = Double.MAX_VALUE values[2] = Double.NEGATIVE_INFINITY values[3] = Double.POSITIVE_INFINITY values[4] = Double.NaN for (v in values) { println(v) } } @Test fun runTest() { testByte() testShort() testInt() testLong() testFloat() testDouble() }
backend.native/tests/runtime/basic/tostring3.kt
1493776195
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.konan.libgit import kotlinx.cinterop.* import libgit2.* class GitRemote(val repository: GitRepository, val handle: CPointer<git_remote>) { fun close() = git_remote_free(handle) val url: String get() = git_remote_url(handle)!!.toKString() val name: String = git_remote_name(handle)!!.toKString() }
samples/gitchurn/src/main/kotlin/org/konan/libgit/GitRemote.kt
2169974921
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT var _l: Any = "" var l: Any get() = _l set(v) { _l = {} } fun box(): String { l = "" // to invoke the setter val enclosingMethod = l.javaClass.getEnclosingMethod() if (enclosingMethod?.getName() != "setL") return "method: $enclosingMethod" val enclosingClass = l.javaClass.getEnclosingClass()!!.getName() if (enclosingClass != "LambdaInPropertySetterKt") return "enclosing class: $enclosingClass" val declaringClass = l.javaClass.getDeclaringClass() if (declaringClass != null) return "anonymous function has a declaring class: $declaringClass" return "OK" }
backend.native/tests/external/codegen/box/reflection/enclosing/lambdaInPropertySetter.kt
895877946
//KT-3450 get and invoke are not parsed in one expression public class A(val s: String) { operator fun get(i: Int) : A = A("$s + $i") operator fun invoke(builder : A.() -> String): String = builder() } fun x(y : String) : A = A(y) fun foo() = x("aaa")[42] { "$s!!" } fun box() = if (foo() == "aaa + 42!!") "OK" else "fail"
backend.native/tests/external/codegen/box/functions/invoke/kt3450getAndInvoke.kt
1433794015
/* * Copyright (C) 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 androidx.navigation import android.content.Context import android.content.res.Resources import android.net.Uri import android.os.Bundle import android.util.AttributeSet import androidx.annotation.CallSuper import androidx.annotation.IdRes import androidx.annotation.RestrictTo import androidx.collection.SparseArrayCompat import androidx.collection.valueIterator import androidx.core.content.res.use import androidx.navigation.common.R import java.util.regex.Pattern import kotlin.reflect.KClass /** * NavDestination represents one node within an overall navigation graph. * * Each destination is associated with a [Navigator] which knows how to navigate to this * particular destination. * * Destinations declare a set of [actions][putAction] that they * support. These actions form a navigation API for the destination; the same actions declared * on different destinations that fill similar roles allow application code to navigate based * on semantic intent. * * Each destination has a set of [arguments][arguments] that will * be applied when [navigating][NavController.navigate] to that destination. * Any default values for those arguments can be overridden at the time of navigation. * * NavDestinations should be created via [Navigator.createDestination]. */ public open class NavDestination( /** * The name associated with this destination's [Navigator]. */ public val navigatorName: String ) { /** * This optional annotation allows tooling to offer auto-complete for the * `android:name` attribute. This should match the class type passed to * [parseClassFromName] when parsing the * `android:name` attribute. */ @kotlin.annotation.Retention(AnnotationRetention.BINARY) @Target(AnnotationTarget.ANNOTATION_CLASS, AnnotationTarget.CLASS) public annotation class ClassType(val value: KClass<*>) /** @suppress */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public class DeepLinkMatch( public val destination: NavDestination, @get:Suppress("NullableCollection") // Needed for nullable bundle public val matchingArgs: Bundle?, private val isExactDeepLink: Boolean, private val matchingPathSegments: Int, private val hasMatchingAction: Boolean, private val mimeTypeMatchLevel: Int ) : Comparable<DeepLinkMatch> { override fun compareTo(other: DeepLinkMatch): Int { // Prefer exact deep links if (isExactDeepLink && !other.isExactDeepLink) { return 1 } else if (!isExactDeepLink && other.isExactDeepLink) { return -1 } // Then prefer most exact match path segments val pathSegmentDifference = matchingPathSegments - other.matchingPathSegments if (pathSegmentDifference > 0) { return 1 } else if (pathSegmentDifference < 0) { return -1 } if (matchingArgs != null && other.matchingArgs == null) { return 1 } else if (matchingArgs == null && other.matchingArgs != null) { return -1 } if (matchingArgs != null) { val sizeDifference = matchingArgs.size() - other.matchingArgs!!.size() if (sizeDifference > 0) { return 1 } else if (sizeDifference < 0) { return -1 } } if (hasMatchingAction && !other.hasMatchingAction) { return 1 } else if (!hasMatchingAction && other.hasMatchingAction) { return -1 } return mimeTypeMatchLevel - other.mimeTypeMatchLevel } } /** * Gets the [NavGraph] that contains this destination. This will be set when a * destination is added to a NavGraph via [NavGraph.addDestination]. */ public var parent: NavGraph? = null /** @suppress */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public set private var idName: String? = null /** * The descriptive label of this destination. */ public var label: CharSequence? = null private val deepLinks = mutableListOf<NavDeepLink>() private val actions: SparseArrayCompat<NavAction> = SparseArrayCompat() private var _arguments: MutableMap<String, NavArgument> = mutableMapOf() /** * The arguments supported by this destination. Returns a read-only map of argument names * to [NavArgument] objects that can be used to check the type, default value * and nullability of the argument. * * To add and remove arguments for this NavDestination * use [addArgument] and [removeArgument]. * @return Read-only map of argument names to arguments. */ public val arguments: Map<String, NavArgument> get() = _arguments.toMap() /** * NavDestinations should be created via [Navigator.createDestination]. * * This constructor requires that the given Navigator has a [Navigator.Name] annotation. */ public constructor(navigator: Navigator<out NavDestination>) : this( NavigatorProvider.getNameForNavigator( navigator.javaClass ) ) /** * Called when inflating a destination from a resource. * * @param context local context performing inflation * @param attrs attrs to parse during inflation */ @CallSuper public open fun onInflate(context: Context, attrs: AttributeSet) { context.resources.obtainAttributes(attrs, R.styleable.Navigator).use { array -> route = array.getString(R.styleable.Navigator_route) if (array.hasValue(R.styleable.Navigator_android_id)) { id = array.getResourceId(R.styleable.Navigator_android_id, 0) idName = getDisplayName(context, id) } label = array.getText(R.styleable.Navigator_android_label) } } /** * The destination's unique ID. This should be an ID resource generated by * the Android resource system. */ @get:IdRes public var id: Int = 0 set(@IdRes id) { field = id idName = null } /** * The destination's unique route. Setting this will also update the [id] of the destinations * so custom destination ids should only be set after setting the route. * * @return this destination's route, or null if no route is set * * @throws IllegalArgumentException is the given route is empty */ public var route: String? = null set(route) { if (route == null) { id = 0 } else { require(route.isNotBlank()) { "Cannot have an empty route" } val internalRoute = createRoute(route) id = internalRoute.hashCode() addDeepLink(internalRoute) } deepLinks.remove(deepLinks.firstOrNull { it.uriPattern == createRoute(field) }) field = route } /** * @hide */ @get:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public open val displayName: String get() = idName ?: id.toString() /** * Checks the given deep link [Uri], and determines whether it matches a Uri pattern added * to the destination by a call to [addDeepLink] . It returns `true` * if the deep link is a valid match, and `false` otherwise. * * This should be called prior to [NavController.navigate] to ensure the deep link * can be navigated to. * * @param deepLink to the destination reachable from the current NavGraph * @return True if the deepLink exists for the destination. * @see NavDestination.addDeepLink * @see NavController.navigate * @see NavDestination.hasDeepLink */ public open fun hasDeepLink(deepLink: Uri): Boolean { return hasDeepLink(NavDeepLinkRequest(deepLink, null, null)) } /** * Checks the given [NavDeepLinkRequest], and determines whether it matches a * [NavDeepLink] added to the destination by a call to * [addDeepLink]. It returns `true` if the request is a valid * match, and `false` otherwise. * * This should be called prior to [NavController.navigate] to * ensure the deep link can be navigated to. * * @param deepLinkRequest to the destination reachable from the current NavGraph * @return True if the deepLink exists for the destination. * @see NavDestination.addDeepLink * @see NavController.navigate */ public open fun hasDeepLink(deepLinkRequest: NavDeepLinkRequest): Boolean { return matchDeepLink(deepLinkRequest) != null } /** * Add a deep link to this destination. Matching Uris sent to * [NavController.handleDeepLink] or [NavController.navigate] will * trigger navigating to this destination. * * In addition to a direct Uri match, the following features are supported: * * - Uris without a scheme are assumed as http and https. For example, * `www.example.com` will match `http://www.example.com` and * `https://www.example.com`. * - Placeholders in the form of `{placeholder_name}` matches 1 or more * characters. The parsed value of the placeholder will be available in the arguments * [Bundle] with a key of the same name. For example, * `http://www.example.com/users/{id}` will match * `http://www.example.com/users/4`. * - The `.*` wildcard can be used to match 0 or more characters. * * These Uris can be declared in your navigation XML files by adding one or more * `<deepLink app:uri="uriPattern" />` elements as * a child to your destination. * * Deep links added in navigation XML files will automatically replace instances of * `${applicationId}` with the applicationId of your app. * Programmatically added deep links should use [Context.getPackageName] directly * when constructing the uriPattern. * @param uriPattern The uri pattern to add as a deep link * @see NavController.handleDeepLink * @see NavController.navigate * @see NavDestination.addDeepLink */ public fun addDeepLink(uriPattern: String) { addDeepLink(NavDeepLink.Builder().setUriPattern(uriPattern).build()) } /** * Add a deep link to this destination. Uris that match the given [NavDeepLink] uri * sent to [NavController.handleDeepLink] or * [NavController.navigate] will trigger navigating to this * destination. * * In addition to a direct Uri match, the following features are supported: * * Uris without a scheme are assumed as http and https. For example, * `www.example.com` will match `http://www.example.com` and * `https://www.example.com`. * Placeholders in the form of `{placeholder_name}` matches 1 or more * characters. The String value of the placeholder will be available in the arguments * [Bundle] with a key of the same name. For example, * `http://www.example.com/users/{id}` will match * `http://www.example.com/users/4`. * The `.*` wildcard can be used to match 0 or more characters. * * These Uris can be declared in your navigation XML files by adding one or more * `<deepLink app:uri="uriPattern" />` elements as * a child to your destination. * * Custom actions and mimetypes are also supported by [NavDeepLink] and can be declared * in your navigation XML files by adding * `<app:action="android.intent.action.SOME_ACTION" />` or * `<app:mimetype="type/subtype" />` as part of your deepLink declaration. * * Deep link Uris, actions, and mimetypes added in navigation XML files will automatically * replace instances of `${applicationId}` with the applicationId of your app. * Programmatically added deep links should use [Context.getPackageName] directly * when constructing the uriPattern. * * When matching deep links for calls to [NavController.handleDeepLink] or * [NavController.navigate] the order of precedence is as follows: * the deep link with the most matching arguments will be chosen, followed by the deep link * with a matching action, followed by the best matching mimeType (e.i. when matching * mimeType image/jpg: image/ * > *\/jpg > *\/ *). * @param navDeepLink The NavDeepLink to add as a deep link * @see NavController.handleDeepLink * @see NavController.navigate */ public fun addDeepLink(navDeepLink: NavDeepLink) { val missingRequiredArguments = arguments.filterValues { !it.isNullable && !it.isDefaultValuePresent } .keys .filter { it !in navDeepLink.argumentsNames } require(missingRequiredArguments.isEmpty()) { "Deep link ${navDeepLink.uriPattern} can't be used to open destination $this.\n" + "Following required arguments are missing: $missingRequiredArguments" } deepLinks.add(navDeepLink) } /** * Determines if this NavDestination has a deep link matching the given Uri. * @param navDeepLinkRequest The request to match against all deep links added in * [addDeepLink] * @return The matching [NavDestination] and the appropriate [Bundle] of arguments * extracted from the Uri, or null if no match was found. * @suppress */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public open fun matchDeepLink(navDeepLinkRequest: NavDeepLinkRequest): DeepLinkMatch? { if (deepLinks.isEmpty()) { return null } var bestMatch: DeepLinkMatch? = null for (deepLink in deepLinks) { val uri = navDeepLinkRequest.uri // includes matching args for path, query, and fragment val matchingArguments = if (uri != null) deepLink.getMatchingArguments(uri, arguments) else null val matchingPathSegments = deepLink.calculateMatchingPathSegments(uri) val requestAction = navDeepLinkRequest.action val matchingAction = requestAction != null && requestAction == deepLink.action val mimeType = navDeepLinkRequest.mimeType val mimeTypeMatchLevel = if (mimeType != null) deepLink.getMimeTypeMatchRating(mimeType) else -1 if (matchingArguments != null || matchingAction || mimeTypeMatchLevel > -1) { val newMatch = DeepLinkMatch( this, matchingArguments, deepLink.isExactDeepLink, matchingPathSegments, matchingAction, mimeTypeMatchLevel ) if (bestMatch == null || newMatch > bestMatch) { bestMatch = newMatch } } } return bestMatch } /** * Build an array containing the hierarchy from the root down to this destination. * * @param previousDestination the previous destination we are starting at * @return An array containing all of the ids from the previous destination (or the root of * the graph if null) to this destination * @suppress */ @JvmOverloads @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public fun buildDeepLinkIds(previousDestination: NavDestination? = null): IntArray { val hierarchy = ArrayDeque<NavDestination>() var current: NavDestination? = this do { val parent = current!!.parent if ( // If the current destination is a sibling of the previous, just add it straightaway previousDestination?.parent != null && previousDestination.parent!!.findNode(current.id) === current ) { hierarchy.addFirst(current) break } if (parent == null || parent.startDestinationId != current.id) { hierarchy.addFirst(current) } if (parent == previousDestination) { break } current = parent } while (current != null) return hierarchy.toList().map { it.id }.toIntArray() } /** * @return Whether this NavDestination supports outgoing actions * @see NavDestination.putAction * @suppress */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public open fun supportsActions(): Boolean { return true } /** * Returns the [NavAction] for the given action ID. This will recursively check the * [parent][getParent] of this destination if the action destination is not found in * this destination. * * @param id action ID to fetch * @return the [NavAction] mapped to the given action id, or null if one has not been set */ public fun getAction(@IdRes id: Int): NavAction? { val destination = if (actions.isEmpty) null else actions[id] // Search the parent for the given action if it is not found in this destination return destination ?: parent?.run { getAction(id) } } /** * Creates a [NavAction] for the given [destId] and associates it with the [actionId]. * * @param actionId action ID to bind * @param destId destination ID for the given action */ public fun putAction(@IdRes actionId: Int, @IdRes destId: Int) { putAction(actionId, NavAction(destId)) } /** * Sets the [NavAction] destination for an action ID. * * @param actionId action ID to bind * @param action action to associate with this action ID * @throws UnsupportedOperationException this destination is considered a terminal destination * and does not support actions */ public fun putAction(@IdRes actionId: Int, action: NavAction) { if (!supportsActions()) { throw UnsupportedOperationException( "Cannot add action $actionId to $this as it does not support actions, " + "indicating that it is a terminal destination in your navigation graph and " + "will never trigger actions." ) } require(actionId != 0) { "Cannot have an action with actionId 0" } actions.put(actionId, action) } /** * Unsets the [NavAction] for an action ID. * * @param actionId action ID to remove */ public fun removeAction(@IdRes actionId: Int) { actions.remove(actionId) } /** * Sets an argument type for an argument name * * @param argumentName argument object to associate with destination * @param argument argument object to associate with destination */ public fun addArgument(argumentName: String, argument: NavArgument) { _arguments[argumentName] = argument } /** * Unsets the argument type for an argument name. * * @param argumentName argument to remove */ public fun removeArgument(argumentName: String) { _arguments.remove(argumentName) } /** * Combines the default arguments for this destination with the arguments provided * to construct the final set of arguments that should be used to navigate * to this destination. * @suppress */ @Suppress("NullableCollection") // Needed for nullable bundle @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public fun addInDefaultArgs(args: Bundle?): Bundle? { if (args == null && _arguments.isNullOrEmpty()) { return null } val defaultArgs = Bundle() for ((key, value) in _arguments) { value.putDefaultValue(key, defaultArgs) } if (args != null) { defaultArgs.putAll(args) for ((key, value) in _arguments) { require(value.verify(key, defaultArgs)) { "Wrong argument type for '$key' in argument bundle. ${value.type.name} " + "expected." } } } return defaultArgs } /** * Parses a dynamic label containing arguments into a String. * * Supports String Resource arguments by parsing `R.string` values of `ReferenceType` * arguments found in `android:label` into their String values. * * Returns `null` if label is null. * * Returns the original label if the label was a static string. * * @param context Context used to resolve a resource's name * @param bundle Bundle containing the arguments used in the label * @return The parsed string or null if the label is null * @throws IllegalArgumentException if an argument provided in the label cannot be found in * the bundle, or if the label contains a string template but the bundle is null */ public fun fillInLabel(context: Context, bundle: Bundle?): String? { val label = label ?: return null val fillInPattern = Pattern.compile("\\{(.+?)\\}") val matcher = fillInPattern.matcher(label) val builder = StringBuffer() while (matcher.find()) { val argName = matcher.group(1) if (bundle != null && bundle.containsKey(argName)) { matcher.appendReplacement(builder, "") val argType = argName?.let { arguments[argName]?.type } if (argType == NavType.ReferenceType) { val value = context.getString(bundle.getInt(argName)) builder.append(value) } else { builder.append(bundle.getString(argName)) } } else { throw IllegalArgumentException( "Could not find \"$argName\" in $bundle to fill label \"$label\"" ) } } matcher.appendTail(builder) return builder.toString() } override fun toString(): String { val sb = StringBuilder() sb.append(javaClass.simpleName) sb.append("(") if (idName == null) { sb.append("0x") sb.append(Integer.toHexString(id)) } else { sb.append(idName) } sb.append(")") if (!route.isNullOrBlank()) { sb.append(" route=") sb.append(route) } if (label != null) { sb.append(" label=") sb.append(label) } return sb.toString() } override fun equals(other: Any?): Boolean { if (other == null || other !is NavDestination) return false val equalDeepLinks = deepLinks.intersect(other.deepLinks).size == deepLinks.size val equalActions = actions.size() == other.actions.size() && actions.valueIterator().asSequence().all { other.actions.containsValue(it) } && other.actions.valueIterator().asSequence().all { actions.containsValue(it) } val equalArguments = arguments.size == other.arguments.size && arguments.asSequence().all { other.arguments.containsKey(it.key) && other.arguments[it.key] == it.value } && other.arguments.asSequence().all { arguments.containsKey(it.key) && arguments[it.key] == it.value } return id == other.id && route == other.route && equalDeepLinks && equalActions && equalArguments } @Suppress("DEPRECATION") override fun hashCode(): Int { var result = id result = 31 * result + route.hashCode() deepLinks.forEach { result = 31 * result + it.uriPattern.hashCode() result = 31 * result + it.action.hashCode() result = 31 * result + it.mimeType.hashCode() } actions.valueIterator().forEach { value -> result = 31 * result + value.destinationId result = 31 * result + value.navOptions.hashCode() value.defaultArguments?.keySet()?.forEach { result = 31 * result + value.defaultArguments!!.get(it).hashCode() } } arguments.keys.forEach { result = 31 * result + it.hashCode() result = 31 * result + arguments[it].hashCode() } return result } public companion object { private val classes = mutableMapOf<String, Class<*>>() /** * Parse the class associated with this destination from a raw name, generally extracted * from the `android:name` attribute added to the destination's XML. This should * be the class providing the visual representation of the destination that the * user sees after navigating to this destination. * * This method does name -> Class caching and should be strongly preferred over doing your * own parsing if your [Navigator] supports the `android:name` attribute to * give consistent behavior across all Navigators. * * @param context Context providing the package name for use with relative class names and the * ClassLoader * @param name Absolute or relative class name. Null names will be ignored. * @param expectedClassType The expected class type * @return The parsed class * @throws IllegalArgumentException if the class is not found in the provided Context's * ClassLoader or if the class is not of the expected type */ @Suppress("UNCHECKED_CAST") @JvmStatic protected fun <C> parseClassFromName( context: Context, name: String, expectedClassType: Class<out C?> ): Class<out C?> { var innerName = name if (innerName[0] == '.') { innerName = context.packageName + innerName } var clazz = classes[innerName] if (clazz == null) { try { clazz = Class.forName(innerName, true, context.classLoader) classes[name] = clazz } catch (e: ClassNotFoundException) { throw IllegalArgumentException(e) } } require(expectedClassType.isAssignableFrom(clazz!!)) { "$innerName must be a subclass of $expectedClassType" } return clazz as Class<out C?> } /** * Used internally for NavDestinationTest * @suppress */ @JvmStatic @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public fun <C> parseClassFromNameInternal( context: Context, name: String, expectedClassType: Class<out C?> ): Class<out C?> { return parseClassFromName(context, name, expectedClassType) } /** * Retrieve a suitable display name for a given id. * @param context Context used to resolve a resource's name * @param id The id to get a display name for * @return The resource's name if it is a valid id or just the id itself if it is not * a valid resource * @hide */ @JvmStatic @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public fun getDisplayName(context: Context, id: Int): String { // aapt-generated IDs have the high byte nonzero, // so anything below that cannot be a valid resource id return if (id <= 0x00FFFFFF) { id.toString() } else try { context.resources.getResourceName(id) } catch (e: Resources.NotFoundException) { id.toString() } } /** * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public fun createRoute(route: String?): String = if (route != null) "android-app://androidx.navigation/$route" else "" /** * Provides a sequence of the NavDestination's hierarchy. The hierarchy starts with this * destination itself and is then followed by this destination's [NavDestination.parent], then that * graph's parent, and up the hierarchy until you've reached the root navigation graph. */ @JvmStatic public val NavDestination.hierarchy: Sequence<NavDestination> get() = generateSequence(this) { it.parent } } }
navigation/navigation-common/src/main/java/androidx/navigation/NavDestination.kt
4157142165
package abi42_0_0.host.exp.exponent.modules.api.components.reactnativestripesdk import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color import android.graphics.drawable.Drawable import android.os.Bundle import android.util.Base64 import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import androidx.appcompat.content.res.AppCompatResources import androidx.core.graphics.drawable.DrawableCompat import androidx.fragment.app.Fragment import com.stripe.android.paymentsheet.* import com.stripe.android.paymentsheet.model.PaymentOption import java.io.ByteArrayOutputStream class PaymentSheetFragment : Fragment() { private var paymentSheet: PaymentSheet? = null private var flowController: PaymentSheet.FlowController? = null private var paymentIntentClientSecret: String? = null private var setupIntentClientSecret: String? = null private lateinit var paymentSheetConfiguration: PaymentSheet.Configuration override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return FrameLayout(requireActivity()).also { it.visibility = View.GONE } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val merchantDisplayName = arguments?.getString("merchantDisplayName").orEmpty() val customerId = arguments?.getString("customerId").orEmpty() val customerEphemeralKeySecret = arguments?.getString("customerEphemeralKeySecret").orEmpty() val countryCode = arguments?.getString("countryCode").orEmpty() val testEnv = arguments?.getBoolean("testEnv") paymentIntentClientSecret = arguments?.getString("paymentIntentClientSecret").orEmpty() setupIntentClientSecret = arguments?.getString("setupIntentClientSecret").orEmpty() val paymentOptionCallback = object : PaymentOptionCallback { override fun onPaymentOption(paymentOption: PaymentOption?) { val intent = Intent(ON_PAYMENT_OPTION_ACTION) if (paymentOption != null) { val bitmap = getBitmapFromVectorDrawable(context, paymentOption.drawableResourceId) val imageString = getBase64FromBitmap(bitmap) intent.putExtra("label", paymentOption.label) intent.putExtra("image", imageString) } activity?.sendBroadcast(intent) } } val paymentResultCallback = object : PaymentSheetResultCallback { override fun onPaymentSheetResult(paymentResult: PaymentSheetResult) { val intent = Intent(ON_PAYMENT_RESULT_ACTION) intent.putExtra("paymentResult", paymentResult) activity?.sendBroadcast(intent) } } paymentSheetConfiguration = PaymentSheet.Configuration( merchantDisplayName = merchantDisplayName, customer = if (customerId.isNotEmpty() && customerEphemeralKeySecret.isNotEmpty()) PaymentSheet.CustomerConfiguration( id = customerId, ephemeralKeySecret = customerEphemeralKeySecret ) else null, googlePay = PaymentSheet.GooglePayConfiguration( environment = if (testEnv == true) PaymentSheet.GooglePayConfiguration.Environment.Test else PaymentSheet.GooglePayConfiguration.Environment.Production, countryCode = countryCode ) ) if (arguments?.getBoolean("customFlow") == true) { flowController = PaymentSheet.FlowController.create(this, paymentOptionCallback, paymentResultCallback) configureFlowController() } else { paymentSheet = PaymentSheet(this, paymentResultCallback) } val intent = Intent(ON_FRAGMENT_CREATED) activity?.sendBroadcast(intent) } fun present() { if (!paymentIntentClientSecret.isNullOrEmpty()) { paymentSheet?.presentWithPaymentIntent(paymentIntentClientSecret!!, paymentSheetConfiguration) } else if (!setupIntentClientSecret.isNullOrEmpty()) { paymentSheet?.presentWithSetupIntent(setupIntentClientSecret!!, paymentSheetConfiguration) } } fun presentPaymentOptions() { flowController?.presentPaymentOptions() } fun confirmPayment() { flowController?.confirm() } private fun configureFlowController() { val onFlowControllerConfigure = object : PaymentSheet.FlowController.ConfigCallback { override fun onConfigured(success: Boolean, error: Throwable?) { val paymentOption = flowController?.getPaymentOption() val intent = Intent(ON_CONFIGURE_FLOW_CONTROLLER) if (paymentOption != null) { val bitmap = getBitmapFromVectorDrawable(context, paymentOption.drawableResourceId) val imageString = getBase64FromBitmap(bitmap) intent.putExtra("label", paymentOption.label) intent.putExtra("image", imageString) } activity?.sendBroadcast(intent) } } if (!paymentIntentClientSecret.isNullOrEmpty()) { flowController?.configureWithPaymentIntent( paymentIntentClientSecret = paymentIntentClientSecret!!, configuration = paymentSheetConfiguration, callback = onFlowControllerConfigure ) } else if (!setupIntentClientSecret.isNullOrEmpty()) { flowController?.configureWithSetupIntent( setupIntentClientSecret = setupIntentClientSecret!!, configuration = paymentSheetConfiguration, callback = onFlowControllerConfigure ) } } } fun getBitmapFromVectorDrawable(context: Context?, drawableId: Int): Bitmap? { var drawable: Drawable? = AppCompatResources.getDrawable(context!!, drawableId) if (drawable == null) { return null } drawable = DrawableCompat.wrap(drawable).mutate() val bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888) bitmap.eraseColor(Color.WHITE) val canvas = Canvas(bitmap) drawable.setBounds(0, 0, canvas.width, canvas.height) drawable.draw(canvas) return bitmap } fun getBase64FromBitmap(bitmap: Bitmap?): String? { if (bitmap == null) { return null } val baos = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos) val imageBytes: ByteArray = baos.toByteArray() return Base64.encodeToString(imageBytes, Base64.DEFAULT) }
android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/host/exp/exponent/modules/api/components/reactnativestripesdk/PaymentSheetFragment.kt
4098578927
/** * ownCloud Android client application * * @author David González Verdugo * Copyright (C) 2020 ownCloud GmbH. * * This program 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. * * 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 com.owncloud.android.domain.exceptions class ServerNotReachableException : Exception()
owncloudDomain/src/main/java/com/owncloud/android/domain/exceptions/ServerNotReachableException.kt
1577586761
package com.goldenpiedevs.schedule.app.ui.widget import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.ComponentName import android.content.Context import android.content.Intent import android.net.Uri import android.widget.RemoteViews import com.goldenpiedevs.schedule.app.R import com.goldenpiedevs.schedule.app.core.ext.currentWeek import com.goldenpiedevs.schedule.app.core.ext.todayName import com.goldenpiedevs.schedule.app.ui.lesson.LessonActivity import com.goldenpiedevs.schedule.app.ui.lesson.LessonImplementation class ScheduleWidgetProvider : AppWidgetProvider() { override fun onUpdate(context: Context?, appWidgetManager: AppWidgetManager?, appWidgetIds: IntArray?) { appWidgetIds?.let { for (appWidgetId in it) { updateAppWidget(context, appWidgetManager, appWidgetId) } } super.onUpdate(context, appWidgetManager, appWidgetIds) } override fun onReceive(context: Context?, intent: Intent?) { when { intent?.action.equals(ACTION_SCHEDULED_UPDATE) || intent?.action.equals("android.appwidget.action.APPWIDGET_UPDATE") -> context?.let { val manager = AppWidgetManager.getInstance(it) val ids = manager.getAppWidgetIds(ComponentName(it, ScheduleWidgetProvider::class.java)) onUpdate(it, manager, ids) } intent?.action.equals(ACTION_OPEN_LESSON) -> context?.let { it.startActivity(Intent(it, LessonActivity::class.java) .apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK putExtra(LessonImplementation.LESSON_ID, intent!!.getStringExtra(LESSON_ID)) }) } } super.onReceive(context, intent) } companion object { const val ACTION_SCHEDULED_UPDATE = "com.goldenpiedevs.schedule.app.ui.widget.SCHEDULED_UPDATE" const val ACTION_OPEN_LESSON = "com.goldenpiedevs.schedule.app.ui.widget.ACTION_OPEN_LESSON" const val LESSON_ID = "com.goldenpiedevs.schedule.app.ui.widget.LESSON_ID" fun updateWidget(context: Context) { val intent = Intent(context, ScheduleWidgetProvider::class.java) intent.action = ACTION_SCHEDULED_UPDATE context.sendBroadcast(intent) } internal fun updateAppWidget(context: Context?, appWidgetManager: AppWidgetManager?, appWidgetId: Int) { context?.let { with(RemoteViews(it.packageName, R.layout.schedule_widget)) { val intent = Intent(context, WidgetService::class.java) intent.data = Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)) intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId) val toastIntent = Intent(context, ScheduleWidgetProvider::class.java) toastIntent.action = ScheduleWidgetProvider.ACTION_OPEN_LESSON intent.data = Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)) val toastPendingIntent = PendingIntent.getBroadcast(context, 0, toastIntent, PendingIntent.FLAG_UPDATE_CURRENT) setPendingIntentTemplate(R.id.widget_list, toastPendingIntent) setRemoteAdapter(R.id.widget_list, intent) setEmptyView(R.id.widget_list, R.id.widget_list_empty_view) setTextViewText(R.id.widget_day_name, todayName.substring(0, 1).toUpperCase() + todayName.substring(1)) setTextViewText(R.id.widget_day_date, "${currentWeek + 1} ${context.getString(R.string.week)}") appWidgetManager?.notifyAppWidgetViewDataChanged(appWidgetId, R.id.widget_list) appWidgetManager?.updateAppWidget(appWidgetId, this) } } } } }
app/src/main/java/com/goldenpiedevs/schedule/app/ui/widget/ScheduleWidgetProvider.kt
104816711
// IS_APPLICABLE: false abstract class <caret>Owner { abstract fun f() }
plugins/kotlin/idea/tests/testData/intentions/declarations/convertMemberToExtension/outsideFunction.kt
1394004736
package zielu.gittoolbox import com.intellij.AbstractBundle import org.jetbrains.annotations.NonNls import org.jetbrains.annotations.PropertyKey internal object ResBundle : AbstractBundle(BUNDLE_NAME) { @JvmStatic fun message(@PropertyKey(resourceBundle = BUNDLE_NAME) key: String, vararg params: Any?): String { return getMessage(key, *params) } @JvmStatic fun on(): String { return message("common.on") } @JvmStatic fun disabled(): String { return message("common.disabled") } } @NonNls private const val BUNDLE_NAME = "zielu.gittoolbox.ResourceBundle"
src/main/kotlin/zielu/gittoolbox/ResBundle.kt
2348888476
package test fun foo() { "" // test/A1Kt }
plugins/kotlin/jvm-debugger/test/testData/positionManager/multiFileSameName/1/a1.kt
2761727243
/* * 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.notebooks.visualization.r.inlays import com.intellij.ide.ui.UISettings import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.ReadAction import com.intellij.openapi.application.invokeLater import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.FoldRegion import com.intellij.openapi.editor.Inlay import com.intellij.openapi.editor.event.CaretEvent import com.intellij.openapi.editor.event.CaretListener import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.editor.ex.EditorGutterComponentEx import com.intellij.openapi.editor.ex.FoldingListener import com.intellij.openapi.editor.ex.util.EditorScrollingPositionKeeper import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.concurrency.FutureResult import com.intellij.util.concurrency.NonUrgentExecutor import com.intellij.util.ui.update.MergingUpdateQueue import com.intellij.util.ui.update.Update import org.jetbrains.annotations.TestOnly import org.jetbrains.concurrency.CancellablePromise import org.jetbrains.plugins.notebooks.visualization.r.inlays.components.InlayProgressStatus import java.awt.Point import java.awt.event.ComponentAdapter import java.awt.event.ComponentEvent import java.util.concurrent.Future import kotlin.math.max import kotlin.math.min /** * Manages inlays. * * On project load subscribes * on editor opening/closing. * on adding/removing notebook cells * on any document changes * on folding actions * * On editor open checks the PSI structure and restores saved inlays. * * ToDo should be split into InlaysManager with all basics and NotebookInlaysManager with all specific. */ class EditorInlaysManager(val project: Project, private val editor: EditorImpl, val descriptor: InlayElementDescriptor) { private val inlays: MutableMap<PsiElement, NotebookInlayComponentPsi> = LinkedHashMap() private val inlayElements = LinkedHashSet<PsiElement>() private val scrollKeeper: EditorScrollingPositionKeeper = EditorScrollingPositionKeeper(editor) private val viewportQueue = MergingUpdateQueue(VIEWPORT_TASK_NAME, VIEWPORT_TIME_SPAN, true, null, project) @Volatile private var toolbarUpdateScheduled: Boolean = false init { addResizeListener() addCaretListener() addFoldingListener() addDocumentListener() addViewportListener() editor.settings.isRightMarginShown = false UISettings.instance.showEditorToolTip = false MouseWheelUtils.wrapEditorMouseWheelListeners(editor) restoreToolbars().onSuccess { restoreOutputs() } onCaretPositionChanged() ApplicationManager.getApplication().invokeLater { if (editor.isDisposed) return@invokeLater updateInlayComponentsWidth() } } fun dispose() { inlays.values.forEach { it.disposeInlay() it.dispose() } inlays.clear() inlayElements.clear() } fun updateCell(psi: PsiElement, inlayOutputs: List<InlayOutput>? = null, createTextOutput: Boolean = false): Future<Unit> { val result = FutureResult<Unit>() if (ApplicationManager.getApplication().isUnitTestMode && !isEnabledInTests) return result.apply { set(Unit) } ApplicationManager.getApplication().invokeLater { try { if (editor.isDisposed) { result.set(Unit) return@invokeLater } if (!psi.isValid) { getInlayComponent(psi)?.let { oldInlay -> removeInlay(oldInlay, cleanup = false) } result.set(Unit) return@invokeLater } if (isOutputPositionCollapsed(psi)) { result.set(Unit) return@invokeLater } val outputs = inlayOutputs ?: descriptor.getInlayOutputs(psi) if (outputs == null) { result.set(Unit) return@invokeLater } scrollKeeper.savePosition() getInlayComponent(psi)?.let { oldInlay -> removeInlay(oldInlay, cleanup = false) } if (outputs.isEmpty() && !createTextOutput) { result.set(Unit) return@invokeLater } val component = addInlayComponent(psi) if (outputs.isNotEmpty()) addInlayOutputs(component, outputs) if (createTextOutput) component.createOutputComponent() scrollKeeper.restorePosition(true) } catch (e: Throwable) { result.set(Unit) throw e } ApplicationManager.getApplication().invokeLater { try { scrollKeeper.savePosition() updateInlays() scrollKeeper.restorePosition(true) } finally { result.set(Unit) } } } return result } private fun isOutputPositionCollapsed(psiCell: PsiElement): Boolean = editor.foldingModel.isOffsetCollapsed(descriptor.getInlayOffset(psiCell)) fun addTextToInlay(psi: PsiElement, message: String, outputType: Key<*>) { invokeLater { scrollKeeper.savePosition() getInlayComponent(psi)?.addText(message, outputType) scrollKeeper.restorePosition(true) } } fun updateInlayProgressStatus(psi: PsiElement, progressStatus: InlayProgressStatus): Future<Unit> { val result = FutureResult<Unit>() ApplicationManager.getApplication().invokeLater { getInlayComponent(psi)?.updateProgressStatus(progressStatus) result.set(Unit) } return result } private fun updateInlaysForViewport() { invokeLater { if (editor.isDisposed) return@invokeLater val viewportRange = calculateViewportRange(editor) val expansionRange = calculateInlayExpansionRange(editor, viewportRange) for (element in inlayElements) { updateInlayForViewport(element, viewportRange, expansionRange) } } } private fun updateInlayForViewport(element: PsiElement, viewportRange: IntRange, expansionRange: IntRange) { val inlay = inlays[element] if (inlay != null) { val bounds = inlay.bounds val isInViewport = bounds.y <= viewportRange.last && bounds.y + bounds.height >= viewportRange.first inlay.onViewportChange(isInViewport) } else { if (element.textRange.startOffset in expansionRange) { updateCell(element) } } } private fun addInlayOutputs(inlayComponent: NotebookInlayComponentPsi, inlayOutputs: List<InlayOutput>) { inlayComponent.addInlayOutputs(inlayOutputs) { removeInlay(inlayComponent) } } private fun removeInlay(inlayComponent: NotebookInlayComponentPsi, cleanup: Boolean = true) { val cell = inlayComponent.cell if (cleanup && cell.isValid) descriptor.cleanup(cell) inlayComponent.parent?.remove(inlayComponent) inlayComponent.disposeInlay() inlayComponent.dispose() inlays.remove(cell) } private fun addFoldingListener() { data class Region(val textRange: TextRange, val isExpanded: Boolean) val listener = object : FoldingListener { private val regions = ArrayList<Region>() override fun onFoldRegionStateChange(region: FoldRegion) { if(region.isValid) { regions.add(Region(TextRange.create(region.startOffset, region.endOffset), region.isExpanded)) } } override fun onFoldProcessingEnd() { inlays.filter { pair -> isOutputPositionCollapsed(pair.key) }.forEach { removeInlay(it.value, cleanup = false) } inlayElements.filter { key -> regions.filter { it.isExpanded }.any { key.textRange.intersects(it.textRange) } }.forEach { updateCell(it) } regions.clear() updateInlays() } } editor.foldingModel.addListener(listener, editor.disposable) } private fun addDocumentListener() { editor.document.addDocumentListener(object : DocumentListener { override fun documentChanged(event: DocumentEvent) { if (project.isDisposed()) return if (!toolbarUpdateScheduled) { toolbarUpdateScheduled = true PsiDocumentManager.getInstance(project).performForCommittedDocument(editor.document) { try { scheduleIntervalUpdate(event.offset, event.newFragment.length) } finally { toolbarUpdateScheduled = false } } } if (!descriptor.shouldUpdateInlays(event)) return PsiDocumentManager.getInstance(project).performForCommittedDocument(editor.document) { updateInlays() } } }, editor.disposable) } private fun scheduleIntervalUpdate(offset: Int, length: Int) { val psiFile = descriptor.psiFile var node = psiFile.node.findLeafElementAt(offset)?.psi while (node != null && node.parent != psiFile) { node = node.parent } inlayElements.filter { !it.isValid }.forEach { getInlayComponent(it)?.let { inlay -> removeInlay(inlay) } } inlayElements.removeIf { !it.isValid } while (node != null && node.textRange.startOffset < offset + length) { PsiTreeUtil.collectElements(node) { psi -> descriptor.isInlayElement(psi) }.forEach { psi -> inlayElements.add(psi) } node = node.nextSibling } } /** On editor resize all inlays got width of editor. */ private fun addResizeListener() { editor.component.addComponentListener(object : ComponentAdapter() { override fun componentResized(e: ComponentEvent) { updateInlayComponentsWidth() } }) } private fun addViewportListener() { editor.scrollPane.viewport.addChangeListener { viewportQueue.queue(object : Update(VIEWPORT_TASK_IDENTITY) { override fun run() { updateInlaysForViewport() } }) } } private fun restoreOutputs() { updateInlaysForViewport() } private fun restoreToolbars(): CancellablePromise<*> { val inlaysPsiElements = ArrayList<PsiElement>() return ReadAction.nonBlocking { PsiTreeUtil.processElements(descriptor.psiFile) { element -> if (descriptor.isInlayElement(element)) inlaysPsiElements.add(element) true } }.finishOnUiThread(ModalityState.NON_MODAL) { inlayElements.clear() inlayElements.addAll(inlaysPsiElements) }.inSmartMode(project).submit(NonUrgentExecutor.getInstance()) } private fun getInlayComponentByOffset(offset: Int): NotebookInlayComponentPsi? { return if (offset == editor.document.textLength) inlays.entries.firstOrNull { it.key.textRange.containsOffset(offset) }?.value else inlays.entries.firstOrNull { it.key.textRange.contains(offset) }?.value } /** Add caret listener for editor to draw highlighted background for psiCell under caret. */ private fun addCaretListener() { editor.caretModel.addCaretListener(object : CaretListener { override fun caretPositionChanged(e: CaretEvent) { if (editor.caretModel.primaryCaret != e.caret) return onCaretPositionChanged() } }, editor.disposable) } private fun onCaretPositionChanged() { if (editor.isDisposed) { return } val cellUnderCaret = getInlayComponentByOffset(editor.logicalPositionToOffset(editor.caretModel.logicalPosition)) if (cellUnderCaret == null) { inlays.values.forEach { it.selected = false } } else { if (!cellUnderCaret.selected) { inlays.values.forEach { it.selected = false } cellUnderCaret.selected = true } } } /** When we are adding or removing paragraphs, old cells can change their text ranges*/ private fun updateInlays() { inlays.values.forEach { updateInlayPosition(it) } } private fun setupInlayComponent(inlayComponent: NotebookInlayComponentPsi) { fun updateInlaysInEditor(editor: Editor) { val end = editor.xyToLogicalPosition(Point(0, Int.MAX_VALUE)) val offsetEnd = editor.logicalPositionToOffset(end) val inlays = editor.inlayModel.getBlockElementsInRange(0, offsetEnd) inlays.forEach { inlay -> if (inlay.renderer is InlayComponent) { (inlay.renderer as InlayComponent).updateComponentBounds(inlay) } } } inlayComponent.beforeHeightChanged = { scrollKeeper.savePosition() } inlayComponent.afterHeightChanged = { updateInlaysInEditor(editor) scrollKeeper.restorePosition(true) } } /** Aligns all editor inlays to fill full width of editor. */ private fun updateInlayComponentsWidth() { val inlayWidth = InlayDimensions.calculateInlayWidth(editor) if (inlayWidth > 0) { inlays.values.forEach { it.setSize(inlayWidth, it.height) it.inlay?.updateSize() } } } /** It could be that user started to type below inlay. In this case we will detect new position and perform inlay repositioning. */ private fun updateInlayPosition(inlayComponent: NotebookInlayComponentPsi) { // editedCell here contains old text. This event will be processed by PSI later. val offset = descriptor.getInlayOffset(inlayComponent.cell) if (inlayComponent.inlay!!.offset != offset) { inlayComponent.disposeInlay() val inlay = addBlockElement(offset, inlayComponent) inlayComponent.assignInlay(inlay) } inlayComponent.updateComponentBounds(inlayComponent.inlay!!) } private fun addBlockElement(offset: Int, inlayComponent: NotebookInlayComponentPsi): Inlay<NotebookInlayComponentPsi> { return editor.inlayModel.addBlockElement(offset, true, false, INLAY_PRIORITY, inlayComponent) } private fun addInlayComponent(cell: PsiElement): NotebookInlayComponentPsi { val existingInlay = inlays[cell] if (existingInlay != null) { throw Exception("Cell already added.") } InlayDimensions.init(editor) val offset = descriptor.getInlayOffset(cell) val inlayComponent = NotebookInlayComponentPsi(cell, editor) // On editor creation it has 0 width val gutterWidth = (editor.gutter as EditorGutterComponentEx).width var editorWideWidth = editor.component.width - inlayComponent.width - gutterWidth - InlayDimensions.rightBorder if (editorWideWidth <= 0) { editorWideWidth = InlayDimensions.width } inlayComponent.setBounds(0, editor.offsetToXY(offset).y + editor.lineHeight, editorWideWidth, InlayDimensions.smallHeight) editor.contentComponent.add(inlayComponent) val inlay = addBlockElement(offset, inlayComponent) inlayComponent.assignInlay(inlay) inlays[cell] = inlayComponent setupInlayComponent(inlayComponent) return inlayComponent } private fun getInlayComponent(cell: PsiElement): NotebookInlayComponentPsi? { return inlays[cell] } companion object { private const val VIEWPORT_TASK_NAME = "On viewport change" private const val VIEWPORT_TASK_IDENTITY = "On viewport change task" private const val VIEWPORT_TIME_SPAN = 50 const val INLAY_PRIORITY = 0 @TestOnly var isEnabledInTests: Boolean = false } } const val VIEWPORT_INLAY_RANGE = 20 fun calculateViewportRange(editor: EditorImpl): IntRange { val viewport = editor.scrollPane.viewport val yMin = viewport.viewPosition.y val yMax = yMin + viewport.height return yMin until yMax } fun calculateInlayExpansionRange(editor: EditorImpl, viewportRange: IntRange): IntRange { val startLine = editor.xyToLogicalPosition(Point(0, viewportRange.first)).line val endLine = editor.xyToLogicalPosition(Point(0, viewportRange.last + 1)).line val startOffset = editor.document.getLineStartOffset(max(startLine - VIEWPORT_INLAY_RANGE, 0)) val endOffset = editor.document.getLineStartOffset(max(min(endLine + VIEWPORT_INLAY_RANGE, editor.document.lineCount - 1), 0)) return startOffset..endOffset }
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/r/inlays/InlayEditorManager.kt
3990977448
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.toml import com.intellij.testFramework.fixtures.BasePlatformTestCase import org.intellij.lang.annotations.Language abstract class TomlTestBase : BasePlatformTestCase() { open val dataPath: String = "" override fun getTestDataPath(): String = getTomlTestsResourcesPath().resolve(dataPath).toString() @Suppress("TestFunctionName") protected fun InlineFile(@Language("TOML") text: String, name: String = "example.toml") { myFixture.configureByText(name, text.trimIndent()) } protected fun checkByText( @Language("TOML") before: String, @Language("TOML") after: String, action: () -> Unit ) { InlineFile(before) action() myFixture.checkResult(after) } protected val testName: String get() = getTestName(true) override fun getTestName(lowercaseFirstLetter: Boolean): String { val camelCase = super.getTestName(lowercaseFirstLetter) return TestCase.camelOrWordsToSnake(camelCase) } }
plugins/toml/core/src/test/kotlin/org/toml/TomlTestBase.kt
3048666595
// 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.core.util import com.intellij.ui.DocumentAdapter import javax.swing.event.DocumentEvent import javax.swing.text.JTextComponent fun JTextComponent.onTextChange(action: (DocumentEvent) -> Unit) { document.addDocumentListener( object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { action(e) } } ) }
plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/util/UiUtils.kt
34788879
/* * Copyright 2018 Benjamin Scherer * * 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.thatsnomoon.kda.extensions import com.thatsnomoon.kda.globalCoroutineContext import com.thatsnomoon.kda.toDuration import kotlinx.coroutines.experimental.Deferred import kotlinx.coroutines.experimental.async import kotlinx.coroutines.experimental.channels.ReceiveChannel import kotlinx.coroutines.experimental.channels.produce import kotlinx.coroutines.experimental.future.asDeferred import kotlinx.coroutines.experimental.future.await import kotlinx.coroutines.experimental.time.delay import net.dv8tion.jda.core.requests.RestAction import net.dv8tion.jda.core.requests.restaction.pagination.PaginationAction import java.time.Duration import java.util.concurrent.TimeUnit /** * Queues and converts this RestAction into a [Deferred]3 * * @return Deferred that resolves to the result of this action */ fun <T> RestAction<T>.asDeferred(): Deferred<T> = this.submit().asDeferred() /** * Suspends until this RestAction is complete3 * * @return The result of this action */ suspend fun <T> RestAction<T>.await(): T = this.submit().await() /** * Queues this RestAction after [delay] and converts it into a [Deferred]. * * @param delay [Duration] to wait before queueing this action * * @return Deferred that resolves to the result of this action */ infix fun <T> RestAction<T>.after(delay: Duration): Deferred<T> = async(globalCoroutineContext) { delay(delay) [email protected]() } /** * Queues this RestAction after [delay] in [TimeUnit] and converts it into a [Deferred]. * * @param delay Time to wait before queueing this action * @param unit Unit of [delay] * * @return Deferred that resolves to the result of this action */ fun <T> RestAction<T>.after(delay: Long, unit: TimeUnit): Deferred<T> = this after toDuration(delay, unit) /** * Maps the result of this [RestAction] to a new value by calling [success]. * * This is simply a convenience function over [Deferred.map], using [asDeferred]. * * @param success Function to map the resulting value of this RestAction * @return A Deferred that resolves to the return value of [success] */ inline infix fun <T, U> RestAction<T>.map(crossinline success: suspend (T) -> U): Deferred<U> = this.asDeferred() map success /** * Adds a suspending success callback to this RestAction. * * This is simply a convenience function over [Deferred.then], using [asDeferred]. * * @param success Callback to add to this RestAction */ inline infix fun <T> RestAction<T>.then(crossinline success: suspend (T) -> Unit) = this.asDeferred() then success /** * Maps the result of this RestAction to a new value, "flattening" a nested [Deferred], by calling [success]. * * This is simply a convenience function over [Deferred.flatMap], using [asDeferred]. * * @param success Function to map the resulting value of this RestAction * @return Deferred that resolves to the resolution value of the return value of [success] */ inline infix fun <T, U> RestAction<T>.flatMap(crossinline success: suspend (T) -> Deferred<U>): Deferred<U> = this.asDeferred() flatMap success /** * Adds a suspending failure callback to this RestAction. * * This is simply a convenience function over [Deferred.catch], using [asDeferred]. * * @param failure Failure callback to add to this RestAction */ inline infix fun <T> RestAction<T>.catch(crossinline failure: suspend (Throwable) -> Unit) = this.asDeferred() catch failure /** * Adds suspending success and failure callbacks to this RestAction. * * This is simply a convenience function over [Deferred.accept], using [asDeferred] * * @param success Success callback to add to this RestAction * @param failure Failure callback to add to this RestAction */ inline fun <T> RestAction<T>.accept(crossinline success: suspend (T) -> Unit, crossinline failure: suspend (Throwable) -> Unit) = this.asDeferred().accept(success, failure) /** * Maps a failed RestAction to a successfully completed [Deferred]. * * This is simply a convenience function over [Deferred.handle], using [asDeferred] * * @param failure Function to map the error of this RestAction to a successful value * @return A Deferred that resolves to the result of this action if successful, or the return value of [failure] otherwise */ inline infix fun <T> RestAction<T>.handle(crossinline failure: suspend (Throwable) -> T): Deferred<T> = this.asDeferred() handle failure /** * Maps a successful or failed RestAction to a successfully completed [Deferred]. * * This is simply a convenience function over [Deferred.apply], using [asDeferred] * * @param success Function to map the successful result of this RestAction * @param failure Function to map the error of this RestAction * @return A Deferred that resolves to the return value of [success] or [failure] */ inline fun <T, U> RestAction<T>.apply(crossinline success: suspend (T) -> U, crossinline failure: suspend (Throwable) -> U): Deferred<U> = this.asDeferred().apply(success, failure) /** * Converts this PaginationAction into a [ReceiveChannel] that produces its values. * * @return ReceiveChannel that produces the values of this PaginationAction */ fun <T, M: PaginationAction<T, M>> PaginationAction<T, M>.toChannel(): ReceiveChannel<T> = produce(globalCoroutineContext) { var items: List<T> = [email protected]() var cursor = 0 while (cursor < items.size) { send(items[cursor]) cursor += 1 if (cursor == items.size) { items = [email protected]() cursor = 0 } } }
src/main/kotlin/com/thatsnomoon/kda/extensions/RestActionExtensions.kt
3789420439
fun X.<caret>foo(s: String, k: Int): Boolean { return this.k + s.length - k - l > 0 } class X(val k: Int, val l: Int) fun test() { with(X(0, 1)) { foo("1", 2) } X(0, 1).foo("1", 2) }
plugins/kotlin/idea/tests/testData/refactoring/changeSignature/RemoveReceiverConflictBefore.kt
3081067321
// "Move to constructor" "true" actual class SimpleWConstructor(i: Int) { actual val <caret>b: String = "" }
plugins/kotlin/idea/tests/testData/multiModuleQuickFix/other/moveActualPropertyToExistentConstructor/jvm/jvm.kt
150422598
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.authentication.accounts import com.intellij.configurationStore.deserializeAndLoadState import com.intellij.configurationStore.serialize import com.intellij.openapi.util.JDOMUtil import com.intellij.testFramework.ApplicationRule import org.jetbrains.plugins.github.api.GithubServerPath import org.junit.Assert.assertEquals import org.junit.ClassRule import org.junit.Test class GHPersistentAccountsTest { companion object { @ClassRule @JvmField val appRule = ApplicationRule() } @Test fun `test serialize`() { val service = GHPersistentAccounts() val id1 = "231775c2-04c4-4819-b04a-d9d21a361b7f" val id2 = "cdd614b1-0511-4f82-b9e2-6625ff5aa059" val n1 = "test1" val n2 = "test2" service.accounts = setOf( GithubAccount(n1, GithubServerPath.DEFAULT_SERVER, id1), GithubAccount(n2, GithubServerPath(false, "ghe.labs.intellij.net", 80, "sfx"), id2) ) @Suppress("UsePropertyAccessSyntax") val state = service.getState() val element = serialize(state)!! val xml = JDOMUtil.write(element) assertEquals(""" <array> <account name="$n1" id="$id1"> <server host="github.com" /> </account> <account name="$n2" id="$id2"> <server useHttp="false" host="ghe.labs.intellij.net" port="80" suffix="sfx" /> </account> </array> """.trimIndent(), xml) } @Test fun `test deserialize`() { val service = GHPersistentAccounts() val id1 = "231775c2-04c4-4819-b04a-d9d21a361b7f" val id2 = "cdd614b1-0511-4f82-b9e2-6625ff5aa059" val n1 = "test1" val n2 = "test2" val element = JDOMUtil.load(""" <component name="GithubAccounts"> <account name="$n1" id="$id1"> <server host="github.com" /> </account> <account name="$n2" id="$id2"> <server useHttp="false" host="ghe.labs.intellij.net" port="80" suffix="sfx" /> </account> </component> """.trimIndent()) deserializeAndLoadState(service, element) assertEquals(setOf( GithubAccount("test1", GithubServerPath.DEFAULT_SERVER, id1), GithubAccount("test2", GithubServerPath(false, "ghe.labs.intellij.net", 80, "sfx"), id2) ), service.accounts) } }
plugins/github/test/org/jetbrains/plugins/github/authentication/accounts/GHPersistentAccountsTest.kt
3515724698
class Bar(val r: Runnable) : Runnable by r class Foo { val bar by lazy { "" } val baz: String by lazy { "" } }
plugins/kotlin/idea/tests/testData/formatter/By.kt
4099968569
internal open class Base internal interface I0 internal interface I1 internal interface I2 internal class A : Base(), I0, I1, I2
plugins/kotlin/j2k/new/tests/testData/newJ2k/class/extendsOneClassAndImplementsSeveralInterfaces.kt
2384232944
package com.kickstarter.ui.activities import android.app.Activity import android.content.Intent import android.os.Bundle import android.util.Pair import com.kickstarter.R import com.kickstarter.databinding.LoginLayoutBinding import com.kickstarter.libs.ActivityRequestCodes import com.kickstarter.libs.BaseActivity import com.kickstarter.libs.KSString import com.kickstarter.libs.qualifiers.RequiresActivityViewModel import com.kickstarter.libs.rx.transformers.Transformers.observeForUI import com.kickstarter.libs.utils.ObjectUtils import com.kickstarter.libs.utils.TransitionUtils.slideInFromLeft import com.kickstarter.libs.utils.ViewUtils import com.kickstarter.libs.utils.extensions.getResetPasswordIntent import com.kickstarter.ui.IntentKey import com.kickstarter.ui.extensions.hideKeyboard import com.kickstarter.ui.extensions.onChange import com.kickstarter.ui.extensions.showSnackbar import com.kickstarter.ui.extensions.text import com.kickstarter.ui.views.ConfirmDialog import com.kickstarter.viewmodels.LoginViewModel @RequiresActivityViewModel(LoginViewModel.ViewModel::class) class LoginActivity : BaseActivity<LoginViewModel.ViewModel>() { private var confirmResetPasswordSuccessDialog: ConfirmDialog? = null private lateinit var ksString: KSString private val forgotPasswordString = R.string.login_buttons_forgot_password_html private val forgotPasswordSentEmailString = R.string.forgot_password_we_sent_an_email_to_email_address_with_instructions_to_reset_your_password private val loginDoesNotMatchString = R.string.login_errors_does_not_match private val unableToLoginString = R.string.login_errors_unable_to_log_in private val loginString = R.string.login_buttons_log_in private val errorTitleString = R.string.login_errors_title private lateinit var binding: LoginLayoutBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = LoginLayoutBinding.inflate(layoutInflater) setContentView(binding.root) this.ksString = requireNotNull(environment().ksString()) binding.loginToolbar.loginToolbar.setTitle(getString(this.loginString)) binding.loginFormView.forgotYourPasswordTextView.text = ViewUtils.html(getString(this.forgotPasswordString)) binding.loginFormView.email.onChange { this.viewModel.inputs.email(it) } binding.loginFormView.password.onChange { this.viewModel.inputs.password(it) } errorMessages() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { e -> ViewUtils.showDialog(this, getString(this.errorTitleString), e) } this.viewModel.outputs.tfaChallenge() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { startTwoFactorActivity() } this.viewModel.outputs.loginSuccess() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { onSuccess() } this.viewModel.outputs.prefillEmail() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { binding.loginFormView.email.setText(it) binding.loginFormView.email.setSelection(it.length) } this.viewModel.outputs.showChangedPasswordSnackbar() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { showSnackbar(binding.loginToolbar.loginToolbar, R.string.Got_it_your_changes_have_been_saved) } this.viewModel.outputs.showCreatedPasswordSnackbar() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { showSnackbar(binding.loginToolbar.loginToolbar, R.string.Got_it_your_changes_have_been_saved) } this.viewModel.outputs.showResetPasswordSuccessDialog() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe { showAndEmail -> val show = showAndEmail.first val email = showAndEmail.second if (show) { resetPasswordSuccessDialog(email).show() } else { resetPasswordSuccessDialog(email).dismiss() } } this.viewModel.outputs.loginButtonIsEnabled() .compose(bindToLifecycle()) .compose(observeForUI()) .subscribe({ this.setLoginButtonEnabled(it) }) binding.loginFormView.forgotYourPasswordTextView.setOnClickListener { startResetPasswordActivity() } binding.loginFormView.loginButton.setOnClickListener { this.viewModel.inputs.loginClick() [email protected]() } } /** * Lazily creates a reset password success confirmation dialog and stores it in an instance variable. */ private fun resetPasswordSuccessDialog(email: String): ConfirmDialog { if (this.confirmResetPasswordSuccessDialog == null) { val message = this.ksString.format(getString(this.forgotPasswordSentEmailString), "email", email) this.confirmResetPasswordSuccessDialog = ConfirmDialog(this, null, message) this.confirmResetPasswordSuccessDialog!! .setOnDismissListener { this.viewModel.inputs.resetPasswordConfirmationDialogDismissed() } this.confirmResetPasswordSuccessDialog!! .setOnCancelListener { this.viewModel.inputs.resetPasswordConfirmationDialogDismissed() } } return this.confirmResetPasswordSuccessDialog!! } private fun errorMessages() = this.viewModel.outputs.invalidLoginError() .map(ObjectUtils.coalesceWith(getString(this.loginDoesNotMatchString))) .mergeWith( this.viewModel.outputs.genericLoginError() .map(ObjectUtils.coalesceWith(getString(this.unableToLoginString))) ) override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) { super.onActivityResult(requestCode, resultCode, intent) if (requestCode != ActivityRequestCodes.LOGIN_FLOW && requestCode != ActivityRequestCodes.RESET_FLOW) { return } if (requestCode != ActivityRequestCodes.RESET_FLOW) { setResult(resultCode, intent) finish() } } private fun onSuccess() { setResult(Activity.RESULT_OK) finish() } private fun setLoginButtonEnabled(enabled: Boolean) { binding.loginFormView.loginButton.isEnabled = enabled } private fun startTwoFactorActivity() { val intent = Intent(this, TwoFactorActivity::class.java) .putExtra(IntentKey.EMAIL, binding.loginFormView.email.text()) .putExtra(IntentKey.PASSWORD, binding.loginFormView.password.text()) startActivityForResult(intent, ActivityRequestCodes.LOGIN_FLOW) overridePendingTransition(R.anim.slide_in_right, R.anim.fade_out_slide_out_left) } private fun startResetPasswordActivity() { val intent = Intent().getResetPasswordIntent(this, email = binding.loginFormView.email.text.toString()) startActivityForResult(intent, ActivityRequestCodes.RESET_FLOW) overridePendingTransition(R.anim.slide_in_right, R.anim.fade_out_slide_out_left) } override fun exitTransition(): Pair<Int, Int>? { return slideInFromLeft() } override fun back() { if (this.supportFragmentManager.backStackEntryCount == 0) { super.back() } } }
app/src/main/java/com/kickstarter/ui/activities/LoginActivity.kt
3516830865
/* * Copyright 1999-2017 Alibaba Group. * * 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.alibaba.p3c.idea.config import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.util.xmlb.XmlSerializerUtil /** * * * @author caikang * @date 2017/03/01 */ @State(name = "SmartFoxProjectConfig", storages = [com.intellij.openapi.components.Storage(file = "smartfox_info.xml")]) class SmartFoxProjectConfig : PersistentStateComponent<SmartFoxProjectConfig> { var projectInspectionClosed = false override fun getState(): SmartFoxProjectConfig? { return this } override fun loadState(state: SmartFoxProjectConfig) { XmlSerializerUtil.copyBean(state, this) } }
idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/config/SmartFoxProjectConfig.kt
3171632303
/* * Copyright 2016 Fabio Collini. * * 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 it.cosenonjaviste.daggermock.realworldappkotlin import com.nhaarman.mockitokotlin2.mock import it.cosenonjaviste.daggermock.DaggerMock import it.cosenonjaviste.daggermock.realworldappkotlin.main.MainView fun jUnitDaggerMockRule() = DaggerMock.rule<AppComponent>(AppModule(mock())) { providesMock<MainView>() }
RealWorldAppKotlin/src/test/java/it/cosenonjaviste/daggermock/realworldappkotlin/JUnitDaggerMockRule.kt
1715752787
@file:Suppress("UnstableApiUsage") // We know that Lint APIs aren't final. package com.vanniktech.lintrules.android import com.android.tools.lint.detector.api.XmlContext import java.util.Locale class MatchingIdFixer(context: XmlContext, private val id: String) { private val layoutName = context.file.name.replace(".xml", "") val expectedPrefix = layoutName.toLowerCamelCase() fun needsFix() = !id.startsWith(expectedPrefix) fun fixedId(): String { return if (id.startsWith(expectedPrefix, ignoreCase = true)) { expectedPrefix + id.substring(expectedPrefix.length) } else { expectedPrefix + id.capitalize(Locale.ROOT) } } }
lint-rules-android-lint/src/main/java/com/vanniktech/lintrules/android/MatchingIdFixer.kt
2831157404
// 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.util.io import com.intellij.util.containers.nullize import java.nio.charset.MalformedInputException import java.nio.file.Path @JvmOverloads fun Path.getDirectoryTree(excluded: Set<String> = emptySet(), printContent: Boolean = true): String { val sb = StringBuilder() getDirectoryTree(this, 0, sb, excluded, printContent = printContent) return sb.toString() } private fun getDirectoryTree(dir: Path, indent: Int, sb: StringBuilder, excluded: Set<String>, printContent: Boolean) { val fileList = sortedFileList(dir, excluded).nullize() ?: return getIndentString(indent, sb) if (printContent) { sb.append("\u251c\u2500\u2500") } sb.append(dir.fileName.toString()) sb.append("/") sb.append("\n") for (file in fileList) { if (file.isDirectory()) { getDirectoryTree(file, indent + 1, sb, excluded, printContent) } else { printFile(file, indent + 1, sb, printContent) } } } private fun sortedFileList(dir: Path, excluded: Set<String>): List<Path>? { return dir.directoryStreamIfExists { stream -> var sequence = stream.asSequence() if (excluded.isNotEmpty()) { sequence = sequence.filter { !excluded.contains(it.fileName.toString()) } } val list = sequence.toMutableList() list.sort() list } } private fun printFile(file: Path, indent: Int, sb: StringBuilder, printContent: Boolean) { getIndentString(indent, sb) if (printContent) { sb.append("\u251c\u2500\u2500") } val fileName = file.fileName.toString() sb.append(fileName) sb.append("\n") if (printContent && !(fileName.endsWith(".zip") || fileName.endsWith(".jar") || fileName.endsWith(".class"))) { try { sb.append(file.readChars()).append("\n\n") } catch (ignore: MalformedInputException) { } } } private fun getIndentString(indent: Int, sb: StringBuilder) { for (i in 0 until indent) { sb.append(" ") } }
platform/testFramework/src/com/intellij/util/io/FileTreePrinter.kt
332463006
// 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.tools.projectWizard.plugins.templates import org.jetbrains.kotlin.tools.projectWizard.core.Context import org.jetbrains.kotlin.tools.projectWizard.core.PluginSettingsOwner import org.jetbrains.kotlin.tools.projectWizard.core.entity.PipelineTask import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase import org.jetbrains.kotlin.tools.projectWizard.templates.ConsoleJvmApplicationTemplate class ConsoleJvmApplicationTemplatePlugin(context: Context) : TemplatePlugin(context) { override val path = pluginPath override val pipelineTasks: List<PipelineTask> = super.pipelineTasks + listOf(addTemplate) companion object : PluginSettingsOwner() { override val pluginPath = "template.consoleJvmApplicationTemplate" val addTemplate by pipelineTask(GenerationPhase.PREPARE) { withAction { TemplatesPlugin.addTemplate.execute(ConsoleJvmApplicationTemplate()) } } } }
plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/plugins/templates/ConsoleJvmApplicationTemplatePlugin.kt
2109660887
// WITH_RUNTIME fun foo() { for (i in 9<caret>..0) {} }
plugins/kotlin/idea/tests/testData/inspectionsLocal/emptyRange/simple.kt
3134607043
// WITH_RUNTIME package org.apache.commons.logging class Foo { private val logger = LogFactory.getLog(<caret>Bar::class.java.getCanonicalName()) } class Bar object LogFactory { fun getLog(clazz: Class<*>) {} fun getLog(name: String?) {} }
plugins/kotlin/idea/tests/testData/inspectionsLocal/logging/loggerInitializedWithForeignClass/commons/getCanonicalName.kt
3468048494
package io.github.feelfreelinux.wykopmobilny.glide import android.content.Context import com.bumptech.glide.Glide import com.bumptech.glide.Registry import com.bumptech.glide.annotation.GlideModule import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader import com.bumptech.glide.load.model.GlideUrl import com.bumptech.glide.module.AppGlideModule import io.github.feelfreelinux.wykopmobilny.api.ApiSignInterceptor import io.github.feelfreelinux.wykopmobilny.api.RetryInterceptor import okhttp3.OkHttpClient import java.io.InputStream import java.util.concurrent.TimeUnit @GlideModule class GlideModule : AppGlideModule() { override fun registerComponents(context: Context, glide: Glide, registry: Registry) { super.registerComponents(context, glide, registry) val builder = OkHttpClient.Builder() builder.readTimeout(30, TimeUnit.SECONDS) builder.writeTimeout(30, TimeUnit.SECONDS) builder.connectTimeout(30, TimeUnit.SECONDS) builder.addInterceptor(RetryInterceptor()) registry?.append(GlideUrl::class.java, InputStream::class.java, OkHttpUrlLoader.Factory(builder.build())) } }
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/glide/GlideModule.kt
3586160815
// WITH_RUNTIME fun foo() { // check that original formatting of "x+1" and "1 .. 4" is preserved <caret>for (x in 1 .. 4) { x x+1 } }
plugins/kotlin/idea/tests/testData/intentions/convertToForEachFunctionCall/blockBodyExpression.kt
4036760038
// 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.model.psi.impl import com.intellij.codeInsight.TargetElementUtil import com.intellij.diagnostic.PluginException import com.intellij.model.Symbol import com.intellij.model.psi.PsiSymbolDeclaration import com.intellij.model.psi.PsiSymbolReference import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.util.leavesAroundOffset import com.intellij.util.SmartList import org.jetbrains.annotations.ApiStatus.Experimental /** * Entry point for obtaining target symbols by [offset] in a [file]. * * @return collection of referenced or declared symbols */ @Experimental fun targetSymbols(file: PsiFile, offset: Int): Collection<Symbol> { val (declaredData, referencedData) = declaredReferencedData(file, offset) ?: return emptyList() val data = referencedData ?: declaredData ?: return emptyList() return data.targets.map { it.symbol } } /** * @return two collections: of declared and of referenced symbols */ @Experimental fun targetDeclarationAndReferenceSymbols(file: PsiFile, offset: Int): Pair<Collection<Symbol>, Collection<Symbol>> { val (declaredData, referencedData) = declaredReferencedData(file, offset) ?: return Pair(emptyList(), emptyList()) return (declaredData?.targets?.map { it.symbol } ?: emptyList()) to (referencedData?.targets?.map { it.symbol } ?: emptyList()) } internal fun declaredReferencedData(file: PsiFile, offset: Int): DeclaredReferencedData? { val allDeclarationsOrReferences: List<DeclarationOrReference> = declarationsOrReferences(file, offset) if (allDeclarationsOrReferences.isEmpty()) { return null } val withMinimalRanges: Collection<DeclarationOrReference> = try { chooseByRange(allDeclarationsOrReferences, offset, DeclarationOrReference::rangeWithOffset) } catch (e: RangeOverlapException) { val details = allDeclarationsOrReferences.joinToString(separator = "") { item -> "\n${item.rangeWithOffset} : $item" } LOG.error("Range overlap", PluginException.createByClass(e, file.javaClass), details) return null } var declaration: PsiSymbolDeclaration? = null val references: MutableList<PsiSymbolReference> = ArrayList() for (dr in withMinimalRanges) { when (dr) { is DeclarationOrReference.Declaration -> { if (declaration != null) { LOG.error( """ Multiple declarations with the same range are not supported. Declaration: $declaration; class: ${declaration.javaClass.name}. Another declaration: ${dr.declaration}; class: ${dr.declaration.javaClass.name}. """.trimIndent() ) } else { declaration = dr.declaration } } is DeclarationOrReference.Reference -> { references.add(dr.reference) } } } return DeclaredReferencedData( declaredData = declaration?.let(TargetData::Declared), referencedData = references.takeUnless { it.isEmpty() }?.let(TargetData::Referenced) ) } private sealed class DeclarationOrReference { abstract val rangeWithOffset: TextRange class Declaration(val declaration: PsiSymbolDeclaration) : DeclarationOrReference() { override val rangeWithOffset: TextRange get() = declaration.absoluteRange override fun toString(): String = declaration.toString() } class Reference(val reference: PsiSymbolReference, private val offset: Int) : DeclarationOrReference() { override val rangeWithOffset: TextRange by lazy(LazyThreadSafetyMode.NONE) { referenceRanges(reference).find { it.containsOffset(offset) } ?: error("One of the ranges must contain offset at this point") } override fun toString(): String = reference.toString() } } internal fun referenceRanges(it: PsiSymbolReference): List<TextRange> { return if (it is EvaluatorReference) { it.origin.absoluteRanges } else { // Symbol references don't support multi-ranges yet. listOf(it.absoluteRange) } } /** * @return declarations/references which contain the given [offset] in the [file] */ private fun declarationsOrReferences(file: PsiFile, offset: Int): List<DeclarationOrReference> { val result = SmartList<DeclarationOrReference>() var foundNamedElement: PsiElement? = null val allDeclarations = file.allDeclarationsAround(offset) if (allDeclarations.isEmpty()) { namedElement(file, offset)?.let { (namedElement, leaf) -> foundNamedElement = namedElement val declaration: PsiSymbolDeclaration = PsiElement2Declaration.createFromDeclaredPsiElement(namedElement, leaf) result += DeclarationOrReference.Declaration(declaration) } } else { allDeclarations.mapTo(result, DeclarationOrReference::Declaration) } val allReferences = file.allReferencesAround(offset) if (allReferences.isEmpty()) { fromTargetEvaluator(file, offset)?.let { evaluatorReference -> if (foundNamedElement != null && evaluatorReference.targetElements.singleOrNull() === foundNamedElement) { return@let // treat self-reference as a declaration } result += DeclarationOrReference.Reference(evaluatorReference, offset) } } else { allReferences.mapTo(result) { DeclarationOrReference.Reference(it, offset) } } return result } private data class NamedElementAndLeaf(val namedElement: PsiElement, val leaf: PsiElement) private fun namedElement(file: PsiFile, offset: Int): NamedElementAndLeaf? { for ((leaf, _) in file.leavesAroundOffset(offset)) { val namedElement: PsiElement? = TargetElementUtil.getNamedElement(leaf) if (namedElement != null) { return NamedElementAndLeaf(namedElement, leaf) } } return null } private fun fromTargetEvaluator(file: PsiFile, offset: Int): EvaluatorReference? { val editor = mockEditor(file) ?: return null val flags = TargetElementUtil.getInstance().allAccepted and TargetElementUtil.ELEMENT_NAME_ACCEPTED.inv() and TargetElementUtil.LOOKUP_ITEM_ACCEPTED.inv() val reference = TargetElementUtil.findReference(editor, offset) val origin: PsiOrigin = if (reference != null) { PsiOrigin.Reference(reference) } else { val leaf = file.findElementAt(TargetElementUtil.adjustOffset(file, editor.document, offset)) ?: return null PsiOrigin.Leaf(leaf) } val targetElement = TargetElementUtil.getInstance().findTargetElement(editor, flags, offset) val targetElements: List<PsiElement> = when { targetElement != null -> listOf(targetElement) reference != null -> TargetElementUtil.getInstance().getTargetCandidates(reference).toList() else -> emptyList() } if (targetElements.isEmpty()) { return null } return EvaluatorReference(origin, targetElements) }
platform/lang-impl/src/com/intellij/model/psi/impl/targets.kt
879356413
fun <T> Array<T>.filter(predicate : (T) -> Boolean) : java.util.List<T> = throw UnsupportedOperationException() fun main(args: Array<String>) { args.fil<caret> } // ELEMENT: *
plugins/kotlin/completion/tests/testData/handlers/basic/highOrderFunctions/HigherOrderFunction.kt
1022027292
fun test() { val (a, b) <caret> } // SET_FALSE: CONTINUATION_INDENT_FOR_EXPRESSION_BODIES
plugins/kotlin/idea/tests/testData/indentationOnNewline/expressionBody/AfterMultideclaration.kt
2548150657
// 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. @file: JvmName("SuggestUsingRunDashBoardUtil") package com.intellij.execution import com.intellij.CommonBundle import com.intellij.execution.configurations.ConfigurationType import com.intellij.execution.dashboard.RunDashboardManager import com.intellij.icons.AllIcons import com.intellij.lang.LangBundle import com.intellij.notification.* import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.project.Project /** * If Run Dashboard is not configured for [configurationTypes], show [Notification] allowing to enable dashboard for those configurations. **/ fun promptUserToUseRunDashboard(project: Project, configurationTypes: Collection<ConfigurationType>) { ApplicationManager.getApplication().invokeLater { val currentTypes = RunDashboardManager.getInstance(project).types val typesToAdd = configurationTypes.filter { it.id !in currentTypes } if (typesToAdd.isNotEmpty()) { Notifications.Bus.notify( SuggestDashboardNotification(project, typesToAdd.toSet(), RunDashboardManager.getInstance(project).toolWindowId), project) } } } private const val suggestRunDashboardId = "Suggest Run Dashboard" private class SuggestDashboardNotification( private val project: Project, types: Set<ConfigurationType>, toolWindowId: String ) : Notification( suggestRunDashboardId, LangBundle.message("notification.title.use.toolwindow", toolWindowId), LangBundle.message("notification.suggest.dashboard", toolWindowId, toolWindowId, types.joinToString(prefix = "<b>", postfix = "</b>", separator = "<br>") { it.configurationTypeDescription }), NotificationType.INFORMATION ) { init { icon = AllIcons.RunConfigurations.TestState.Run addAction(NotificationAction.create(CommonBundle.message("button.without.mnemonic.yes")) { _ -> ApplicationManager.getApplication().invokeLater { runWriteAction { val runDashboardManager = RunDashboardManager.getInstance(project) runDashboardManager.types = runDashboardManager.types + types.map { it.id } } } expire() }) addAction(NotificationAction.create(LangBundle.message("button.not.this.time.text")) { _ -> expire() }) addAction(NotificationAction.create(LangBundle.message("button.do.not.ask.again.text")) { _ -> NotificationsConfiguration.getNotificationsConfiguration().changeSettings( suggestRunDashboardId, NotificationDisplayType.NONE, true, false ) expire() }) } }
platform/lang-api/src/com/intellij/execution/suggestUsingDashboard.kt
1883771687
// 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.highlighter import com.intellij.codeInsight.daemon.LineMarkerInfo import com.intellij.codeInsight.daemon.LineMarkerProvider import com.intellij.icons.AllIcons import com.intellij.openapi.editor.markup.GutterIconRenderer import com.intellij.openapi.progress.ProgressManager import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.highlighter.markers.LineMarkerInfos import org.jetbrains.kotlin.idea.inspections.RecursivePropertyAccessorInspection import org.jetbrains.kotlin.idea.util.getReceiverTargetDescriptor import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.lexer.KtToken import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.parents import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.inline.InlineUtil import org.jetbrains.kotlin.resolve.scopes.receivers.Receiver import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue import org.jetbrains.kotlin.types.expressions.OperatorConventions import org.jetbrains.kotlin.util.OperatorNameConventions class KotlinRecursiveCallLineMarkerProvider : LineMarkerProvider { override fun getLineMarkerInfo(element: PsiElement) = null override fun collectSlowLineMarkers(elements: MutableList<out PsiElement>, result: LineMarkerInfos) { val markedLineNumbers = HashSet<Int>() for (element in elements) { ProgressManager.checkCanceled() if (element is KtElement) { val lineNumber = element.getLineNumber() if (lineNumber !in markedLineNumbers && isRecursiveCall(element)) { markedLineNumbers.add(lineNumber) result.add(RecursiveMethodCallMarkerInfo(getElementForLineMark(element))) } } } } private fun getEnclosingFunction(element: KtElement, stopOnNonInlinedLambdas: Boolean): KtNamedFunction? { for (parent in element.parents) { when (parent) { is KtFunctionLiteral -> if (stopOnNonInlinedLambdas && !InlineUtil.isInlinedArgument( parent, parent.analyze(), false ) ) return null is KtNamedFunction -> { when (parent.parent) { is KtBlockExpression, is KtClassBody, is KtFile, is KtScript -> return parent else -> if (stopOnNonInlinedLambdas && !InlineUtil.isInlinedArgument(parent, parent.analyze(), false)) return null } } is KtClassOrObject -> return null } } return null } private fun isRecursiveCall(element: KtElement): Boolean { if (RecursivePropertyAccessorInspection.isRecursivePropertyAccess(element)) return true if (RecursivePropertyAccessorInspection.isRecursiveSyntheticPropertyAccess(element)) return true // Fast check for names without resolve val resolveName = getCallNameFromPsi(element) ?: return false val enclosingFunction = getEnclosingFunction(element, false) ?: return false val enclosingFunctionName = enclosingFunction.name if (enclosingFunctionName != OperatorNameConventions.INVOKE.asString() && enclosingFunctionName != resolveName.asString() ) return false // Check that there were no not-inlined lambdas on the way to enclosing function if (enclosingFunction != getEnclosingFunction(element, true)) return false val bindingContext = element.safeAnalyzeNonSourceRootCode() val enclosingFunctionDescriptor = bindingContext[BindingContext.FUNCTION, enclosingFunction] ?: return false val call = bindingContext[BindingContext.CALL, element] ?: return false val resolvedCall = bindingContext[BindingContext.RESOLVED_CALL, call] ?: return false if (resolvedCall.candidateDescriptor.original != enclosingFunctionDescriptor) return false fun isDifferentReceiver(receiver: Receiver?): Boolean { if (receiver !is ReceiverValue) return false val receiverOwner = receiver.getReceiverTargetDescriptor(bindingContext) ?: return true return when (receiverOwner) { is SimpleFunctionDescriptor -> receiverOwner != enclosingFunctionDescriptor is ClassDescriptor -> receiverOwner != enclosingFunctionDescriptor.containingDeclaration else -> return true } } if (isDifferentReceiver(resolvedCall.dispatchReceiver)) return false return true } private class RecursiveMethodCallMarkerInfo(callElement: PsiElement) : LineMarkerInfo<PsiElement>( callElement, callElement.textRange, AllIcons.Gutter.RecursiveMethod, { KotlinBundle.message("highlighter.tool.tip.text.recursive.call") }, null, GutterIconRenderer.Alignment.RIGHT, { KotlinBundle.message("highlighter.tool.tip.text.recursive.call") } ) { override fun createGutterRenderer(): GutterIconRenderer { return object : LineMarkerInfo.LineMarkerGutterIconRenderer<PsiElement>(this) { override fun getClickAction() = null // to place breakpoint on mouse click } } } } internal fun getElementForLineMark(callElement: PsiElement): PsiElement = when (callElement) { is KtSimpleNameExpression -> callElement.getReferencedNameElement() else -> // a fallback, //but who knows what to reference in KtArrayAccessExpression ? generateSequence(callElement) { it.firstChild }.last() } private fun PsiElement.getLineNumber(): Int { return PsiDocumentManager.getInstance(project).getDocument(containingFile)!!.getLineNumber(textOffset) } private fun getCallNameFromPsi(element: KtElement): Name? { when (element) { is KtSimpleNameExpression -> when (val elementParent = element.getParent()) { is KtCallExpression -> return Name.identifier(element.getText()) is KtOperationExpression -> { val operationReference = elementParent.operationReference if (element == operationReference) { val node = operationReference.getReferencedNameElementType() return if (node is KtToken) { val conventionName = if (elementParent is KtPrefixExpression) OperatorConventions.getNameForOperationSymbol(node, true, false) else OperatorConventions.getNameForOperationSymbol(node) conventionName ?: Name.identifier(element.getText()) } else { Name.identifier(element.getText()) } } } } is KtArrayAccessExpression -> return OperatorNameConventions.GET is KtThisExpression -> if (element.getParent() is KtCallExpression) return OperatorNameConventions.INVOKE } return null }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/highlighter/KotlinRecursiveCallLineMarkerProvider.kt
620966043
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.completion.lookups internal abstract class KotlinCallableLookupObject : KotlinLookupObject { abstract val renderedDeclaration: String abstract val options: CallableInsertionOptions }
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/completion/lookups/KotlinCallableLookupObject.kt
1545012897
package com.github.kerubistan.kerub.utils.junix.smartmontools import com.github.kerubistan.kerub.model.SoftwarePackage import com.github.kerubistan.kerub.model.Version import com.github.kerubistan.kerub.sshtestutils.mockCommandExecution import com.github.kerubistan.kerub.sshtestutils.mockProcess import com.github.kerubistan.kerub.testHostCapabilities import com.nhaarman.mockito_kotlin.eq import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.times import com.nhaarman.mockito_kotlin.verify import io.github.kerubistan.kroki.io.resourceToString import org.apache.sshd.client.session.ClientSession import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue class SmartCtlTest { val session = mock<ClientSession>() @Test fun available() { assertFalse("smartmontools usually not part of the default isntall, so no info - no smartmontools") { SmartCtl.available(null) } assertFalse("smartmontools usually not part of the default isntall, so no info - no smartmontools") { SmartCtl.available(testHostCapabilities.copy(installedSoftware = listOf())) } assertTrue("smartmontools installed") { SmartCtl.available( testHostCapabilities.copy( installedSoftware = listOf( SoftwarePackage("smartmontools", version = Version.fromVersionString("0.6.2")) ))) } } @Test fun infoWithSsd() { session.mockCommandExecution( "smartctl -i .*".toRegex(), resourceToString("com/github/kerubistan/kerub/utils/junix/smartmontools/smartctl-info-ssd.txt")) val storageDevice = SmartCtl.info(session, "/dev/sda") assertEquals("14320DF8BD3F", storageDevice.serialNumber) assertEquals(256060514304, storageDevice.userCapacity.toLong()) assertNull(storageDevice.rotationRate) } @Test fun infoWithHddSata() { session.mockCommandExecution( "smartctl -i .*".toRegex(), resourceToString("com/github/kerubistan/kerub/utils/junix/smartmontools/smartctl-info-hdd-sata.txt")) val storageDevice = SmartCtl.info(session, "/dev/sda") assertEquals("WD-WXN1E9485PZA", storageDevice.serialNumber) assertEquals(1000204886016, storageDevice.userCapacity.toLong()) assertEquals(5400, storageDevice.rotationRate) } @Test fun infoWithQemuSata() { session.mockCommandExecution( "smartctl -i .*".toRegex(), resourceToString("com/github/kerubistan/kerub/utils/junix/smartmontools/smartctl-info-qemu-sata.txt")) val storageDevice = SmartCtl.info(session, "/dev/sda") assertEquals("QM00005", storageDevice.serialNumber) assertEquals(8589934592, storageDevice.userCapacity.toLong()) assertNull(storageDevice.rotationRate) } @Test fun healthCheck() { session.mockCommandExecution( "smartctl -H .*".toRegex(), resourceToString("com/github/kerubistan/kerub/utils/junix/smartmontools/smartctl-healthcheck-ssd.txt")) assertTrue(SmartCtl.healthCheck(session, "/dev/sda")) } @Test fun healthCheckHdd() { session.mockCommandExecution( "smartctl -H .*".toRegex(), resourceToString("com/github/kerubistan/kerub/utils/junix/smartmontools/smartctl-healthcheck-hdd.txt")) assertTrue(SmartCtl.healthCheck(session, "/dev/sda")) } @Test fun healthCheckQemu() { session.mockCommandExecution( "smartctl -H .*".toRegex(), resourceToString("com/github/kerubistan/kerub/utils/junix/smartmontools/smartctl-healthcheck-qemu.txt")) assertTrue(SmartCtl.healthCheck(session, "/dev/sda")) } @Test fun monitor() { session.mockProcess( ".*smartctl.*".toRegex(), """smartctl 6.6 2016-05-31 r4324 [x86_64-linux-4.15.0-42-generic] (local build) Copyright (C) 2002-16, Bruce Allen, Christian Franke, www.smartmontools.org === START OF READ SMART DATA SECTION === SMART overall-health self-assessment test result: PASSED ---end--- smartctl 6.6 2016-05-31 r4324 [x86_64-linux-4.15.0-42-generic] (local build) Copyright (C) 2002-16, Bruce Allen, Christian Franke, www.smartmontools.org === START OF READ SMART DATA SECTION === SMART overall-health self-assessment test result: PASSED ---end--- smartctl 6.6 2016-05-31 r4324 [x86_64-linux-4.15.0-42-generic] (local build) Copyright (C) 2002-16, Bruce Allen, Christian Franke, www.smartmontools.org === START OF READ SMART DATA SECTION === SMART overall-health self-assessment test result: PASSED ---end--- """) val update = mock<(Boolean) -> Unit>() SmartCtl.monitor(session, "/dev/sda", interval = 1, update = update) verify(update, times(3)).invoke(eq(true)) } }
src/test/kotlin/com/github/kerubistan/kerub/utils/junix/smartmontools/SmartCtlTest.kt
1907706080
package com.intellij.cce.interpreter import com.intellij.cce.core.Lookup import com.intellij.cce.core.Session import com.intellij.cce.core.TokenProperties interface CompletionInvoker { fun moveCaret(offset: Int) fun callCompletion(expectedText: String, prefix: String?): Lookup fun finishCompletion(expectedText: String, prefix: String): Boolean fun printText(text: String) fun deleteRange(begin: Int, end: Int) fun openFile(file: String): String fun closeFile(file: String) fun isOpen(file: String): Boolean fun save() fun getText(): String fun emulateUserSession(expectedText: String, nodeProperties: TokenProperties, offset: Int): Session fun emulateCodeGolfSession(expectedLine: String, offset: Int, nodeProperties: TokenProperties): Session }
plugins/evaluation-plugin/core/src/com/intellij/cce/interpreter/CompletionInvoker.kt
2154447516
// FILE: lib/JavaFields.java package lib; public class JavaFields { private static String s = "s"; static int i = 1; private static double d = 2.0; private static boolean b = true; String is = "is"; private int ii = 2; private double id = 3.0; private boolean ib = false; public JavaFields() {} } // FILE: test.kt package foo import lib.JavaFields fun main() { val f = JavaFields() //Breakpoint! val a = 0 } fun <T> block(block: () -> T): T { return block() } // EXPRESSION: block { JavaFields.s = "ss" } // RESULT: VOID_VALUE // EXPRESSION: block { JavaFields.s } // RESULT: "ss": Ljava/lang/String; // EXPRESSION: block { JavaFields.i = 2 } // RESULT: VOID_VALUE // EXPRESSION: block { JavaFields.i } // RESULT: 2: I // EXPRESSION: block { JavaFields.d = -4.0 } // RESULT: VOID_VALUE // EXPRESSION: block { JavaFields.d } // RESULT: -4.0: D // EXPRESSION: block { JavaFields.b = false } // RESULT: VOID_VALUE // EXPRESSION: block { JavaFields.b } // RESULT: 0: Z // EXPRESSION: block { f.`is` = "isis" } // RESULT: VOID_VALUE // EXPRESSION: block { f.`is` } // RESULT: "isis": Ljava/lang/String; // EXPRESSION: block { f.ii = 4 } // RESULT: VOID_VALUE // EXPRESSION: block { f.ii } // RESULT: 4: I // EXPRESSION: block { f.id = 6.0 } // RESULT: VOID_VALUE // EXPRESSION: block { f.id } // RESULT: 6.0: D // EXPRESSION: block { f.ib = true } // RESULT: VOID_VALUE // EXPRESSION: block { f.ib } // RESULT: 1: Z
plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/compilingEvaluator/inaccessibleMembers/javaFields.kt
469390648
// 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.structuralsearch import com.intellij.lang.Language import com.intellij.openapi.fileTypes.LanguageFileType import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiErrorElement import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.util.elementType import com.intellij.structuralsearch.* import com.intellij.structuralsearch.impl.matcher.CompiledPattern import com.intellij.structuralsearch.impl.matcher.GlobalMatchingVisitor import com.intellij.structuralsearch.impl.matcher.PatternTreeContext import com.intellij.structuralsearch.impl.matcher.compiler.GlobalCompilingVisitor import com.intellij.structuralsearch.impl.matcher.predicates.MatchPredicate import com.intellij.structuralsearch.impl.matcher.predicates.NotPredicate import com.intellij.structuralsearch.plugin.replace.ReplaceOptions import com.intellij.structuralsearch.plugin.ui.Configuration import com.intellij.structuralsearch.plugin.ui.UIUtil import com.intellij.util.SmartList import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.liveTemplates.KotlinTemplateContextType import org.jetbrains.kotlin.idea.structuralsearch.filters.* import org.jetbrains.kotlin.idea.structuralsearch.predicates.KotlinAlsoMatchCompanionObjectPredicate import org.jetbrains.kotlin.idea.structuralsearch.predicates.KotlinAlsoMatchValVarPredicate import org.jetbrains.kotlin.idea.structuralsearch.predicates.KotlinExprTypePredicate import org.jetbrains.kotlin.idea.structuralsearch.predicates.KotlinMatchCallSemantics import org.jetbrains.kotlin.idea.structuralsearch.visitor.KotlinCompilingVisitor import org.jetbrains.kotlin.idea.structuralsearch.visitor.KotlinMatchingVisitor import org.jetbrains.kotlin.idea.structuralsearch.visitor.KotlinRecursiveElementWalkingVisitor import org.jetbrains.kotlin.kdoc.psi.impl.KDocTag import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* class KotlinStructuralSearchProfile : StructuralSearchProfile() { override fun isMatchNode(element: PsiElement?): Boolean = element !is PsiWhiteSpace override fun createMatchingVisitor(globalVisitor: GlobalMatchingVisitor): KotlinMatchingVisitor = KotlinMatchingVisitor(globalVisitor) override fun createCompiledPattern(): CompiledPattern = object : CompiledPattern() { init { strategy = KotlinMatchingStrategy } override fun getTypedVarPrefixes(): Array<String> = arrayOf(TYPED_VAR_PREFIX) override fun isTypedVar(str: String): Boolean = when { str.isEmpty() -> false str[0] == '@' -> str.regionMatches(1, TYPED_VAR_PREFIX, 0, TYPED_VAR_PREFIX.length) else -> str.startsWith(TYPED_VAR_PREFIX) } override fun getTypedVarString(element: PsiElement): String { val typedVarString = super.getTypedVarString(element) return if (typedVarString.firstOrNull() == '@') typedVarString.drop(1) else typedVarString } } override fun isMyLanguage(language: Language): Boolean = language == KotlinLanguage.INSTANCE override fun getTemplateContextTypeClass(): Class<KotlinTemplateContextType.Generic> = KotlinTemplateContextType.Generic::class.java override fun getPredefinedTemplates(): Array<Configuration> = KotlinPredefinedConfigurations.createPredefinedTemplates() override fun getDefaultFileType(fileType: LanguageFileType?): LanguageFileType = fileType ?: KotlinFileType.INSTANCE override fun supportsShortenFQNames(): Boolean = true override fun compile(elements: Array<out PsiElement>, globalVisitor: GlobalCompilingVisitor) { KotlinCompilingVisitor(globalVisitor).compile(elements) } override fun getPresentableElement(element: PsiElement): PsiElement { val elem = if (isIdentifier(element)) element.parent else return element return if(elem is KtReferenceExpression) elem.parent else elem } override fun isIdentifier(element: PsiElement?): Boolean = element != null && element.node?.elementType == KtTokens.IDENTIFIER override fun createPatternTree( text: String, context: PatternTreeContext, fileType: LanguageFileType, language: Language, contextId: String?, project: Project, physical: Boolean ): Array<PsiElement> { var elements: List<PsiElement> val factory = KtPsiFactory(project, false) if (PROPERTY_CONTEXT.id == contextId) { try { val fragment = factory.createProperty(text) elements = listOf(getNonWhitespaceChildren(fragment).first().parent) if (elements.first() !is KtProperty) return PsiElement.EMPTY_ARRAY } catch (e: Exception) { return arrayOf(factory.createComment("//").apply { putUserData(PATTERN_ERROR, KotlinBundle.message("error.context.getter.or.setter")) }) } } else { val fragment = factory.createBlockCodeFragment("Unit\n$text", null).let { if (physical) it else it.copy() // workaround to create non-physical code fragment } elements = when (fragment.lastChild) { is PsiComment -> getNonWhitespaceChildren(fragment).drop(1) else -> getNonWhitespaceChildren(fragment.firstChild).drop(1) } } if (elements.isEmpty()) return PsiElement.EMPTY_ARRAY // Standalone KtAnnotationEntry support if (elements.first() is KtAnnotatedExpression && elements.first().lastChild is PsiErrorElement) elements = getNonWhitespaceChildren(elements.first()).dropLast(1) // Standalone KtNullableType || KtUserType w/ type parameter support if (elements.last() is PsiErrorElement && elements.last().firstChild.elementType == KtTokens.QUEST || elements.first() is KtCallExpression && (elements.first() as KtCallExpression).valueArgumentList == null) { try { val fragment = factory.createType(text) elements = listOf(getNonWhitespaceChildren(fragment).first().parent) } catch (e: Exception) {} } // for (element in elements) print(DebugUtil.psiToString(element, false)) return elements.toTypedArray() } inner class KotlinValidator : KotlinRecursiveElementWalkingVisitor() { override fun visitErrorElement(element: PsiErrorElement) { super.visitErrorElement(element) if (shouldShowProblem(element)) { throw MalformedPatternException(element.errorDescription) } } override fun visitComment(comment: PsiComment) { super.visitComment(comment) comment.getUserData(PATTERN_ERROR)?.let { error -> throw MalformedPatternException(error) } } } override fun checkSearchPattern(pattern: CompiledPattern) { val visitor = KotlinValidator() val nodes = pattern.nodes while (nodes.hasNext()) { nodes.current().accept(visitor) nodes.advance() } nodes.reset() } override fun shouldShowProblem(error: PsiErrorElement): Boolean { val description = error.errorDescription val parent = error.parent return when { parent is KtTryExpression && KotlinBundle.message("error.expected.catch.or.finally") == description -> false //naked try parent is KtAnnotatedExpression && KotlinBundle.message("error.expected.an.expression") == description -> false else -> true } } override fun checkReplacementPattern(project: Project, options: ReplaceOptions) { val matchOptions = options.matchOptions val fileType = matchOptions.fileType!! val dialect = matchOptions.dialect!! val searchIsDeclaration = isProbableExpression(matchOptions.searchPattern, fileType, dialect, project) val replacementIsDeclaration = isProbableExpression(options.replacement, fileType, dialect, project) if (searchIsDeclaration != replacementIsDeclaration) { throw UnsupportedPatternException( if (searchIsDeclaration) SSRBundle.message("replacement.template.is.not.expression.error.message") else SSRBundle.message("search.template.is.not.expression.error.message") ) } } private fun ancestors(node: PsiElement?): List<PsiElement?> { val family = mutableListOf(node) repeat(7) { family.add(family.last()?.parent) } return family.drop(1) } override fun isApplicableConstraint( constraintName: String, variableNode: PsiElement?, completePattern: Boolean, target: Boolean ): Boolean { if (variableNode != null) return when (constraintName) { UIUtil.TYPE, UIUtil.TYPE_REGEX -> isApplicableType(variableNode) UIUtil.MINIMUM_ZERO -> isApplicableMinCount(variableNode) || isApplicableMinMaxCount(variableNode) UIUtil.MAXIMUM_UNLIMITED -> isApplicableMaxCount(variableNode) || isApplicableMinMaxCount(variableNode) UIUtil.TEXT_HIERARCHY -> isApplicableTextHierarchy(variableNode) UIUtil.REFERENCE -> isApplicableReference(variableNode) AlsoMatchVarModifier.CONSTRAINT_NAME -> variableNode.parent is KtProperty && !(variableNode.parent as KtProperty).isVar AlsoMatchValModifier.CONSTRAINT_NAME -> variableNode.parent is KtProperty && (variableNode.parent as KtProperty).isVar AlsoMatchCompanionObjectModifier.CONSTRAINT_NAME -> variableNode.parent is KtObjectDeclaration && !(variableNode.parent as KtObjectDeclaration).isCompanion() MatchCallSemanticsModifier.CONSTRAINT_NAME -> variableNode.parent.parent is KtCallElement else -> super.isApplicableConstraint(constraintName, variableNode, completePattern, target) } return super.isApplicableConstraint(constraintName, null as PsiElement?, completePattern, target) } private fun isApplicableReference(variableNode: PsiElement): Boolean = variableNode.parent is KtNameReferenceExpression private fun isApplicableTextHierarchy(variableNode: PsiElement): Boolean { val family = ancestors(variableNode) return when { family[0] is KtClass && (family[0] as KtClass).nameIdentifier == variableNode -> true family[0] is KtObjectDeclaration && (family[0] as KtObjectDeclaration).nameIdentifier == variableNode -> true family[0] is KtEnumEntry && (family[0] as KtEnumEntry).nameIdentifier == variableNode -> true family[0] is KtNamedDeclaration && family[2] is KtClassOrObject -> true family[3] is KtSuperTypeListEntry && family[5] is KtClassOrObject -> true family[4] is KtSuperTypeListEntry && family[6] is KtClassOrObject -> true else -> false } } private fun isApplicableType(variableNode: PsiElement): Boolean { val family = ancestors(variableNode) return when { family[0] is KtNameReferenceExpression -> when (family[1]) { is KtValueArgument, is KtProperty, is KtBinaryExpression, is KtBinaryExpressionWithTypeRHS, is KtIsExpression, is KtBlockExpression, is KtContainerNode, is KtArrayAccessExpression, is KtPostfixExpression, is KtDotQualifiedExpression, is KtSafeQualifiedExpression, is KtCallableReferenceExpression, is KtSimpleNameStringTemplateEntry, is KtBlockStringTemplateEntry, is KtPropertyAccessor, is KtWhenEntry -> true else -> false } family[0] is KtProperty -> true family[0] is KtParameter -> true else -> false } } /** * Returns true if the largest count filter should be [0; 1]. */ private fun isApplicableMinCount(variableNode: PsiElement): Boolean { val family = ancestors(variableNode) return when { family[0] is KtObjectDeclaration -> true family[0] !is KtNameReferenceExpression -> false family[1] is KtProperty -> true family[1] is KtDotQualifiedExpression -> true family[1] is KtCallableReferenceExpression && family[0]?.nextSibling.elementType == KtTokens.COLONCOLON -> true family[1] is KtWhenExpression -> true family[2] is KtTypeReference && family[3] is KtNamedFunction -> true family[3] is KtConstructorCalleeExpression -> true else -> false } } /** * Returns true if the largest count filter should be [1; +inf]. */ private fun isApplicableMaxCount(variableNode: PsiElement): Boolean { val family = ancestors(variableNode) return when { family[0] is KtDestructuringDeclarationEntry -> true family[0] is KtNameReferenceExpression && family[1] is KtWhenConditionWithExpression -> true else -> false } } /** * Returns true if the largest count filter should be [0; +inf]. */ private fun isApplicableMinMaxCount(variableNode: PsiElement): Boolean { val family = ancestors(variableNode) return when { // Containers (lists, bodies, ...) family[0] is KtObjectDeclaration -> false family[1] is KtClassBody -> true family[0] is KtParameter && family[1] is KtParameterList -> true family[0] is KtTypeParameter && family[1] is KtTypeParameterList -> true family[2] is KtTypeParameter && family[3] is KtTypeParameterList -> true family[1] is KtUserType && family[4] is KtParameterList && family[5] !is KtNamedFunction -> true family[1] is KtUserType && family[3] is KtSuperTypeEntry -> true family[1] is KtValueArgument && family[2] is KtValueArgumentList -> true family[1] is KtBlockExpression && family[3] is KtDoWhileExpression -> true family[0] is KtNameReferenceExpression && family[1] is KtBlockExpression -> true family[1] is KtUserType && family[3] is KtTypeProjection && family[5] !is KtNamedFunction -> true // Annotations family[1] is KtUserType && family[4] is KtAnnotationEntry -> true family[1] is KtCollectionLiteralExpression -> true // Strings family[1] is KtSimpleNameStringTemplateEntry -> true // KDoc family[0] is KDocTag -> true // Default: count filter not applicable else -> false } } override fun getCustomPredicates( constraint: MatchVariableConstraint, name: String, options: MatchOptions ): MutableList<MatchPredicate> { val result = SmartList<MatchPredicate>() constraint.apply { if (!StringUtil.isEmptyOrSpaces(nameOfExprType)) { val predicate = KotlinExprTypePredicate( search = if (isRegexExprType) nameOfExprType else expressionTypes, withinHierarchy = isExprTypeWithinHierarchy, ignoreCase = !options.isCaseSensitiveMatch, target = isPartOfSearchResults, baseName = name, regex = isRegexExprType ) result.add(if (isInvertExprType) NotPredicate(predicate) else predicate) } if (getAdditionalConstraint(AlsoMatchValModifier.CONSTRAINT_NAME) == OneStateFilter.ENABLED || getAdditionalConstraint(AlsoMatchVarModifier.CONSTRAINT_NAME) == OneStateFilter.ENABLED ) result.add(KotlinAlsoMatchValVarPredicate()) if (getAdditionalConstraint(AlsoMatchCompanionObjectModifier.CONSTRAINT_NAME) == OneStateFilter.ENABLED) { result.add(KotlinAlsoMatchCompanionObjectPredicate()) } if (getAdditionalConstraint(MatchCallSemanticsModifier.CONSTRAINT_NAME) == OneStateFilter.ENABLED) { result.add(KotlinMatchCallSemantics()) } } return result } private fun isProbableExpression(pattern: String, fileType: LanguageFileType, dialect: Language, project: Project): Boolean { if(pattern.isEmpty()) return false val searchElements = try { createPatternTree(pattern, PatternTreeContext.Block, fileType, dialect, null, project, false) } catch (e: Exception) { return false } if (searchElements.isEmpty()) return false return searchElements[0] is KtDeclaration } override fun getReplaceHandler(project: Project, replaceOptions: ReplaceOptions): KotlinStructuralReplaceHandler = KotlinStructuralReplaceHandler(project) override fun getPatternContexts(): MutableList<PatternContext> = PATTERN_CONTEXTS companion object { const val TYPED_VAR_PREFIX: String = "_____" val DEFAULT_CONTEXT: PatternContext = PatternContext("default", KotlinBundle.lazyMessage("context.default")) val PROPERTY_CONTEXT: PatternContext = PatternContext("property", KotlinBundle.lazyMessage("context.property.getter.or.setter")) private val PATTERN_CONTEXTS: MutableList<PatternContext> = mutableListOf(DEFAULT_CONTEXT, PROPERTY_CONTEXT) private val PATTERN_ERROR: Key<String> = Key("patternError") fun getNonWhitespaceChildren(fragment: PsiElement): List<PsiElement> { var element = fragment.firstChild val result: MutableList<PsiElement> = SmartList() while (element != null) { if (element !is PsiWhiteSpace) result.add(element) element = element.nextSibling } return result } } }
plugins/kotlin/code-insight/structural-search-k1/src/org/jetbrains/kotlin/idea/structuralsearch/KotlinStructuralSearchProfile.kt
2096984604
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sample.experimental @ExperimentalLocationKt class LocationProviderKt { fun getLocation(): Int { return -1 } }
annotation/annotation-experimental-lint/integration-tests/src/main/java/sample/experimental/LocationProviderKt.kt
680641432
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.core.i18n import android.content.Context import androidx.core.i18n.messageformat_icu.simple.MessageFormat import java.util.Locale class MessageFormat private constructor() { companion object { /** * Formats a message pattern string with a variable number of name/value pair arguments. * Creates an ICU MessageFormat for the locale and pattern, * and formats with the arguments. * * @param context Android context object. Used to retrieve user preferences. * @param locale Locale for number formatting and plural selection etc. * @param msg an ICU-MessageFormat-syntax string * @param namedArguments map of argument name to argument value */ @JvmStatic @JvmOverloads fun format( context: Context, locale: Locale = Locale.getDefault(), msg: String, namedArguments: Map<String, Any> ): String { val result: StringBuffer = StringBuffer() return MessageFormat(context, msg, locale) .format(namedArguments, result, null).toString() } /** * Formats a message pattern from Android resource for the default locale with a variable number * of name/value pair arguments. * Creates an ICU MessageFormat for Locale.getDefault() and pattern, * and formats with the arguments. * * @param context Android context object * @param id Android string resource ID representing ICU-MessageFormat-syntax string * @param namedArguments map of argument name to argument value */ @JvmStatic fun format(context: Context, id: Int, namedArguments: Map<String, Any>): String { return format( context, Locale.getDefault(), context.resources.getString(id), namedArguments ) } } }
core/core-i18n/src/main/java/androidx/core/i18n/MessageFormat.kt
660932453
package com.github.tommykw.musical.utils enum class Status { SUCCESS, ERROR, LOADING }
app/src/main/java/com/github/tommykw/musical/utils/Status.kt
449825245
/* * 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.navigation import android.app.Activity import androidx.annotation.IdRes /** * Find a [NavController] given the id of a View and its containing * [Activity]. * * Calling this on a View that is not a [NavHost] or within a [NavHost] * will result in an [IllegalStateException] */ public fun Activity.findNavController( @IdRes viewId: Int ): NavController = Navigation.findNavController(this, viewId)
navigation/navigation-runtime/src/main/java/androidx/navigation/Activity.kt
418061350
package data.autoswipe import android.annotation.SuppressLint import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.os.Build internal class AutoSwipeLauncherBroadcastReceiver : BroadcastReceiver() { @SuppressLint("UnsafeProtectedBroadcastReceiver") override fun onReceive(context: Context?, intent: Intent?) { context?.apply { AutoSwipeIntentService.callingIntent(context).let { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { startForegroundService(it) } else { startService(it) } } } } companion object { fun getCallingIntent(context: Context) = Intent(context, AutoSwipeLauncherBroadcastReceiver::class.java) } }
data/src/main/kotlin/data/autoswipe/AutoSwipeLauncherBroadcastReceiver.kt
1689876330
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.sizeIn import androidx.compose.foundation.layout.widthIn import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.AlignmentLine import androidx.compose.ui.layout.FirstBaseline import androidx.compose.ui.layout.LastBaseline import androidx.compose.ui.layout.Layout import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.TextStyle import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import androidx.compose.ui.util.fastForEachIndexed import kotlin.math.max /** * <a href="https://material.io/components/lists" class="external" target="_blank">Material Design list</a> item. * * Lists are continuous, vertical indexes of text or images. * * ![Lists image](https://developer.android.com/images/reference/androidx/compose/material/lists.png) * * To make this [ListItem] clickable, use [Modifier.clickable]. * To add a background to the [ListItem], wrap it with a [Surface]. * * This component can be used to achieve the list item templates existing in the spec. For example: * - one-line items * @sample androidx.compose.material.samples.OneLineListItems * - two-line items * @sample androidx.compose.material.samples.TwoLineListItems * - three-line items * @sample androidx.compose.material.samples.ThreeLineListItems * * You can combine this component with a checkbox or switch as in the following examples: * @sample androidx.compose.material.samples.ClickableListItems * * @param modifier Modifier to be applied to the list item * @param icon The leading supporting visual of the list item * @param secondaryText The secondary text of the list item * @param singleLineSecondaryText Whether the secondary text is single line * @param overlineText The text displayed above the primary text * @param trailing The trailing meta text, icon, switch or checkbox * @param text The primary text of the list item */ @Composable @ExperimentalMaterialApi fun ListItem( modifier: Modifier = Modifier, icon: @Composable (() -> Unit)? = null, secondaryText: @Composable (() -> Unit)? = null, singleLineSecondaryText: Boolean = true, overlineText: @Composable (() -> Unit)? = null, trailing: @Composable (() -> Unit)? = null, text: @Composable () -> Unit ) { val typography = MaterialTheme.typography val styledText = applyTextStyle(typography.subtitle1, ContentAlpha.high, text)!! val styledSecondaryText = applyTextStyle(typography.body2, ContentAlpha.medium, secondaryText) val styledOverlineText = applyTextStyle(typography.overline, ContentAlpha.high, overlineText) val styledTrailing = applyTextStyle(typography.caption, ContentAlpha.high, trailing) val semanticsModifier = modifier.semantics(mergeDescendants = true) {} if (styledSecondaryText == null && styledOverlineText == null) { OneLine.ListItem(semanticsModifier, icon, styledText, styledTrailing) } else if ( (styledOverlineText == null && singleLineSecondaryText) || styledSecondaryText == null ) { TwoLine.ListItem( semanticsModifier, icon, styledText, styledSecondaryText, styledOverlineText, styledTrailing ) } else { ThreeLine.ListItem( semanticsModifier, icon, styledText, styledSecondaryText, styledOverlineText, styledTrailing ) } } private object OneLine { // TODO(popam): support wide icons // TODO(popam): convert these to sp // List item related defaults. private val MinHeight = 48.dp private val MinHeightWithIcon = 56.dp // Icon related defaults. private val IconMinPaddedWidth = 40.dp private val IconLeftPadding = 16.dp private val IconVerticalPadding = 8.dp // Content related defaults. private val ContentLeftPadding = 16.dp private val ContentRightPadding = 16.dp // Trailing related defaults. private val TrailingRightPadding = 16.dp @Composable fun ListItem( modifier: Modifier = Modifier, icon: @Composable (() -> Unit)?, text: @Composable (() -> Unit), trailing: @Composable (() -> Unit)? ) { val minHeight = if (icon == null) MinHeight else MinHeightWithIcon Row(modifier.heightIn(min = minHeight)) { if (icon != null) { Box( Modifier.align(Alignment.CenterVertically) .widthIn(min = IconLeftPadding + IconMinPaddedWidth) .padding( start = IconLeftPadding, top = IconVerticalPadding, bottom = IconVerticalPadding ), contentAlignment = Alignment.CenterStart ) { icon() } } Box( Modifier.weight(1f) .align(Alignment.CenterVertically) .padding(start = ContentLeftPadding, end = ContentRightPadding), contentAlignment = Alignment.CenterStart ) { text() } if (trailing != null) { Box( Modifier .align(Alignment.CenterVertically) .padding(end = TrailingRightPadding) ) { trailing() } } } } } private object TwoLine { // List item related defaults. private val MinHeight = 64.dp private val MinHeightWithIcon = 72.dp // Icon related defaults. private val IconMinPaddedWidth = 40.dp private val IconLeftPadding = 16.dp private val IconVerticalPadding = 16.dp // Content related defaults. private val ContentLeftPadding = 16.dp private val ContentRightPadding = 16.dp private val OverlineBaselineOffset = 24.dp private val OverlineToPrimaryBaselineOffset = 20.dp private val PrimaryBaselineOffsetNoIcon = 28.dp private val PrimaryBaselineOffsetWithIcon = 32.dp private val PrimaryToSecondaryBaselineOffsetNoIcon = 20.dp private val PrimaryToSecondaryBaselineOffsetWithIcon = 20.dp // Trailing related defaults. private val TrailingRightPadding = 16.dp @Composable fun ListItem( modifier: Modifier = Modifier, icon: @Composable (() -> Unit)?, text: @Composable (() -> Unit), secondaryText: @Composable (() -> Unit)?, overlineText: @Composable (() -> Unit)?, trailing: @Composable (() -> Unit)? ) { val minHeight = if (icon == null) MinHeight else MinHeightWithIcon Row(modifier.heightIn(min = minHeight)) { val columnModifier = Modifier.weight(1f) .padding(start = ContentLeftPadding, end = ContentRightPadding) if (icon != null) { Box( Modifier .sizeIn( minWidth = IconLeftPadding + IconMinPaddedWidth, minHeight = minHeight ) .padding( start = IconLeftPadding, top = IconVerticalPadding, bottom = IconVerticalPadding ), contentAlignment = Alignment.TopStart ) { icon() } } if (overlineText != null) { BaselinesOffsetColumn( listOf(OverlineBaselineOffset, OverlineToPrimaryBaselineOffset), columnModifier ) { overlineText() text() } } else { BaselinesOffsetColumn( listOf( if (icon != null) { PrimaryBaselineOffsetWithIcon } else { PrimaryBaselineOffsetNoIcon }, if (icon != null) { PrimaryToSecondaryBaselineOffsetWithIcon } else { PrimaryToSecondaryBaselineOffsetNoIcon } ), columnModifier ) { text() secondaryText!!() } } if (trailing != null) { OffsetToBaselineOrCenter( if (icon != null) { PrimaryBaselineOffsetWithIcon } else { PrimaryBaselineOffsetNoIcon } ) { Box( // TODO(popam): find way to center and wrap content without minHeight Modifier.heightIn(min = minHeight) .padding(end = TrailingRightPadding), contentAlignment = Alignment.Center ) { trailing() } } } } } } private object ThreeLine { // List item related defaults. private val MinHeight = 88.dp // Icon related defaults. private val IconMinPaddedWidth = 40.dp private val IconLeftPadding = 16.dp private val IconThreeLineVerticalPadding = 16.dp // Content related defaults. private val ContentLeftPadding = 16.dp private val ContentRightPadding = 16.dp private val ThreeLineBaselineFirstOffset = 28.dp private val ThreeLineBaselineSecondOffset = 20.dp private val ThreeLineBaselineThirdOffset = 20.dp private val ThreeLineTrailingTopPadding = 16.dp // Trailing related defaults. private val TrailingRightPadding = 16.dp @Composable fun ListItem( modifier: Modifier = Modifier, icon: @Composable (() -> Unit)?, text: @Composable (() -> Unit), secondaryText: @Composable (() -> Unit), overlineText: @Composable (() -> Unit)?, trailing: @Composable (() -> Unit)? ) { Row(modifier.heightIn(min = MinHeight)) { if (icon != null) { val minSize = IconLeftPadding + IconMinPaddedWidth Box( Modifier .sizeIn(minWidth = minSize, minHeight = minSize) .padding( start = IconLeftPadding, top = IconThreeLineVerticalPadding, bottom = IconThreeLineVerticalPadding ), contentAlignment = Alignment.CenterStart ) { icon() } } BaselinesOffsetColumn( listOf( ThreeLineBaselineFirstOffset, ThreeLineBaselineSecondOffset, ThreeLineBaselineThirdOffset ), Modifier.weight(1f) .padding(start = ContentLeftPadding, end = ContentRightPadding) ) { if (overlineText != null) overlineText() text() secondaryText() } if (trailing != null) { OffsetToBaselineOrCenter( ThreeLineBaselineFirstOffset - ThreeLineTrailingTopPadding, Modifier.padding(top = ThreeLineTrailingTopPadding, end = TrailingRightPadding), trailing ) } } } } /** * Layout that expects [Text] children, and positions them with specific offsets between the * top of the layout and the first text, as well as the last baseline and first baseline * for subsequent pairs of texts. */ // TODO(popam): consider making this a layout composable in `foundation-layout`. @Composable private fun BaselinesOffsetColumn( offsets: List<Dp>, modifier: Modifier = Modifier, content: @Composable () -> Unit ) { Layout(content, modifier) { measurables, constraints -> val childConstraints = constraints.copy(minHeight = 0, maxHeight = Constraints.Infinity) val placeables = measurables.map { it.measure(childConstraints) } val containerWidth = placeables.fold(0) { maxWidth, placeable -> max(maxWidth, placeable.width) } val y = Array(placeables.size) { 0 } var containerHeight = 0 placeables.fastForEachIndexed { index, placeable -> val toPreviousBaseline = if (index > 0) { placeables[index - 1].height - placeables[index - 1][LastBaseline] } else 0 val topPadding = max( 0, offsets[index].roundToPx() - placeable[FirstBaseline] - toPreviousBaseline ) y[index] = topPadding + containerHeight containerHeight += topPadding + placeable.height } layout(containerWidth, containerHeight) { placeables.fastForEachIndexed { index, placeable -> placeable.placeRelative(0, y[index]) } } } } /** * Layout that takes a child and adds the necessary padding such that the first baseline of the * child is at a specific offset from the top of the container. If the child does not have * a first baseline, the layout will match the minHeight constraint and will center the * child. */ // TODO(popam): support fallback alignment in AlignmentLineOffset, and use that here. @Composable private fun OffsetToBaselineOrCenter( offset: Dp, modifier: Modifier = Modifier, content: @Composable () -> Unit ) { Layout(content, modifier) { measurables, constraints -> val placeable = measurables[0].measure(constraints.copy(minHeight = 0)) val baseline = placeable[FirstBaseline] val y: Int val containerHeight: Int if (baseline != AlignmentLine.Unspecified) { y = offset.roundToPx() - baseline containerHeight = max(constraints.minHeight, y + placeable.height) } else { containerHeight = max(constraints.minHeight, placeable.height) y = Alignment.Center.align( IntSize.Zero, IntSize(0, containerHeight - placeable.height), layoutDirection ).y } layout(placeable.width, containerHeight) { placeable.placeRelative(0, y) } } } private fun applyTextStyle( textStyle: TextStyle, contentAlpha: Float, icon: @Composable (() -> Unit)? ): @Composable (() -> Unit)? { if (icon == null) return null return { CompositionLocalProvider(LocalContentAlpha provides contentAlpha) { ProvideTextStyle(textStyle, icon) } } }
compose/material/material/src/commonMain/kotlin/androidx/compose/material/ListItem.kt
1007472891
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.uast.kotlin.internal import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.jetbrains.kotlin.analyzer.AnalysisResult import org.jetbrains.kotlin.codegen.ClassBuilderMode import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.config.LanguageVersionSettingsImpl import org.jetbrains.kotlin.container.ComponentProvider import org.jetbrains.kotlin.container.get import org.jetbrains.kotlin.context.ProjectContext import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmProtoBufUtil import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.BindingTrace import org.jetbrains.kotlin.resolve.jvm.extensions.AnalysisHandlerExtension import org.jetbrains.uast.kotlin.KotlinUastResolveProviderService class CliKotlinUastResolveProviderService : KotlinUastResolveProviderService { private val Project.analysisCompletedHandler: UastAnalysisHandlerExtension? get() = getExtensions(AnalysisHandlerExtension.extensionPointName) .filterIsInstance<UastAnalysisHandlerExtension>() .firstOrNull() @Deprecated("For binary compatibility, please, use KotlinUastTypeMapper") override fun getTypeMapper(element: KtElement): KotlinTypeMapper? { @Suppress("DEPRECATION") return element.project.analysisCompletedHandler?.getTypeMapper() } override fun getBindingContext(element: KtElement): BindingContext { return element.project.analysisCompletedHandler?.getBindingContext() ?: BindingContext.EMPTY } override fun isJvmElement(psiElement: PsiElement) = true override fun getLanguageVersionSettings(element: KtElement): LanguageVersionSettings { return element.project.analysisCompletedHandler?.getLanguageVersionSettings() ?: LanguageVersionSettingsImpl.DEFAULT } override fun getReferenceVariants(ktExpression: KtExpression, nameHint: String): Sequence<PsiElement> = emptySequence() // Not supported } class UastAnalysisHandlerExtension : AnalysisHandlerExtension { private var context: BindingContext? = null private var typeMapper: KotlinTypeMapper? = null private var languageVersionSettings: LanguageVersionSettings? = null fun getBindingContext() = context fun getLanguageVersionSettings() = languageVersionSettings @Deprecated("For binary compatibility, please, use KotlinUastTypeMapper") fun getTypeMapper(): KotlinTypeMapper? { if (typeMapper != null) return typeMapper val bindingContext = context ?: return null val typeMapper = KotlinTypeMapper( bindingContext, ClassBuilderMode.LIGHT_CLASSES, JvmProtoBufUtil.DEFAULT_MODULE_NAME, KotlinTypeMapper.LANGUAGE_VERSION_SETTINGS_DEFAULT, // TODO use proper LanguageVersionSettings useOldInlineClassesManglingScheme = false ) this.typeMapper = typeMapper return typeMapper } override fun doAnalysis( project: Project, module: ModuleDescriptor, projectContext: ProjectContext, files: Collection<KtFile>, bindingTrace: BindingTrace, componentProvider: ComponentProvider ): AnalysisResult? { languageVersionSettings = componentProvider.get<LanguageVersionSettings>() return super.doAnalysis(project, module, projectContext, files, bindingTrace, componentProvider) } override fun analysisCompleted( project: Project, module: ModuleDescriptor, bindingTrace: BindingTrace, files: Collection<KtFile> ): AnalysisResult? { context = bindingTrace.bindingContext return null } }
plugins/kotlin/uast/uast-kotlin/src/org/jetbrains/uast/kotlin/internal/CliKotlinUastResolveProviderService.kt
804408790
/* * Copyright (c) 2022, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. 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. * * 3. Neither the name of the copyright holder 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 * HOLDER 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 no.nordicsemi.android.dfu.profile.settings.repository import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.intPreferencesKey import androidx.datastore.preferences.preferencesDataStore import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.flow.map import no.nordicsemi.android.dfu.profile.settings.domain.DFUSettings import no.nordicsemi.android.dfu.profile.settings.domain.NUMBER_OF_POCKETS_INITIAL import javax.inject.Inject import javax.inject.Singleton private val PACKETS_RECEIPT_NOTIFICATION_KEY = booleanPreferencesKey("packets_receipt") private val KEEP_BOND_KEY = booleanPreferencesKey("keep_bond") private val EXTERNAL_MCU_KEY = booleanPreferencesKey("external_mcu") private val SHOW_WELCOME_KEY = booleanPreferencesKey("show_welcome") private val DISABLE_RESUME = booleanPreferencesKey("disable_resume") private val FORCE_SCANNING_ADDRESS = booleanPreferencesKey("force_scanning_address") private val NUMBER_OF_POCKETS_KEY = intPreferencesKey("number_of_pockets") private val PREPARE_OBJECT_DELAY_KEY = intPreferencesKey("prepare_data_object_delay") private val REBOOT_TIME_KEY = intPreferencesKey("reboot_time") private val SCAN_TIMEOUT_KEY = intPreferencesKey("scan_timeout") @Singleton class SettingsDataSource @Inject constructor( @ApplicationContext private val context: Context ) { private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings") val settings = context.dataStore.data.map { it.toSettings() } suspend fun tickWelcomeScreenShown() { context.dataStore.edit { it[SHOW_WELCOME_KEY] = false } } suspend fun storeSettings(settings: DFUSettings) { context.dataStore.edit { it[PACKETS_RECEIPT_NOTIFICATION_KEY] = settings.packetsReceiptNotification it[PREPARE_OBJECT_DELAY_KEY] = settings.prepareDataObjectDelay it[REBOOT_TIME_KEY] = settings.rebootTime it[SCAN_TIMEOUT_KEY] = settings.scanTimeout it[NUMBER_OF_POCKETS_KEY] = settings.numberOfPackets it[KEEP_BOND_KEY] = settings.keepBondInformation it[EXTERNAL_MCU_KEY] = settings.externalMcuDfu it[DISABLE_RESUME] = settings.disableResume it[FORCE_SCANNING_ADDRESS] = settings.forceScanningInLegacyDfu it[SHOW_WELCOME_KEY] = settings.showWelcomeScreen } } private fun Preferences.toSettings(): DFUSettings { return DFUSettings( this[PACKETS_RECEIPT_NOTIFICATION_KEY] ?: false, this[NUMBER_OF_POCKETS_KEY] ?: NUMBER_OF_POCKETS_INITIAL, this[KEEP_BOND_KEY] ?: false, this[EXTERNAL_MCU_KEY] ?: false, this[DISABLE_RESUME] ?: false, this[PREPARE_OBJECT_DELAY_KEY] ?: 400, this[REBOOT_TIME_KEY] ?: 0, this[SCAN_TIMEOUT_KEY] ?: 2_000, this[FORCE_SCANNING_ADDRESS] ?: false, this[SHOW_WELCOME_KEY] ?: true, ) } }
profile_dfu/src/main/java/no/nordicsemi/android/dfu/profile/settings/repository/SettingsDataSource.kt
2178709924
package database.query import com.onyx.exception.OnyxException import com.onyx.persistence.IManagedEntity import com.onyx.persistence.query.* import database.base.PrePopulatedDatabaseTest import entities.AllAttributeForFetch import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import java.util.* import kotlin.reflect.KClass import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertTrue @RunWith(Parameterized::class) class SelectQueryTest(override var factoryClass: KClass<*>) : PrePopulatedDatabaseTest(factoryClass) { @Test fun testExecuteSelectFields() { val criteria = QueryCriteria("stringValue", QueryCriteriaOperator.STARTS_WITH, "Some") val query = Query(AllAttributeForFetch::class.java, Arrays.asList("longValue", "intPrimitive"), criteria) val results = manager.executeQuery<IManagedEntity>(query) assertNotNull(results) assertEquals(4, results.size, "Expected 5 matching criteria") assertTrue(results[0] is Map<*, *>, "Result is not a map") assertTrue(((results[0] as Map<*, *>)["longValue"] as Number).toInt() > 0, "longValue was not assigned") } @Test @Throws(OnyxException::class, InstantiationException::class, IllegalAccessException::class) fun testSelectOnlyOne() { val criteria = QueryCriteria("stringValue", QueryCriteriaOperator.STARTS_WITH, "Some") val query = Query(AllAttributeForFetch::class.java, arrayListOf("longValue", "intPrimitive"), criteria) query.firstRow = 0 query.maxResults = 1 val results = manager.executeQuery<Any>(query) assertNotNull(results, "Results were null") assertEquals(1, results.size, "Expected 1 result") assertTrue(results[0] is Map<*, *>, "Results are not in map format") if (results[0] is Long) { assertTrue((results[0] as Map<*, *>)["longValue"] as Long > 0, "longValue was not assigned") } else if (results[0] is Int) { assertTrue((results[0] as Map<*, *>)["longValue"] as Int > 0, "Long value was not assigned") } } @Test fun testSelectTwoOrderBy() { val results = manager.select("intPrimitive", "stringValue", "longPrimitive") .from(AllAttributeForFetch::class) .where("stringValue" startsWith "Some") .orderBy("intPrimitive", "stringValue") .first(2) .limit(2) .list<Map<String, Any?>>() assertNotNull(results, "Results should not be null") assertEquals(3, results[0]["intPrimitive"] as Int, "intPrimitive has incorrect value") assertEquals(4, results[1]["intPrimitive"] as Int, "intPrimitive has incorrect value") } @Test fun testNoSelect() { val results = manager.from(AllAttributeForFetch::class).where("stringValue" startsWith "Some") .first(0) .limit(2) .orderBy("stringValue", "intPrimitive") .list<AllAttributeForFetch>() assertNotNull(results, "Results should not be null") assertEquals(2, results.size, "Expected 2 results") assertEquals("FIRST ONE", results[0].id, "Query order is incorrect") assertEquals("FIRST ONE1", results[1].id, "Query order is incorrect") } @Test fun testSelectRelationship() { val criteria = QueryCriteria("stringValue", QueryCriteriaOperator.STARTS_WITH, "Some") .and("child.someOtherField", QueryCriteriaOperator.STARTS_WITH, "HIYA") val query = Query(AllAttributeForFetch::class.java, criteria) query.firstRow = 0 query.maxResults = 2 query.queryOrders = Arrays.asList(QueryOrder("child.someOtherField"), QueryOrder("intPrimitive")) query.selections = Arrays.asList("longValue", "intPrimitive", "child.someOtherField") val results = manager.executeQuery<Any>(query) assertNotNull(results) assertTrue(results.size == 1) assertTrue(results[0] is Map<*, *>) } @Test fun testSelectRelationshipMultiResult() { val results = manager.select("id", "longValue", "intPrimitive", "child.someOtherField") .from(AllAttributeForFetch::class) .where(("id" startsWith "FIRST ONE") and ("child.someOtherField" startsWith "HIYA")) .first(0) .limit(2) .orderBy("id", "longValue", "intPrimitive", "child.someOtherField") .list<Map<String, Any?>>() assertNotNull(results) assertEquals(2, results.size, "Results should have 2 records") assertEquals("FIRST ONE", results[0]["id"], "Invalid query order") assertEquals("FIRST ONE4", results[1]["id"], "Invalid query order") } }
onyx-database-tests/src/test/kotlin/database/query/SelectQueryTest.kt
883202914
// 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 inline fun StringBuilder.wrap(prefix: String, postfix: String, crossinline body: () -> Unit) { append(prefix) body() append(postfix) } inline fun StringBuilder.wrapTag(tag: String, crossinline body: () -> Unit) { wrap("<$tag>", "</$tag>", body) } inline fun StringBuilder.wrapTag(tag: String, params: String, crossinline body: () -> Unit) { wrap("<$tag $params>", "</$tag>", body) }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/util/xmlMarkupStringBuilderUtil.kt
979651108
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.tools import com.jetbrains.python.PythonHelper import com.jetbrains.python.sdk.PythonSdkUtil import java.io.BufferedReader import java.io.File import java.io.InputStreamReader fun main() { val pythons = System.getenv("PACK_STDLIB_FROM") val baseDir = System.getenv("PACK_STDLIB_TO") if (!File(baseDir).exists()) { File(baseDir).mkdirs() } for (python in File(pythons).listFiles()!!) { if (python.name.startsWith(".")) { continue } val sdkHome = python.absolutePath val executable = PythonSdkUtil.getPythonExecutable(sdkHome)?.let { File(it) } if (executable == null) { println("No python on $sdkHome") continue } else { println("Packing stdlib of $sdkHome") } val arg = PythonHelper.GENERATOR3.asParamString() val process = ProcessBuilder(executable.absolutePath, arg, "-u", baseDir).start() BufferedReader(InputStreamReader(process.inputStream)).use { it.lines().forEach(::println) } BufferedReader(InputStreamReader(process.errorStream)).use { it.lines().forEach(::println) } val rc = process.waitFor() if (rc != 0) { error("Process '${executable.absolutePath} $arg' exited with error code $rc") } } }
python/tools/src/com/jetbrains/python/tools/PackPythonSdkLibsForStubs.kt
4219652293
/* * 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.inspections import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.frontend.api.KtAnalysisSession import org.jetbrains.kotlin.idea.frontend.api.types.* import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtPsiFactory class AddFunctionReturnTypeIntention : AbstractHighLevelApiBasedIntention<KtNamedFunction, TypeCandidate>( KtNamedFunction::class.java, { "Specify type explicitly" } ) { override fun isApplicableByPsi(element: KtNamedFunction): Boolean = element.typeReference == null && !element.hasBlockBody() override fun KtAnalysisSession.analyzeAndGetData(element: KtNamedFunction): TypeCandidate? { val returnType = element.getReturnKtType() val approximated = approximateTypeToUpperDenotable(returnType) ?: return null return TypeCandidate(approximated.render()) } private tailrec fun approximateTypeToUpperDenotable(type: KtType): KtDenotableType? = when (type) { is KtNonDenotableType -> when (type) { is KtFlexibleType -> approximateTypeToUpperDenotable(type.upperBound) is KtIntersectionType -> null } is KtDenotableType -> type else -> null } override fun applyTo(element: KtNamedFunction, data: TypeCandidate, editor: Editor?) { element.typeReference = KtPsiFactory(element).createType(data.candidate) } } data class TypeCandidate(val candidate: String)
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/fir/inspections/AddFunctionReturnTypeIntention.kt
2674676644