content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package test
fun <P, Q> funTwoTypeParams(): Int = 1
| plugins/kotlin/idea/tests/testData/compiler/loadJava/compiledKotlin/fun/genericWithTypeVariables/FunTwoTypeParams.kt | 332639800 |
private class FunctionScope {
fun foo(anArgument: Int) {
val aLocal = 1
a
}
private val aClassVal = 1
private fun aClassFun() = 1
companion object {
private val aCompanionVal = 1
private fun aCompanionFun() = 1
}
} | server/src/test/resources/completions/FunctionScope.kt | 3866289954 |
// 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.search
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.*
import com.intellij.psi.impl.cache.impl.id.IdIndex
import com.intellij.psi.impl.cache.impl.id.IdIndexEntry
import com.intellij.psi.search.*
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.util.Processor
import com.intellij.util.indexing.FileBasedIndex
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.base.psi.kotlinFqName
import org.jetbrains.kotlin.idea.base.util.and
import org.jetbrains.kotlin.idea.base.util.not
import org.jetbrains.kotlin.idea.base.util.projectScope
import org.jetbrains.kotlin.idea.base.util.restrictToKotlinSources
import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.scriptDefinitionExists
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.types.expressions.OperatorConventions
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
@Deprecated(
"Use 'org.jetbrains.kotlin.idea.base.util.minus' instead",
ReplaceWith("this.minus", imports = ["org.jetbrains.kotlin.idea.base.util.minus"]),
DeprecationLevel.ERROR
)
operator fun SearchScope.minus(otherScope: GlobalSearchScope): SearchScope = this and !otherScope
@Deprecated(
"Use 'org.jetbrains.kotlin.idea.base.util.allScope' instead",
ReplaceWith("this.allScope()", imports = ["org.jetbrains.kotlin.idea.base.util.allScope"]),
DeprecationLevel.ERROR
)
fun Project.allScope(): GlobalSearchScope = GlobalSearchScope.allScope(this)
@Deprecated(
"Use 'org.jetbrains.kotlin.idea.base.util.projectScope' instead",
ReplaceWith("this.projectScope()", imports = ["org.jetbrains.kotlin.idea.base.util.projectScope"]),
DeprecationLevel.ERROR
)
fun Project.projectScope(): GlobalSearchScope = GlobalSearchScope.projectScope(this)
@Deprecated(
"Use 'org.jetbrains.kotlin.idea.base.util.moduleScope' instead",
ReplaceWith("this.moduleScope()", imports = ["org.jetbrains.kotlin.idea.base.util.moduleScope"]),
DeprecationLevel.ERROR
)
fun PsiFile.fileScope(): GlobalSearchScope = GlobalSearchScope.fileScope(this)
fun Project.containsKotlinFile(): Boolean = FileTypeIndex.containsFileOfType(KotlinFileType.INSTANCE, projectScope())
/**
* `( *\\( *)` and `( *\\) *)` – to find parenthesis
* `( *, *(?![^\\[]*]))` – to find commas outside square brackets
*/
private val parenthesisRegex = Regex("( *\\( *)|( *\\) *)|( *, *(?![^\\[]*]))")
private inline fun CharSequence.ifNotEmpty(action: (CharSequence) -> Unit) {
takeIf(CharSequence::isNotBlank)?.let(action)
}
fun SearchScope.toHumanReadableString(): String = buildString {
val scopeText = [email protected]()
var currentIndent = 0
var lastIndex = 0
for (parenthesis in parenthesisRegex.findAll(scopeText)) {
val subSequence = scopeText.subSequence(lastIndex, parenthesis.range.first)
subSequence.ifNotEmpty {
append(" ".repeat(currentIndent))
appendLine(it)
}
val value = parenthesis.value
when {
"(" in value -> currentIndent += 2
")" in value -> currentIndent -= 2
}
lastIndex = parenthesis.range.last + 1
}
if (isEmpty()) append(scopeText)
}
// Copied from SearchParameters.getEffectiveSearchScope()
fun ReferencesSearch.SearchParameters.effectiveSearchScope(element: PsiElement): SearchScope {
if (element == elementToSearch) return effectiveSearchScope
if (isIgnoreAccessScope) return scopeDeterminedByUser
val accessScope = element.useScope()
return scopeDeterminedByUser.intersectWith(accessScope)
}
fun isOnlyKotlinSearch(searchScope: SearchScope): Boolean {
return searchScope is LocalSearchScope && searchScope.scope.all { it.containingFile is KtFile }
}
fun PsiElement.codeUsageScopeRestrictedToProject(): SearchScope = project.projectScope().intersectWith(codeUsageScope())
fun PsiElement.useScope(): SearchScope = PsiSearchHelper.getInstance(project).getUseScope(this)
fun PsiElement.codeUsageScope(): SearchScope = PsiSearchHelper.getInstance(project).getCodeUsageScope(this)
// TODO: improve scope calculations
fun PsiElement.codeUsageScopeRestrictedToKotlinSources(): SearchScope = codeUsageScope().restrictToKotlinSources()
fun PsiSearchHelper.isCheapEnoughToSearchConsideringOperators(
name: String,
scope: GlobalSearchScope,
fileToIgnoreOccurrencesIn: PsiFile?,
progress: ProgressIndicator?
): PsiSearchHelper.SearchCostResult {
if (OperatorConventions.isConventionName(Name.identifier(name))) {
return PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES
}
return isCheapEnoughToSearch(name, scope, fileToIgnoreOccurrencesIn, progress)
}
fun findScriptsWithUsages(declaration: KtNamedDeclaration, processor: (KtFile) -> Boolean): Boolean {
val project = declaration.project
val scope = declaration.useScope() as? GlobalSearchScope ?: return true
val name = declaration.name.takeIf { it?.isNotBlank() == true } ?: return true
val collector = Processor<VirtualFile> { file ->
val ktFile =
(PsiManager.getInstance(project).findFile(file) as? KtFile)?.takeIf { it.scriptDefinitionExists() } ?: return@Processor true
processor(ktFile)
}
return FileBasedIndex.getInstance().getFilesWithKey(
IdIndex.NAME,
setOf(IdIndexEntry(name, true)),
collector,
scope
)
}
data class ReceiverTypeSearcherInfo(
val psiClass: PsiClass?,
val containsTypeOrDerivedInside: ((KtDeclaration) -> Boolean)
)
fun PsiReference.isImportUsage(): Boolean =
element.getNonStrictParentOfType<KtImportDirective>() != null
// Used in the "mirai" plugin
@Deprecated(
"Use org.jetbrains.kotlin.idea.base.psi.kotlinFqName",
level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith("kotlinFqName", "org.jetbrains.kotlin.idea.base.psi.kotlinFqName")
)
fun PsiElement.getKotlinFqName(): FqName? = kotlinFqName
fun PsiElement?.isPotentiallyOperator(): Boolean {
val namedFunction = safeAs<KtNamedFunction>() ?: return false
if (namedFunction.hasModifier(KtTokens.OPERATOR_KEYWORD)) return true
// operator modifier could be omitted for overriding function
if (!namedFunction.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return false
val name = namedFunction.name ?: return false
if (!OperatorConventions.isConventionName(Name.identifier(name))) return false
// TODO: it's fast PSI-based check, a proper check requires call to resolveDeclarationWithParents() that is not frontend-independent
return true
}
| plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/search/searchUtil.kt | 642400469 |
package jp.juggler.subwaytooter.view
import android.text.Spannable
import android.text.method.LinkMovementMethod
import android.text.method.Touch
import android.text.style.ClickableSpan
import android.view.MotionEvent
import android.widget.TextView
import jp.juggler.util.LogCategory
object MyLinkMovementMethod : LinkMovementMethod() {
private val log = LogCategory("MyLinkMovementMethod")
// 改行より右をタッチしても反応しないようにする
override fun onTouchEvent(widget: TextView, buffer: Spannable, event: MotionEvent): Boolean {
val action = event.action
if (action != MotionEvent.ACTION_UP && action != MotionEvent.ACTION_DOWN) {
return Touch.onTouchEvent(widget, buffer, event)
}
var x = event.x.toInt()
var y = event.y.toInt()
x -= widget.totalPaddingLeft
y -= widget.totalPaddingTop
x += widget.scrollX
y += widget.scrollY
val layout = widget.layout
val line = layout.getLineForVertical(y)
if (0 <= line && line < layout.lineCount) {
val lineLeft = layout.getLineLeft(line)
val lineRight = layout.getLineRight(line)
if (lineLeft <= x && x <= lineRight) {
val offset = try {
layout.getOffsetForHorizontal(line, x.toFloat())
} catch (ex: Throwable) {
// getOffsetForHorizontal raises error on Xiaomi Mi A1(tissot_sprout), Android 8.1
log.trace(ex, "getOffsetForHorizontal failed.")
null
}
if (offset != null) {
val link = buffer.getSpans(offset, offset, ClickableSpan::class.java)
if (link != null && link.isNotEmpty()) {
if (action == MotionEvent.ACTION_UP) {
link[0].onClick(widget)
}
if (widget is MyTextView) {
widget.linkHit = true
}
return true
}
}
}
}
Touch.onTouchEvent(widget, buffer, event)
return false
}
}
| app/src/main/java/jp/juggler/subwaytooter/view/MyLinkMovementMethod.kt | 466371372 |
// snippet-sourcedescription:[CreateEndpoint.kt demonstrates how to create an endpoint for an application in Amazon Pinpoint.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-keyword:[Amazon Pinpoint]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.pinpoint
// snippet-start:[pinpoint.kotlin.createendpoint.import]
import aws.sdk.kotlin.services.pinpoint.PinpointClient
import aws.sdk.kotlin.services.pinpoint.model.ChannelType
import aws.sdk.kotlin.services.pinpoint.model.EndpointDemographic
import aws.sdk.kotlin.services.pinpoint.model.EndpointLocation
import aws.sdk.kotlin.services.pinpoint.model.EndpointRequest
import aws.sdk.kotlin.services.pinpoint.model.EndpointUser
import aws.sdk.kotlin.services.pinpoint.model.GetEndpointRequest
import aws.sdk.kotlin.services.pinpoint.model.UpdateEndpointRequest
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.Date
import java.util.UUID
import kotlin.system.exitProcess
// snippet-end:[pinpoint.kotlin.createendpoint.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<appId>
Where:
appId - The Id value of the application to create an endpoint for.
"""
if (args.size != 1) {
println(usage)
exitProcess(0)
}
val appId = args[0]
val endId = createPinpointEndpoint(appId)
if (endId != null)
println("The Endpoint id is: $endId")
}
// snippet-start:[pinpoint.kotlin.createendpoint.main]
suspend fun createPinpointEndpoint(applicationIdVal: String?): String? {
val endpointIdVal = UUID.randomUUID().toString()
println("Endpoint ID: $endpointIdVal")
val endpointRequestOb = createEndpointRequestData()
val updateEndpointRequest = UpdateEndpointRequest {
applicationId = applicationIdVal
endpointId = endpointIdVal
endpointRequest = endpointRequestOb
}
PinpointClient { region = "us-west-2" }.use { pinpoint ->
val updateEndpointResponse = pinpoint.updateEndpoint(updateEndpointRequest)
println("Update Endpoint Response ${updateEndpointResponse.messageBody}")
val getEndpointRequest = GetEndpointRequest {
applicationId = applicationIdVal
endpointId = endpointIdVal
}
val endpointResponse = pinpoint.getEndpoint(getEndpointRequest)
println(endpointResponse.endpointResponse?.address)
println(endpointResponse.endpointResponse?.channelType)
println(endpointResponse.endpointResponse?.applicationId)
println(endpointResponse.endpointResponse?.endpointStatus)
println(endpointResponse.endpointResponse?.requestId)
println(endpointResponse.endpointResponse?.user)
// Return the endpoint Id value.
return endpointResponse.endpointResponse?.id
}
}
private fun createEndpointRequestData(): EndpointRequest? {
val favoriteTeams = mutableListOf<String>()
favoriteTeams.add("Lakers")
favoriteTeams.add("Warriors")
val customAttributes = mutableMapOf<String, List<String>>()
customAttributes["team"] = favoriteTeams
val demographicOb = EndpointDemographic {
appVersion = "1.0"
make = "apple"
model = "iPhone"
modelVersion = "7"
platform = "ios"
platformVersion = "10.1.1"
timezone = "America/Los_Angeles"
}
val locationOb = EndpointLocation {
city = "Los Angeles"
country = "US"
latitude = 34.0
longitude = -118.2
postalCode = "90068"
region = "CA"
}
val metricsMap = mutableMapOf<String, Double>()
metricsMap["health"] = 100.00
metricsMap["luck"] = 75.00
val userOb = EndpointUser {
userId = UUID.randomUUID().toString()
}
val df: DateFormat =
SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'") // Quoted "Z" to indicate UTC, no timezone offset
val nowAsISO = df.format(Date())
return EndpointRequest {
address = UUID.randomUUID().toString()
attributes = customAttributes
channelType = ChannelType.Apns
demographic = demographicOb
effectiveDate = nowAsISO
location = locationOb
metrics = metricsMap
optOut = "NONE"
requestId = UUID.randomUUID().toString()
user = userOb
}
}
// snippet-end:[pinpoint.kotlin.createendpoint.main]
| kotlin/services/pinpoint/src/main/kotlin/com/kotlin/pinpoint/CreateEndpoint.kt | 1552511594 |
package org.pixelndice.table.pixelserver.connection.main.state04hostgame
import com.google.common.base.Throwables
import org.apache.logging.log4j.LogManager
import org.hibernate.Session
import org.hibernate.Transaction
import org.pixelndice.table.pixelprotocol.Protobuf
import org.pixelndice.table.pixelserver.connection.main.Context
import org.pixelndice.table.pixelserver.connection.main.State
import org.pixelndice.table.pixelserver.connection.main.StateStop
import org.pixelndice.table.pixelserver.sessionFactory
import org.pixelndice.table.pixelserverhibernate.Account
private val logger = LogManager.getLogger(State08WaitingPlayerList::class.java)
class State08WaitingPlayerList : State {
override fun process(ctx: Context) {
val p: Protobuf.Packet? = ctx.channel.packet
val resp = Protobuf.Packet.newBuilder()
if (p != null) {
if (p.payloadCase == Protobuf.Packet.PayloadCase.PUBLISHPLAYERLIST) {
logger.debug("Received publish player list. Number of accounts: ${p.publishPlayerList.playersList.size}")
p.publishPlayerList.playersList.forEach { account ->
logger.debug("${account.id} - ${account.email} - ${account.name}")
var session: Session? = null
var tx: Transaction? = null
try {
session = sessionFactory.openSession()
val query = session.createNamedQuery("accountById", Account::class.java)
query.setParameter("id", account.id)
val list = query.list()
if (list.isNotEmpty()) {
tx = session.beginTransaction()
ctx.game!!.players.add(list[0])
session.merge(ctx.game)
logger.debug("Added account ${account} to game player list.")
tx.commit()
}else{
logger.warn("Account id not found: ${account.id}")
}
}catch (e: Exception){
logger.fatal("Hibernate fatal error!")
logger.fatal(Throwables.getStackTraceAsString(e))
tx?.rollback()
}finally {
session?.close()
}
}
ctx.state = StateStop()
}else{
logger.error("Expecting publish player list. Instead received: $p")
val error = Protobuf.EndWithError.newBuilder()
error.reason = "key.errorexpectingplayerlist"
resp.endWithError = error.build()
ctx.channel.packet = resp.build()
ctx.state = StateStop()
}
}
}
} | src/main/kotlin/org/pixelndice/table/pixelserver/connection/main/state04hostgame/State08WaitingPlayerList.kt | 2853560636 |
/*
* Copyright (C) 2017 JRummy Apps Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jrummyapps.android.colorpicker
import android.content.Context
import android.util.TypedValue
internal object DrawingUtils {
fun dpToPx(c: Context, dipValue: Float): Int {
val metrics = c.resources.displayMetrics
val v = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, metrics)
val res = (v + 0.5).toInt() // Round
// Ensure at least 1 pixel if val was > 0
return if (res == 0 && v > 0) 1 else res
}
}
| colorpicker/src/main/java/com/jrummyapps/android/colorpicker/DrawingUtils.kt | 4099056242 |
/*
* Copyright 2017, Red Hat, Inc. and individual contributors as indicated by the
* @author tags. See the copyright.txt file in the distribution for a full
* listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This software 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 Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
* site: http://www.fsf.org.
*/
package org.zanata.feature.account
import org.junit.runner.RunWith
import org.junit.runners.Suite
import org.zanata.feature.account.comp.InactiveUserLoginCTest
import org.zanata.feature.account.comp.RegisterCTest
import org.zanata.feature.account.comp.RegisterUsernameCharactersCTest
/**
* @author Damian Jansen [[email protected]](mailto:[email protected])
*/
@RunWith(Suite::class)
@Suite.SuiteClasses(ChangePasswordTest::class,
EmailValidationTest::class,
InactiveUserLoginTest::class,
ProfileTest::class, RegisterTest::class,
UsernameValidationTest::class,
RegisterTest::class,
//Comprehensive tests
InactiveUserLoginCTest::class,
RegisterCTest::class,
RegisterUsernameCharactersCTest::class)
class AccountTestSuite
| server/functional-test/src/test/java/org/zanata/feature/account/AccountTestSuite.kt | 2895359492 |
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.vcs.log.graph
import org.junit.Assert.*
import org.junit.Test
class TestGraphBuilderTest : AbstractTestWithTextFile("testGraphBuilder") {
fun runTest(testName: String, builder: TestGraphBuilder.() -> Unit) {
val actual = graph(builder).asString()
assertEquals(loadText(testName + ".txt"), actual)
}
@Test fun simple() = runTest("simple") {
1(2)
2(3)
3()
}
@Test fun simpleManyNodes() = runTest("simpleManyNodes") {
3(4, 6, 8)
4(5, 6, 7, 8)
7(8, 6)
6(9, 10, 11)
9(10, 11)
10(11)
5(8, 11)
8(11)
11()
}
@Test fun specialEdges() = runTest("specialEdges") {
1(2.u, 3.dot, 100.not_load, 42.down_dot, null.down_dot, null.not_load, 0.up_dot, null.up_dot)
2(null.up_dot)
3(0.up_dot)
}
@Test fun specialNodes() = runTest("specialNodes") {
2.U(3, 4)
3.UNM(4.dot)
4.U()
100.NOT_LOAD()
}
} | platform/vcs-log/graph/test/com/intellij/vcs/log/graph/TestGraphBuilderTest.kt | 1641723590 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.extractOneToManyParent
import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent
import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class TreeEntityImpl(val dataSource: TreeEntityData) : TreeEntity, WorkspaceEntityBase() {
companion object {
internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(TreeEntity::class.java, TreeEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, false)
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(TreeEntity::class.java, TreeEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, false)
val connections = listOf<ConnectionId>(
CHILDREN_CONNECTION_ID,
PARENTENTITY_CONNECTION_ID,
)
}
override val data: String
get() = dataSource.data
override val children: List<TreeEntity>
get() = snapshot.extractOneToManyChildren<TreeEntity>(CHILDREN_CONNECTION_ID, this)!!.toList()
override val parentEntity: TreeEntity
get() = snapshot.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this)!!
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: TreeEntityData?) : ModifiableWorkspaceEntityBase<TreeEntity>(), TreeEntity.Builder {
constructor() : this(TreeEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity TreeEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isDataInitialized()) {
error("Field TreeEntity#data should be initialized")
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) {
error("Field TreeEntity#children should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) {
error("Field TreeEntity#children should be initialized")
}
}
if (_diff != null) {
if (_diff.extractOneToManyParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) {
error("Field TreeEntity#parentEntity should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) {
error("Field TreeEntity#parentEntity should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as TreeEntity
this.entitySource = dataSource.entitySource
this.data = dataSource.data
if (parents != null) {
this.parentEntity = parents.filterIsInstance<TreeEntity>().single()
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var data: String
get() = getEntityData().data
set(value) {
checkModificationAllowed()
getEntityData().data = value
changedProperty.add("data")
}
// List of non-abstract referenced types
var _children: List<TreeEntity>? = emptyList()
override var children: List<TreeEntity>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<TreeEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true,
CHILDREN_CONNECTION_ID)] as? List<TreeEntity>
?: emptyList())
}
else {
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<TreeEntity> ?: emptyList()
}
}
set(value) {
// Setter of the list of non-abstract referenced types
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) {
_diff.addEntity(item_value)
}
}
_diff.updateOneToManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*>) {
item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value
}
changedProperty.add("children")
}
override var parentEntity: TreeEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
PARENTENTITY_CONNECTION_ID)]!! as TreeEntity
}
else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as TreeEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override fun getEntityData(): TreeEntityData = result ?: super.getEntityData() as TreeEntityData
override fun getEntityClass(): Class<TreeEntity> = TreeEntity::class.java
}
}
class TreeEntityData : WorkspaceEntityData<TreeEntity>() {
lateinit var data: String
fun isDataInitialized(): Boolean = ::data.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<TreeEntity> {
val modifiable = TreeEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): TreeEntity {
return getCached(snapshot) {
val entity = TreeEntityImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return TreeEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return TreeEntity(data, entitySource) {
this.parentEntity = parents.filterIsInstance<TreeEntity>().single()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
res.add(TreeEntity::class.java)
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as TreeEntityData
if (this.entitySource != other.entitySource) return false
if (this.data != other.data) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as TreeEntityData
if (this.data != other.data) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + data.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + data.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/TreeEntityImpl.kt | 2499090293 |
// 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.idea.maven.plugins.groovy
import com.intellij.openapi.extensions.ExtensionPointName
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.idea.maven.importing.*
import org.jetbrains.idea.maven.model.MavenPlugin
import org.jetbrains.idea.maven.project.MavenProject
import org.jetbrains.idea.maven.utils.MavenJDOMUtil
import java.util.stream.Stream
import kotlin.streams.asSequence
import kotlin.streams.asStream
class GroovyPluginConfigurator : MavenWorkspaceConfigurator {
private val CONTRIBUTOR_EP = ExtensionPointName.create<PluginContributor>(
"org.jetbrains.idea.maven.importing.groovy.foldersConfiguratorContributor")
interface PluginContributor {
fun getAdditionalPlugins(): List<GroovyPlugin>
}
@Suppress("DEPRECATION")
interface GroovyPlugin {
val groupId: String
val artifactId: String
val requiredDependency: PluginDependency?
data class PluginDependency(val groupId: String, val artifactId: String)
@JvmDefault
fun findInProject(mavenProject: MavenProject): MavenPlugin? {
val plugin = mavenProject.findPlugin(groupId, artifactId)
if (plugin == null) return null
val dependency = requiredDependency
if (dependency != null) {
if (plugin.dependencies.none { id -> dependency.groupId == id.groupId && dependency.artifactId == id.artifactId }) {
return null
}
}
return plugin
}
}
enum class KnownPlugins(override val groupId: String,
override val artifactId: String,
override val requiredDependency: GroovyPlugin.PluginDependency? = null) : GroovyPlugin {
GROOVY_1_0("org.codehaus.groovy.maven", "gmaven-plugin"),
GROOVY_1_1_PLUS("org.codehaus.gmaven", "gmaven-plugin"),
GROOVY_GMAVEN("org.codehaus.gmaven", "groovy-maven-plugin"),
GROOVY_GMAVEN_PLUS("org.codehaus.gmavenplus", "gmavenplus-plugin"),
GROOVY_ECLIPSE_COMPILER("org.apache.maven.plugins", "maven-compiler-plugin",
GroovyPlugin.PluginDependency("org.codehaus.groovy", "groovy-eclipse-compiler"));
}
override fun getAdditionalSourceFolders(context: MavenWorkspaceConfigurator.FoldersContext): Stream<String> {
return getGroovySources(context, isForMain = true)
}
override fun getAdditionalTestSourceFolders(context: MavenWorkspaceConfigurator.FoldersContext): Stream<String> {
return getGroovySources(context, isForMain = false)
}
private fun getGroovySources(context: MavenWorkspaceConfigurator.FoldersContext, isForMain: Boolean): Stream<String> {
return getGroovyPluginsInProject(context)
.flatMap { collectGroovyFolders(it, isForMain) }
.asStream()
}
override fun getFoldersToExclude(context: MavenWorkspaceConfigurator.FoldersContext): Stream<String> {
return getGroovyPluginsInProject(context)
.flatMap { collectIgnoredFolders(context.mavenProject, it) }
.asStream()
}
private fun getGroovyPluginsInProject(context: MavenWorkspaceConfigurator.FoldersContext): Sequence<MavenPlugin> {
val allPlugins = KnownPlugins.values().asSequence() +
(CONTRIBUTOR_EP.extensionList.stream().flatMap { it.getAdditionalPlugins().stream() }).asSequence()
return allPlugins.mapNotNull { it.findInProject(context.mavenProject) }
}
companion object {
@ApiStatus.Internal
fun collectGroovyFolders(plugin: MavenPlugin, isForMain: Boolean): Collection<String> {
val goal = if (isForMain) "compile" else "testCompile"
val defaultDir = if (isForMain) "src/main/groovy" else "src/test/groovy"
val dirs = MavenJDOMUtil.findChildrenValuesByPath(plugin.getGoalConfiguration(goal), "sources", "fileset.directory")
return if (dirs.isEmpty()) listOf(defaultDir) else dirs
}
@ApiStatus.Internal
fun collectIgnoredFolders(mavenProject: MavenProject, plugin: MavenPlugin): Collection<String> {
val stubsDir = MavenJDOMUtil.findChildValueByPath(plugin.getGoalConfiguration("generateStubs"), "outputDirectory")
val testStubsDir = MavenJDOMUtil.findChildValueByPath(plugin.getGoalConfiguration("generateTestStubs"), "outputDirectory")
// exclude common parent of /groovy-stubs/main and /groovy-stubs/test
val defaultStubsDir = mavenProject.getGeneratedSourcesDirectory(false) + "/groovy-stubs"
return listOf(stubsDir ?: defaultStubsDir, testStubsDir ?: defaultStubsDir)
}
}
} | plugins/maven/src/main/java/org/jetbrains/idea/maven/plugins/groovy/GroovyPluginConfigurator.kt | 838234127 |
// 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.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.project.builtIns
import org.jetbrains.kotlin.idea.quickfix.ChangeToMutableCollectionFix
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.lexer.KtSingleValueToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments
import org.jetbrains.kotlin.psi.psiUtil.siblings
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.descriptorUtil.isSubclassOf
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.SimpleType
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.codeinsight.utils.findExistingEditor
class SuspiciousCollectionReassignmentInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor =
binaryExpressionVisitor(fun(binaryExpression) {
if (binaryExpression.right == null) return
val operationToken = binaryExpression.operationToken as? KtSingleValueToken ?: return
if (operationToken !in targetOperations) return
val left = binaryExpression.left ?: return
val property = left.mainReference?.resolve() as? KtProperty ?: return
if (!property.isVar) return
val context = binaryExpression.analyze()
val leftType = left.getType(context) ?: return
val leftDefaultType = leftType.constructor.declarationDescriptor?.defaultType ?: return
if (!leftType.isReadOnlyCollectionOrMap(binaryExpression.builtIns)) return
if (context.diagnostics.forElement(binaryExpression).any { it.severity == Severity.ERROR }) return
val fixes = mutableListOf<LocalQuickFix>()
if (ChangeTypeToMutableFix.isApplicable(property)) {
fixes.add(ChangeTypeToMutableFix(leftType))
}
if (ReplaceWithFilterFix.isApplicable(binaryExpression, leftDefaultType, context)) {
fixes.add(ReplaceWithFilterFix())
}
when {
ReplaceWithAssignmentFix.isApplicable(binaryExpression, property, context) -> fixes.add(ReplaceWithAssignmentFix())
JoinWithInitializerFix.isApplicable(binaryExpression, property) -> fixes.add(JoinWithInitializerFix(operationToken))
}
if (fixes.isEmpty()) return
val typeText = leftDefaultType.toString().takeWhile { it != '<' }.lowercase()
val operationReference = binaryExpression.operationReference
holder.registerProblem(
operationReference,
KotlinBundle.message("0.on.a.readonly.1.creates.a.new.1.under.the.hood", operationReference.text, typeText),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
*fixes.toTypedArray()
)
})
private class ChangeTypeToMutableFix(private val type: KotlinType) : LocalQuickFix {
override fun getName() = KotlinBundle.message("change.type.to.mutable.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val operationReference = descriptor.psiElement as? KtOperationReferenceExpression ?: return
val binaryExpression = operationReference.parent as? KtBinaryExpression ?: return
val left = binaryExpression.left ?: return
val property = left.mainReference?.resolve() as? KtProperty ?: return
ChangeToMutableCollectionFix.applyFix(property, type)
property.valOrVarKeyword.replace(KtPsiFactory(property).createValKeyword())
binaryExpression.findExistingEditor()?.caretModel?.moveToOffset(property.endOffset)
}
companion object {
fun isApplicable(property: KtProperty): Boolean {
return ChangeToMutableCollectionFix.isApplicable(property)
}
}
}
private class ReplaceWithFilterFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.with.filter.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val operationReference = descriptor.psiElement as? KtOperationReferenceExpression ?: return
val binaryExpression = operationReference.parent as? KtBinaryExpression ?: return
val left = binaryExpression.left ?: return
val right = binaryExpression.right ?: return
val psiFactory = KtPsiFactory(operationReference)
operationReference.replace(psiFactory.createOperationName(KtTokens.EQ.value))
right.replace(psiFactory.createExpressionByPattern("$0.filter { it !in $1 }", left, right))
}
companion object {
fun isApplicable(binaryExpression: KtBinaryExpression, leftType: SimpleType, context: BindingContext): Boolean {
if (binaryExpression.operationToken != KtTokens.MINUSEQ) return false
if (leftType == binaryExpression.builtIns.map.defaultType) return false
return binaryExpression.right?.getType(context)?.classDescriptor()?.isSubclassOf(binaryExpression.builtIns.iterable) == true
}
}
}
private class ReplaceWithAssignmentFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.with.assignment.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val operationReference = descriptor.psiElement as? KtOperationReferenceExpression ?: return
val psiFactory = KtPsiFactory(operationReference)
operationReference.replace(psiFactory.createOperationName(KtTokens.EQ.value))
}
companion object {
val emptyCollectionFactoryMethods =
listOf("emptyList", "emptySet", "emptyMap", "listOf", "setOf", "mapOf").map { "kotlin.collections.$it" }
fun isApplicable(binaryExpression: KtBinaryExpression, property: KtProperty, context: BindingContext): Boolean {
if (binaryExpression.operationToken != KtTokens.PLUSEQ) return false
if (!property.isLocal) return false
val initializer = property.initializer as? KtCallExpression ?: return false
if (initializer.valueArguments.isNotEmpty()) return false
val initializerResultingDescriptor = initializer.getResolvedCall(context)?.resultingDescriptor
val fqName = initializerResultingDescriptor?.fqNameOrNull()?.asString()
if (fqName !in emptyCollectionFactoryMethods) return false
val rightClassDescriptor = binaryExpression.right?.getType(context)?.classDescriptor() ?: return false
val initializerClassDescriptor = initializerResultingDescriptor?.returnType?.classDescriptor() ?: return false
if (!rightClassDescriptor.isSubclassOf(initializerClassDescriptor)) return false
if (binaryExpression.siblings(forward = false, withItself = false)
.filter { it != property }
.any { sibling -> sibling.anyDescendantOfType<KtSimpleNameExpression> { it.mainReference.resolve() == property } }
) return false
return true
}
}
}
private class JoinWithInitializerFix(private val op: KtSingleValueToken) : LocalQuickFix {
override fun getName() = KotlinBundle.message("join.with.initializer.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val operationReference = descriptor.psiElement as? KtOperationReferenceExpression ?: return
val binaryExpression = operationReference.parent as? KtBinaryExpression ?: return
val left = binaryExpression.left ?: return
val right = binaryExpression.right ?: return
val property = left.mainReference?.resolve() as? KtProperty ?: return
val initializer = property.initializer ?: return
val psiFactory = KtPsiFactory(operationReference)
val newOp = if (op == KtTokens.PLUSEQ) KtTokens.PLUS else KtTokens.MINUS
val replaced = initializer.replaced(psiFactory.createExpressionByPattern("$0 $1 $2", initializer, newOp.value, right))
binaryExpression.delete()
property.findExistingEditor()?.caretModel?.moveToOffset(replaced.endOffset)
}
companion object {
fun isApplicable(binaryExpression: KtBinaryExpression, property: KtProperty): Boolean {
if (!property.isLocal || property.initializer == null) return false
return binaryExpression.getPrevSiblingIgnoringWhitespaceAndComments() == property
}
}
}
}
private val targetOperations: List<KtSingleValueToken> = listOf(KtTokens.PLUSEQ, KtTokens.MINUSEQ)
private fun KotlinType.classDescriptor() = constructor.declarationDescriptor as? ClassDescriptor
internal fun KotlinType.isReadOnlyCollectionOrMap(builtIns: KotlinBuiltIns): Boolean {
val leftDefaultType = constructor.declarationDescriptor?.defaultType ?: return false
return leftDefaultType in listOf(builtIns.list.defaultType, builtIns.set.defaultType, builtIns.map.defaultType)
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/SuspiciousCollectionReassignmentInspection.kt | 3193508840 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.causeway.client.kroviz.ui.dialog
import org.apache.causeway.client.kroviz.to.ValueType
import org.apache.causeway.client.kroviz.ui.core.FormItem
import org.apache.causeway.client.kroviz.ui.core.RoDialog
import org.apache.causeway.client.kroviz.ui.core.SessionManager
import org.apache.causeway.client.kroviz.ui.core.ViewManager
import org.apache.causeway.client.kroviz.ui.menu.DropDownMenuBuilder
import org.apache.causeway.client.kroviz.utils.*
import io.kvision.html.Link as KvisionHtmlLink
class DiagramDialog(
var label: String,
private var pumlCode: String,
) : Controller() {
private var callBack: Any = UUID()
private val formItems = mutableListOf<FormItem>()
override fun open() {
super.open()
UmlUtils.generateJsonDiagram(pumlCode, callBack)
}
init {
val fi = FormItem("svg", ValueType.SVG_INLINE, callBack = callBack)
formItems.add(fi)
dialog = RoDialog(
widthPerc = 80,
heightPerc = 80,
caption = label,
items = formItems,
controller = this,
defaultAction = "Pin",
menu = buildMenu()
)
}
override fun execute(action: String?) {
pin()
}
private fun pin() {
val svgCode = getDiagramCode()
ViewManager.addSvg("Diagram", svgCode)
dialog.close()
}
private fun getDiagramCode(): String {
val logEntry = SessionManager.getEventStore().findByDispatcher(callBack as UUID)
return logEntry.getResponse()
}
@Deprecated("use leaflet/svg")
fun scale(direction: Direction) {
val svgCode = getDiagramCode()
val svg = ScalableVectorGraphic(svgCode)
when (direction) {
Direction.UP -> svg.scaleUp()
Direction.DOWN -> svg.scaleDown()
}
DomUtil.replaceWith(callBack as UUID, svg)
}
private fun buildMenu(): List<KvisionHtmlLink> {
val menu = mutableListOf<KvisionHtmlLink>()
menu.add(buildPinAction())
menu.add(buildDownloadAction())
return menu
}
private fun buildPinAction(): io.kvision.html.Link {
val action = DropDownMenuBuilder.buildActionLink(
label = "Pin",
menuTitle = "Pin")
action.onClick {
pin()
}
return action
}
private fun buildDownloadAction(): io.kvision.html.Link {
val action = DropDownMenuBuilder.buildActionLink(
label = "Download",
menuTitle = "Download")
action.onClick {
download()
}
return action
}
private fun download() {
val svgCode = getDiagramCode()
DownloadDialog(fileName = "diagram.svg", svgCode).open()
dialog.close()
}
}
| incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/ui/dialog/DiagramDialog.kt | 1761383448 |
package com.github.stephenvinouze.advancedrecyclerview.core.adapters
import android.util.SparseBooleanArray
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.github.stephenvinouze.advancedrecyclerview.core.enums.ChoiceMode
import com.github.stephenvinouze.advancedrecyclerview.core.extensions.swap
import com.github.stephenvinouze.advancedrecyclerview.core.views.BaseViewHolder
/**
* Created by Stephen Vinouze on 09/11/2015.
*/
abstract class RecyclerAdapter<MODEL> : RecyclerView.Adapter<BaseViewHolder>() {
val selectedItemViewCount: Int
get() = selectedItemViews.size()
var choiceMode = ChoiceMode.NONE
set(value) {
field = value
clearSelectedItemViews()
}
open var items: MutableList<MODEL> = arrayListOf()
set(value) {
field = value
notifyDataSetChanged()
}
var onClick: ((view: View, position: Int) -> Unit)? = null
var onLongClick: ((view: View, position: Int) -> Boolean)? = null
private val selectedItemViews = SparseBooleanArray()
fun addItems(items: MutableList<MODEL>, position: Int) {
addItemsInternal(items, position)
notifyItemRangeInserted(position, items.size)
}
fun addItem(item: MODEL, position: Int) {
addItemInternal(item, position)
notifyItemInserted(position)
}
fun removeItem(position: Int) {
removeItemInternal(position)
notifyItemRemoved(position)
}
fun moveItem(from: Int, to: Int) {
moveItemInternal(from, to)
notifyItemMoved(from, to)
}
fun clearItems() {
clearItemsInternal()
clearSelectedItemViews()
}
fun isItemViewToggled(position: Int): Boolean = selectedItemViews.get(position, false)
fun getSelectedItemViews(): MutableList<Int> {
val items: MutableList<Int> = arrayListOf()
(0 until selectedItemViews.size()).mapTo(items) { selectedItemViews.keyAt(it) }
return items
}
fun clearSelectedItemViews() {
selectedItemViews.clear()
notifyDataSetChanged()
}
open fun toggleItemView(position: Int) {
when (choiceMode) {
ChoiceMode.NONE -> return
ChoiceMode.SINGLE -> {
getSelectedItemViews().forEach {
selectedItemViews.delete(it)
notifyItemChanged(it)
}
selectedItemViews.put(position, true)
}
ChoiceMode.MULTIPLE -> if (isItemViewToggled(position)) {
selectedItemViews.delete(position)
} else {
selectedItemViews.put(position, true)
}
}
notifyItemChanged(position)
}
protected open fun addItemsInternal(items: MutableList<MODEL>, position: Int) {
this.items.addAll(position, items)
}
protected open fun addItemInternal(item: MODEL, position: Int) {
this.items.add(position, item)
}
protected open fun moveItemInternal(from: Int, to: Int) {
moveSelectedItemView(from, to)
this.items.swap(from, to)
}
protected open fun removeItemInternal(position: Int) {
removeSelectedItemView(position)
this.items.removeAt(position)
}
protected open fun clearItemsInternal() {
this.items.clear()
}
protected open fun handleClick(viewHolder: BaseViewHolder, clickPosition: (BaseViewHolder) -> Int) {
val itemView = viewHolder.view
itemView.setOnClickListener {
toggleItemView(clickPosition(viewHolder))
onClick?.invoke(itemView, clickPosition(viewHolder))
}
onLongClick?.let { listener ->
itemView.setOnLongClickListener { listener(itemView, clickPosition(viewHolder)) }
}
}
private fun moveSelectedItemView(from: Int, to: Int) {
if (isItemViewToggled(from) && !isItemViewToggled(to)) {
selectedItemViews.delete(from)
selectedItemViews.put(to, true)
} else if (!isItemViewToggled(from) && isItemViewToggled(to)) {
selectedItemViews.delete(to)
selectedItemViews.put(from, true)
}
}
private fun removeSelectedItemView(position: Int) {
val selectedPositions = getSelectedItemViews()
if (isItemViewToggled(position)) {
selectedPositions.removeAt(selectedPositions.indexOf(position))
}
selectedItemViews.clear()
for (selectedPosition in selectedPositions) {
selectedItemViews.put(if (position > selectedPosition) selectedPosition else selectedPosition - 1, true)
}
}
override fun getItemCount(): Int = items.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
val itemView = onCreateItemView(parent, viewType)
val viewHolder = BaseViewHolder(itemView)
handleClick(viewHolder) { it.layoutPosition }
return viewHolder
}
override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
onBindItemView(holder.view, position)
}
protected abstract fun onCreateItemView(parent: ViewGroup, viewType: Int): View
protected abstract fun onBindItemView(view: View, position: Int)
}
| core/src/main/kotlin/com/github/stephenvinouze/advancedrecyclerview/core/adapters/RecyclerAdapter.kt | 964336551 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.extractOneToManyParent
import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent
import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class TreeMultiparentLeafEntityImpl(val dataSource: TreeMultiparentLeafEntityData) : TreeMultiparentLeafEntity, WorkspaceEntityBase() {
companion object {
internal val MAINPARENT_CONNECTION_ID: ConnectionId = ConnectionId.create(TreeMultiparentRootEntity::class.java,
TreeMultiparentLeafEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, true)
internal val LEAFPARENT_CONNECTION_ID: ConnectionId = ConnectionId.create(TreeMultiparentLeafEntity::class.java,
TreeMultiparentLeafEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, true)
internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(TreeMultiparentLeafEntity::class.java,
TreeMultiparentLeafEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, true)
val connections = listOf<ConnectionId>(
MAINPARENT_CONNECTION_ID,
LEAFPARENT_CONNECTION_ID,
CHILDREN_CONNECTION_ID,
)
}
override val data: String
get() = dataSource.data
override val mainParent: TreeMultiparentRootEntity?
get() = snapshot.extractOneToManyParent(MAINPARENT_CONNECTION_ID, this)
override val leafParent: TreeMultiparentLeafEntity?
get() = snapshot.extractOneToManyParent(LEAFPARENT_CONNECTION_ID, this)
override val children: List<TreeMultiparentLeafEntity>
get() = snapshot.extractOneToManyChildren<TreeMultiparentLeafEntity>(CHILDREN_CONNECTION_ID, this)!!.toList()
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: TreeMultiparentLeafEntityData?) : ModifiableWorkspaceEntityBase<TreeMultiparentLeafEntity>(), TreeMultiparentLeafEntity.Builder {
constructor() : this(TreeMultiparentLeafEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity TreeMultiparentLeafEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isDataInitialized()) {
error("Field TreeMultiparentLeafEntity#data should be initialized")
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) {
error("Field TreeMultiparentLeafEntity#children should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) {
error("Field TreeMultiparentLeafEntity#children should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as TreeMultiparentLeafEntity
this.entitySource = dataSource.entitySource
this.data = dataSource.data
if (parents != null) {
this.mainParent = parents.filterIsInstance<TreeMultiparentRootEntity>().singleOrNull()
this.leafParent = parents.filterIsInstance<TreeMultiparentLeafEntity>().singleOrNull()
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var data: String
get() = getEntityData().data
set(value) {
checkModificationAllowed()
getEntityData().data = value
changedProperty.add("data")
}
override var mainParent: TreeMultiparentRootEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyParent(MAINPARENT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
MAINPARENT_CONNECTION_ID)] as? TreeMultiparentRootEntity
}
else {
this.entityLinks[EntityLink(false, MAINPARENT_CONNECTION_ID)] as? TreeMultiparentRootEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, MAINPARENT_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, MAINPARENT_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToManyParentOfChild(MAINPARENT_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, MAINPARENT_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, MAINPARENT_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, MAINPARENT_CONNECTION_ID)] = value
}
changedProperty.add("mainParent")
}
override var leafParent: TreeMultiparentLeafEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyParent(LEAFPARENT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
LEAFPARENT_CONNECTION_ID)] as? TreeMultiparentLeafEntity
}
else {
this.entityLinks[EntityLink(false, LEAFPARENT_CONNECTION_ID)] as? TreeMultiparentLeafEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, LEAFPARENT_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, LEAFPARENT_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToManyParentOfChild(LEAFPARENT_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, LEAFPARENT_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, LEAFPARENT_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, LEAFPARENT_CONNECTION_ID)] = value
}
changedProperty.add("leafParent")
}
// List of non-abstract referenced types
var _children: List<TreeMultiparentLeafEntity>? = emptyList()
override var children: List<TreeMultiparentLeafEntity>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<TreeMultiparentLeafEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(
true, CHILDREN_CONNECTION_ID)] as? List<TreeMultiparentLeafEntity> ?: emptyList())
}
else {
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<TreeMultiparentLeafEntity> ?: emptyList()
}
}
set(value) {
// Setter of the list of non-abstract referenced types
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) {
_diff.addEntity(item_value)
}
}
_diff.updateOneToManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*>) {
item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value
}
changedProperty.add("children")
}
override fun getEntityData(): TreeMultiparentLeafEntityData = result ?: super.getEntityData() as TreeMultiparentLeafEntityData
override fun getEntityClass(): Class<TreeMultiparentLeafEntity> = TreeMultiparentLeafEntity::class.java
}
}
class TreeMultiparentLeafEntityData : WorkspaceEntityData<TreeMultiparentLeafEntity>() {
lateinit var data: String
fun isDataInitialized(): Boolean = ::data.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<TreeMultiparentLeafEntity> {
val modifiable = TreeMultiparentLeafEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): TreeMultiparentLeafEntity {
return getCached(snapshot) {
val entity = TreeMultiparentLeafEntityImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return TreeMultiparentLeafEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return TreeMultiparentLeafEntity(data, entitySource) {
this.mainParent = parents.filterIsInstance<TreeMultiparentRootEntity>().singleOrNull()
this.leafParent = parents.filterIsInstance<TreeMultiparentLeafEntity>().singleOrNull()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as TreeMultiparentLeafEntityData
if (this.entitySource != other.entitySource) return false
if (this.data != other.data) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as TreeMultiparentLeafEntityData
if (this.data != other.data) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + data.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + data.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/TreeMultiparentLeafEntityImpl.kt | 4269290113 |
package com.simplemobiletools.gallery.pro.activities
import android.os.Bundle
import com.simplemobiletools.commons.dialogs.FilePickerDialog
import com.simplemobiletools.commons.extensions.beVisibleIf
import com.simplemobiletools.commons.extensions.getProperTextColor
import com.simplemobiletools.commons.helpers.NavigationIcon
import com.simplemobiletools.commons.helpers.ensureBackgroundThread
import com.simplemobiletools.commons.interfaces.RefreshRecyclerViewListener
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.adapters.ManageHiddenFoldersAdapter
import com.simplemobiletools.gallery.pro.extensions.addNoMedia
import com.simplemobiletools.gallery.pro.extensions.config
import com.simplemobiletools.gallery.pro.extensions.getNoMediaFolders
import kotlinx.android.synthetic.main.activity_manage_folders.*
class HiddenFoldersActivity : SimpleActivity(), RefreshRecyclerViewListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_manage_folders)
updateFolders()
setupOptionsMenu()
manage_folders_toolbar.title = getString(R.string.hidden_folders)
}
override fun onResume() {
super.onResume()
setupToolbar(manage_folders_toolbar, NavigationIcon.Arrow)
}
private fun updateFolders() {
getNoMediaFolders {
runOnUiThread {
manage_folders_placeholder.apply {
text = getString(R.string.hidden_folders_placeholder)
beVisibleIf(it.isEmpty())
setTextColor(getProperTextColor())
}
val adapter = ManageHiddenFoldersAdapter(this, it, this, manage_folders_list) {}
manage_folders_list.adapter = adapter
}
}
}
private fun setupOptionsMenu() {
manage_folders_toolbar.setOnMenuItemClickListener { menuItem ->
when (menuItem.itemId) {
R.id.add_folder -> addFolder()
else -> return@setOnMenuItemClickListener false
}
return@setOnMenuItemClickListener true
}
}
override fun refreshItems() {
updateFolders()
}
private fun addFolder() {
FilePickerDialog(this, config.lastFilepickerPath, false, config.shouldShowHidden, false, true) {
config.lastFilepickerPath = it
ensureBackgroundThread {
addNoMedia(it) {
updateFolders()
}
}
}
}
}
| app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/HiddenFoldersActivity.kt | 49085335 |
package com.simplemobiletools.gallery.pro.models
import android.graphics.Bitmap
import com.zomato.photofilters.imageprocessors.Filter
data class FilterItem(var bitmap: Bitmap, val filter: Filter)
| app/src/main/kotlin/com/simplemobiletools/gallery/pro/models/FilterItem.kt | 1990595736 |
import com.intellij.openapi.util.Couple
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.Pair.create
class UseCoupleOfFactoryMethodInVariableWhenPairCreateUsed {
fun any() {
takePair(Couple.of("a", "b"))
}
@Suppress("UNUSED_PARAMETER")
fun <A, B> takePair(pair: Pair<A, B>?) {
// do nothing
}
}
| plugins/devkit/devkit-kotlin-tests/testData/inspections/useCoupleFix/UseCoupleOfFactoryMethodInMethodParameterWhenPairCreateStaticImportUsed_after.kt | 3659323518 |
/*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.internal.connection
import java.io.IOException
import okhttp3.Address
import okhttp3.HttpUrl
/**
* Policy on choosing which connection to use for an exchange and any retries that follow. This uses
* the following strategies:
*
* 1. If the current call already has a connection that can satisfy the request it is used. Using
* the same connection for an initial exchange and its follow-ups may improve locality.
*
* 2. If there is a connection in the pool that can satisfy the request it is used. Note that it is
* possible for shared exchanges to make requests to different host names! See
* [RealConnection.isEligible] for details.
*
* 3. Attempt plans from prior connect attempts for this call. These occur as either follow-ups to
* failed connect attempts (such as trying the next [ConnectionSpec]), or as attempts that lost
* a race in fast follow-up.
*
* 4. If there's no existing connection, make a list of routes (which may require blocking DNS
* lookups) and attempt a new connection them. When failures occur, retries iterate the list of
* available routes.
*
* If the pool gains an eligible connection while DNS, TCP, or TLS work is in flight, this finder
* will prefer pooled connections. Only pooled HTTP/2 connections are used for such de-duplication.
*
* It is possible to cancel the finding process by canceling its call.
*
* Implementations of this interface are not thread-safe. Each instance is thread-confined to the
* thread executing the call.
*/
interface RoutePlanner {
val address: Address
/** Follow-ups for failed plans and plans that lost a race. */
val deferredPlans: ArrayDeque<Plan>
fun isCanceled(): Boolean
/** Returns a plan to attempt. */
@Throws(IOException::class)
fun plan(): Plan
/**
* Returns true if there's more route plans to try.
*
* @param failedConnection an optional connection that was resulted in a failure. If the failure
* is recoverable, the connection's route may be recovered for the retry.
*/
fun hasNext(failedConnection: RealConnection? = null): Boolean
/**
* Returns true if the host and port are unchanged from when this was created. This is used to
* detect if followups need to do a full connection-finding process including DNS resolution, and
* certificate pin checks.
*/
fun sameHostAndPort(url: HttpUrl): Boolean
/**
* A plan holds either an immediately-usable connection, or one that must be connected first.
* These steps are split so callers can call [connectTcp] on a background thread if attempting
* multiple plans concurrently.
*/
interface Plan {
val isReady: Boolean
fun connectTcp(): ConnectResult
fun connectTlsEtc(): ConnectResult
fun handleSuccess(): RealConnection
fun cancel()
/**
* Returns a plan to attempt if canceling this plan was a mistake! The returned plan is not
* canceled, even if this plan is canceled.
*/
fun retry(): Plan?
}
/**
* What to do once a plan has executed.
*
* If [nextPlan] is not-null, another attempt should be made by following it. If [throwable] is
* non-null, it should be reported to the user should all further attempts fail.
*
* The two values are independent: results can contain both (recoverable error), neither
* (success), just an exception (permanent failure), or just a plan (non-exceptional retry).
*/
data class ConnectResult(
val plan: Plan,
val nextPlan: Plan? = null,
val throwable: Throwable? = null,
) {
val isSuccess: Boolean
get() = nextPlan == null && throwable == null
}
}
| okhttp/src/jvmMain/kotlin/okhttp3/internal/connection/RoutePlanner.kt | 2581406231 |
package rhmodding.bread.model.bccad
import com.badlogic.gdx.graphics.Color
import rhmodding.bread.model.IDataModel
import java.nio.ByteBuffer
import java.nio.ByteOrder
class BCCAD : IDataModel {
companion object {
fun read(bytes: ByteBuffer): BCCAD {
bytes.order(ByteOrder.LITTLE_ENDIAN)
return BCCAD().apply {
timestamp = bytes.int
sheetW = bytes.short.toUShort()
sheetH = bytes.short.toUShort()
repeat(bytes.int) {
sprites += Sprite().apply {
repeat(bytes.int) {
parts += SpritePart().apply {
regionX = bytes.short.toUShort()
regionY = bytes.short.toUShort()
regionW = bytes.short.toUShort()
regionH = bytes.short.toUShort()
posX = bytes.short
posY = bytes.short
stretchX = bytes.float
stretchY = bytes.float
rotation = bytes.float
flipX = bytes.get() != 0.toByte()
flipY = bytes.get() != 0.toByte()
multColor = Color((bytes.get().toInt() and 0xFF) / 255f, (bytes.get().toInt() and 0xFF) / 255f, (bytes.get().toInt() and 0xFF) / 255f, 1f)
screenColor = Color((bytes.get().toInt() and 0xFF) / 255f, (bytes.get().toInt() and 0xFF) / 255f, (bytes.get().toInt() and 0xFF) / 255f,1f)
opacity = bytes.get().toUByte()
repeat(12) {
unknownData[it] = bytes.get()
}
designation = bytes.get().toUByte()
unknown = bytes.short
tlDepth = bytes.float
blDepth = bytes.float
trDepth = bytes.float
brDepth = bytes.float
}
}
}
}
repeat(bytes.int) {
var s = ""
val n = bytes.get().toInt()
repeat(n) {
s += bytes.get().toChar()
}
repeat(4 - ((n + 1) % 4)) {
bytes.get()
}
animations += Animation().apply {
name = s
interpolationInt = bytes.int
repeat(bytes.int) {
steps.add(AnimationStep().apply {
spriteIndex = bytes.short.toUShort()
delay = bytes.short.toUShort()
translateX = bytes.short
translateY = bytes.short
depth = bytes.float
stretchX = bytes.float
stretchY = bytes.float
rotation = bytes.float
color = Color((bytes.get().toInt() and 0xFF) / 255f, (bytes.get().toInt() and 0xFF) / 255f, (bytes.get().toInt() and 0xFF) / 255f, 1f)
bytes.get()
unknown1 = bytes.get()
unknown2 = bytes.get()
opacity = (bytes.short.toInt() and 0xFF).toUByte()
})
}
}
}
bytes.get()
}
}
}
var timestamp: Int = 0
override var sheetW: UShort = 1u
override var sheetH: UShort = 1u
override val sprites: MutableList<Sprite> = mutableListOf()
override val animations: MutableList<Animation> = mutableListOf()
fun toBytes(): ByteBuffer {
// Compute size of buffer
// Header: 8 bytes
// Num sprites: 4 bytes
// For each sprite: 4 bytes
// For each sprite part: 64 bytes
// Num animations: 4 bytes
// For each animation: 1 + (1*name.length in bytes, padded to nearest four bytes) + 16
// For each animation step: 32 bytes
// One end byte
val bytes = ByteBuffer.allocate(8 + 4 +
(4 * sprites.size + (64 * sprites.sumBy { it.parts.size }) +
4 + (animations.sumBy { 1 + it.name.length + (4 - ((it.name.length + 1) % 4)) + 8 } +
animations.sumBy { 32 * it.steps.size })) + 1)
.order(ByteOrder.LITTLE_ENDIAN)
bytes.putInt(timestamp)
.putShort(sheetW.toShort())
.putShort(sheetH.toShort())
.putInt(sprites.size)
sprites.forEach { sprite ->
bytes.putInt(sprite.parts.size)
sprite.parts.forEach { p ->
with(p) {
bytes.putShort(regionX.toShort())
.putShort(regionY.toShort())
.putShort(regionW.toShort())
.putShort(regionH.toShort())
.putShort(posX)
.putShort(posY)
.putFloat(stretchX)
.putFloat(stretchY)
.putFloat(rotation)
.put((if (flipX) 1 else 0).toByte())
.put((if (flipY) 1 else 0).toByte())
.put((multColor.r * 255).toByte())
.put((multColor.g * 255).toByte())
.put((multColor.b * 255).toByte())
.put((screenColor.r * 255).toByte())
.put((screenColor.g * 255).toByte())
.put((screenColor.b * 255).toByte())
.put(opacity.toByte())
repeat(12) {
bytes.put(unknownData[it])
}
bytes.put(designation.toByte())
.putShort(unknown)
.putFloat(tlDepth)
.putFloat(blDepth)
.putFloat(trDepth)
.putFloat(brDepth)
}
}
}
bytes.putInt(animations.size)
animations.forEach { a ->
with(a) {
bytes.put(name.length.toByte())
name.toCharArray().forEach { b -> bytes.put(b.toByte()) }
repeat(4 - ((name.length + 1) % 4)) { bytes.put(0.toByte()) }
bytes.putInt(interpolationInt)
.putInt(steps.size)
steps.forEach { s ->
with(s) {
bytes.putShort(spriteIndex.toShort())
.putShort(delay.toShort())
.putShort(translateX)
.putShort(translateY)
.putFloat(depth)
.putFloat(stretchX)
.putFloat(stretchY)
.putFloat(rotation)
.put((color.r * 255).toByte())
.put((color.g * 255).toByte())
.put((color.b * 255).toByte())
.put(0.toByte())
.put(unknown1)
.put(unknown2)
.putShort(opacity.toShort())
}
}
}
}
bytes.put(0.toByte())
return bytes
}
override fun toString(): String {
return """BCCAD=[
| timestamp=$timestamp, width=$sheetW, height=$sheetH,
| numSprites=${sprites.size},
| sprites=[${sprites.joinToString(separator = "\n")}],
| numAnimations=${animations.size},
| animations=[${animations.joinToString(separator = "\n")}]
|]""".trimMargin()
}
} | core/src/main/kotlin/rhmodding/bread/model/bccad/BCCAD.kt | 2369250247 |
package org.stepik.android.data.course_revenue.repository
import io.reactivex.Single
import org.stepik.android.data.course_revenue.source.CourseBenefitByMonthsRemoteDataSource
import org.stepik.android.domain.course_revenue.model.CourseBenefitByMonth
import org.stepik.android.domain.course_revenue.repository.CourseBenefitByMonthsRepository
import ru.nobird.app.core.model.PagedList
import javax.inject.Inject
class CourseBenefitByMonthsRepositoryImpl
@Inject
constructor(
private val courseBenefitByMonthsRemoteDataSource: CourseBenefitByMonthsRemoteDataSource
) : CourseBenefitByMonthsRepository {
override fun getCourseBenefitByMonths(courseId: Long, page: Int): Single<PagedList<CourseBenefitByMonth>> =
courseBenefitByMonthsRemoteDataSource.getCourseBenefitByMonths(courseId)
} | app/src/main/java/org/stepik/android/data/course_revenue/repository/CourseBenefitByMonthsRepositoryImpl.kt | 2976937145 |
package org.stepik.android.view.injection.auth
import dagger.Subcomponent
import org.stepik.android.view.auth.ui.activity.SocialAuthActivity
import org.stepik.android.view.auth.ui.activity.CredentialAuthActivity
import org.stepik.android.view.auth.ui.activity.RegistrationActivity
import org.stepik.android.view.injection.user.UserDataModule
import org.stepik.android.view.injection.user_profile.UserProfileDataModule
import org.stepik.android.view.injection.wishlist.WishlistDataModule
@Subcomponent(
modules = [
AuthModule::class,
UserDataModule::class,
UserProfileDataModule::class,
WishlistDataModule::class
]
)
interface AuthComponent {
@Subcomponent.Builder
interface Builder {
fun build(): AuthComponent
}
fun inject(credentialAuthActivity: CredentialAuthActivity)
fun inject(registerActivity: SocialAuthActivity)
fun inject(registrationActivity: RegistrationActivity)
} | app/src/main/java/org/stepik/android/view/injection/auth/AuthComponent.kt | 2115741864 |
package org.stepik.android.view.injection.user_activity
import dagger.Binds
import dagger.Module
import dagger.Provides
import org.stepik.android.data.user_activity.repository.UserActivityRepositoryImpl
import org.stepik.android.data.user_activity.source.UserActivityRemoteDataSource
import org.stepik.android.domain.user_activity.repository.UserActivityRepository
import org.stepik.android.remote.user_activity.UserActivityRemoteDataSourceImpl
import org.stepik.android.remote.user_activity.service.UserActivityService
import org.stepik.android.view.injection.base.Authorized
import retrofit2.Retrofit
@Module
abstract class UserActivityDataModule {
@Binds
internal abstract fun bindUserActivityRepository(
userActivityRepositoryImpl: UserActivityRepositoryImpl
): UserActivityRepository
@Binds
internal abstract fun bindUserActivityRemoteDataSource(
userActivityRemoteDataSourceImpl: UserActivityRemoteDataSourceImpl
): UserActivityRemoteDataSource
@Module
companion object {
@Provides
@JvmStatic
internal fun provideUserActivityService(@Authorized retrofit: Retrofit): UserActivityService =
retrofit.create(UserActivityService::class.java)
}
} | app/src/main/java/org/stepik/android/view/injection/user_activity/UserActivityDataModule.kt | 766864620 |
import kotlin.test.Ignore
import kotlin.test.Test
import kotlin.test.assertEquals
import YachtCategory.*
class YachtTest {
@Test
fun yacht() = assertEquals(50, Yacht.solve(YACHT, 5, 5, 5, 5, 5))
@Ignore
@Test
fun `not yacht`() = assertEquals(0, Yacht.solve(YACHT, 1, 3, 3, 2, 5))
@Ignore
@Test
fun ones() = assertEquals(3, Yacht.solve(ONES, 1, 1, 1, 3, 5))
@Ignore
@Test
fun `ones out of order`() = assertEquals(3, Yacht.solve(ONES, 3, 1, 1, 5, 1))
@Ignore
@Test
fun `no ones`() = assertEquals(0, Yacht.solve(ONES, 4, 3, 6, 5, 5))
@Ignore
@Test
fun twos() = assertEquals(2, Yacht.solve(TWOS, 2, 3, 4, 5, 6))
@Ignore
@Test
fun fours() = assertEquals(8, Yacht.solve(FOURS, 1, 4, 1, 4, 1))
@Ignore
@Test
fun `yacht counted as threes`() = assertEquals(15, Yacht.solve(THREES, 3, 3, 3, 3, 3))
@Ignore
@Test
fun `yacht of threes counted as fives`() = assertEquals(0, Yacht.solve(FIVES, 3, 3, 3, 3, 3))
@Ignore
@Test
fun sixes() = assertEquals(6, Yacht.solve(SIXES, 2, 3, 4, 5, 6))
@Ignore
@Test
fun `full house two small three big`() = assertEquals(16, Yacht.solve(FULL_HOUSE, 2, 2, 4, 4, 4))
@Ignore
@Test
fun `full house three small two big`() = assertEquals(19, Yacht.solve(FULL_HOUSE, 5, 3, 3, 5, 3))
@Ignore
@Test
fun `two pair is not a full house`() = assertEquals(0, Yacht.solve(FULL_HOUSE, 2, 2, 4, 4, 5))
@Ignore
@Test
fun `four of a kind is not a full house`() = assertEquals(0, Yacht.solve(FULL_HOUSE, 1, 4, 4, 4, 4))
@Ignore
@Test
fun `yacht is not a full house`() = assertEquals(0, Yacht.solve(FULL_HOUSE, 2, 2, 2, 2, 2))
@Ignore
@Test
fun `four of a kind`() = assertEquals(24, Yacht.solve(FOUR_OF_A_KIND, 6, 6, 4, 6, 6))
@Ignore
@Test
fun `yacht can be scored as four of a kind`() = assertEquals(12, Yacht.solve(FOUR_OF_A_KIND, 3, 3, 3, 3, 3))
@Ignore
@Test
fun `full house is not four of a kind`() = assertEquals(0, Yacht.solve(FOUR_OF_A_KIND, 3, 3, 3, 5, 5))
@Ignore
@Test
fun `little straight`() = assertEquals(30, Yacht.solve(LITTLE_STRAIGHT, 3, 5, 4, 1, 2))
@Ignore
@Test
fun `little straight as big straight`() = assertEquals(0, Yacht.solve(BIG_STRAIGHT, 1, 2, 3, 4, 5))
@Ignore
@Test
fun `four in order but not a little straight`() = assertEquals(0, Yacht.solve(LITTLE_STRAIGHT, 1, 1, 2, 3, 4))
@Ignore
@Test
fun `no pairs but not a little straight`() = assertEquals(0, Yacht.solve(LITTLE_STRAIGHT, 1, 2, 3, 4, 6))
@Ignore
@Test
fun `minimum is 1 maximum is 5 but not a little straight`() =
assertEquals(0, Yacht.solve(LITTLE_STRAIGHT, 1, 1, 3, 4, 5))
@Ignore
@Test
fun `big straight`() = assertEquals(30, Yacht.solve(BIG_STRAIGHT, 4, 6, 2, 5, 3))
@Ignore
@Test
fun `big straight as little straight`() = assertEquals(0, Yacht.solve(LITTLE_STRAIGHT, 6, 5, 4, 3, 2))
@Ignore
@Test
fun `no pairs but not a big straight`() = assertEquals(0, Yacht.solve(BIG_STRAIGHT, 6, 5, 4, 3, 1))
@Ignore
@Test
fun choice() = assertEquals(23, Yacht.solve(CHOICE, 3, 3, 5, 6, 6))
@Ignore
@Test
fun `yacht as choice`() = assertEquals(10, Yacht.solve(CHOICE, 2, 2, 2, 2, 2))
}
| exercises/practice/yacht/src/test/kotlin/YachtTest.kt | 2183704691 |
package com.nononsenseapps.feeder.db.room
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Ignore
import androidx.room.Index
import androidx.room.PrimaryKey
import com.nononsenseapps.feeder.db.COL_ID
import java.net.URL
@Entity(
tableName = "read_status_synced",
indices = [
Index(value = ["feed_item", "sync_remote"], unique = true),
Index(value = ["feed_item"]),
Index(value = ["sync_remote"]),
],
foreignKeys = [
ForeignKey(
entity = FeedItem::class,
parentColumns = [COL_ID],
childColumns = ["feed_item"],
onDelete = ForeignKey.CASCADE
),
ForeignKey(
entity = SyncRemote::class,
parentColumns = [COL_ID],
childColumns = ["sync_remote"],
onDelete = ForeignKey.CASCADE
)
]
)
data class ReadStatusSynced @Ignore constructor(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = COL_ID) var id: Long = ID_UNSET,
@ColumnInfo(name = "sync_remote") var sync_remote: Long = ID_UNSET,
@ColumnInfo(name = "feed_item") var feed_item: Long = ID_UNSET
) {
constructor() : this(id = ID_UNSET)
}
interface ReadStatusFeedItem {
val id: Long
val feedId: Long
val guid: String
val feedUrl: URL
}
| app/src/main/java/com/nononsenseapps/feeder/db/room/ReadStatusSynced.kt | 1210386259 |
// 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.refactoring.rename.impl
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.refactoring.rename.Renamer
import com.intellij.refactoring.rename.api.RenameTarget
import com.intellij.refactoring.rename.inplace.inplaceRename
class RenameTargetRenamer(
private val project: Project,
private val editor: Editor?,
private val target: RenameTarget
) : Renamer {
override fun getPresentableText(): String = target.presentation.presentableText
override fun performRename() {
if (editor != null &&
editor.settings.isVariableInplaceRenameEnabled &&
inplaceRename(project, editor, target)) {
return
}
showDialogAndRename(project, target)
}
}
| platform/lang-impl/src/com/intellij/refactoring/rename/impl/RenameTargetRenamer.kt | 4112942750 |
/*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okio
import okio.internal.commonClose
import okio.internal.commonExhausted
import okio.internal.commonIndexOf
import okio.internal.commonIndexOfElement
import okio.internal.commonPeek
import okio.internal.commonRangeEquals
import okio.internal.commonRead
import okio.internal.commonReadAll
import okio.internal.commonReadByte
import okio.internal.commonReadByteArray
import okio.internal.commonReadByteString
import okio.internal.commonReadDecimalLong
import okio.internal.commonReadFully
import okio.internal.commonReadHexadecimalUnsignedLong
import okio.internal.commonReadInt
import okio.internal.commonReadIntLe
import okio.internal.commonReadLong
import okio.internal.commonReadLongLe
import okio.internal.commonReadShort
import okio.internal.commonReadShortLe
import okio.internal.commonReadUtf8
import okio.internal.commonReadUtf8CodePoint
import okio.internal.commonReadUtf8Line
import okio.internal.commonReadUtf8LineStrict
import okio.internal.commonRequest
import okio.internal.commonRequire
import okio.internal.commonSelect
import okio.internal.commonSkip
import okio.internal.commonTimeout
import okio.internal.commonToString
internal actual class RealBufferedSource actual constructor(
actual val source: Source
) : BufferedSource {
actual var closed: Boolean = false
override val buffer: Buffer = Buffer()
override fun read(sink: Buffer, byteCount: Long): Long = commonRead(sink, byteCount)
override fun exhausted(): Boolean = commonExhausted()
override fun require(byteCount: Long): Unit = commonRequire(byteCount)
override fun request(byteCount: Long): Boolean = commonRequest(byteCount)
override fun readByte(): Byte = commonReadByte()
override fun readByteString(): ByteString = commonReadByteString()
override fun readByteString(byteCount: Long): ByteString = commonReadByteString(byteCount)
override fun select(options: Options): Int = commonSelect(options)
override fun readByteArray(): ByteArray = commonReadByteArray()
override fun readByteArray(byteCount: Long): ByteArray = commonReadByteArray(byteCount)
override fun read(sink: ByteArray): Int = read(sink, 0, sink.size)
override fun readFully(sink: ByteArray): Unit = commonReadFully(sink)
override fun read(sink: ByteArray, offset: Int, byteCount: Int): Int =
commonRead(sink, offset, byteCount)
override fun readFully(sink: Buffer, byteCount: Long): Unit = commonReadFully(sink, byteCount)
override fun readAll(sink: Sink): Long = commonReadAll(sink)
override fun readUtf8(): String = commonReadUtf8()
override fun readUtf8(byteCount: Long): String = commonReadUtf8(byteCount)
override fun readUtf8Line(): String? = commonReadUtf8Line()
override fun readUtf8LineStrict() = readUtf8LineStrict(Long.MAX_VALUE)
override fun readUtf8LineStrict(limit: Long): String = commonReadUtf8LineStrict(limit)
override fun readUtf8CodePoint(): Int = commonReadUtf8CodePoint()
override fun readShort(): Short = commonReadShort()
override fun readShortLe(): Short = commonReadShortLe()
override fun readInt(): Int = commonReadInt()
override fun readIntLe(): Int = commonReadIntLe()
override fun readLong(): Long = commonReadLong()
override fun readLongLe(): Long = commonReadLongLe()
override fun readDecimalLong(): Long = commonReadDecimalLong()
override fun readHexadecimalUnsignedLong(): Long = commonReadHexadecimalUnsignedLong()
override fun skip(byteCount: Long): Unit = commonSkip(byteCount)
override fun indexOf(b: Byte): Long = indexOf(b, 0L, Long.MAX_VALUE)
override fun indexOf(b: Byte, fromIndex: Long): Long = indexOf(b, fromIndex, Long.MAX_VALUE)
override fun indexOf(b: Byte, fromIndex: Long, toIndex: Long): Long =
commonIndexOf(b, fromIndex, toIndex)
override fun indexOf(bytes: ByteString): Long = indexOf(bytes, 0L)
override fun indexOf(bytes: ByteString, fromIndex: Long): Long = commonIndexOf(bytes, fromIndex)
override fun indexOfElement(targetBytes: ByteString): Long = indexOfElement(targetBytes, 0L)
override fun indexOfElement(targetBytes: ByteString, fromIndex: Long): Long =
commonIndexOfElement(targetBytes, fromIndex)
override fun rangeEquals(offset: Long, bytes: ByteString) = rangeEquals(
offset, bytes, 0,
bytes.size
)
override fun rangeEquals(
offset: Long,
bytes: ByteString,
bytesOffset: Int,
byteCount: Int
): Boolean = commonRangeEquals(offset, bytes, bytesOffset, byteCount)
override fun peek(): BufferedSource = commonPeek()
override fun close(): Unit = commonClose()
override fun timeout(): Timeout = commonTimeout()
override fun toString(): String = commonToString()
}
| okio/src/nonJvmMain/kotlin/okio/RealBufferedSource.kt | 2725454908 |
/*
* Copyright (c) 2016. Manuel Rebollo Báez
*
* 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.mrebollob.m2p.presentation.di.modules
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import com.mrebollob.m2p.BuildConfig
import com.mrebollob.m2p.data.datasources.db.DbDataSourceImp
import com.mrebollob.m2p.domain.datasources.DbDataSource
import com.mrebollob.m2p.presentation.di.qualifiers.SharedPreferencesName
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
class DbModule {
@Provides
@Singleton
fun provideDbDataSource(dbDataSource: DbDataSourceImp): DbDataSource {
return dbDataSource
}
@Provides
@Singleton
fun provideSharedPreferences(application: Application, @SharedPreferencesName sharedPreferencesName: String)
: SharedPreferences {
return application.getSharedPreferences(sharedPreferencesName, Context.MODE_PRIVATE)
}
@Provides
@Singleton
@SharedPreferencesName
fun provideSharedPreferencesName(): String {
return "M2P" + if (BuildConfig.DEBUG) "-dev" else ""
}
} | app/src/main/java/com/mrebollob/m2p/presentation/di/modules/DbModule.kt | 302990228 |
package com.aemtools.completion.html.provider
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionProvider
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.completion.XmlAttributeInsertHandler
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.util.ProcessingContext
/**
* @author Dmytro Troynikov
*/
object HtmlHrefLinkCheckerCompletionProvider : CompletionProvider<CompletionParameters>() {
override fun addCompletions(
parameters: CompletionParameters,
context: ProcessingContext,
result: CompletionResultSet) {
if (result.isStopped) {
return
}
result.addElement(LookupElementBuilder.create("x-cq-linkchecker")
.withInsertHandler(XmlAttributeInsertHandler())
)
}
}
| aem-intellij-core/src/main/kotlin/com/aemtools/completion/html/provider/HtmlHrefLinkCheckerCompletionProvider.kt | 2724178307 |
/*
* Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("unused")
package kotlinx.coroutines.lincheck
import kotlinx.coroutines.*
import kotlinx.coroutines.internal.*
import org.jetbrains.kotlinx.lincheck.annotations.*
import org.jetbrains.kotlinx.lincheck.annotations.Operation
import org.jetbrains.kotlinx.lincheck.paramgen.*
import org.jetbrains.kotlinx.lincheck.strategy.managed.modelchecking.*
@Param(name = "value", gen = IntGen::class, conf = "1:5")
class LockFreeListLincheckTest : AbstractLincheckTest() {
class Node(val value: Int): LockFreeLinkedListNode()
private val q: LockFreeLinkedListHead = LockFreeLinkedListHead()
@Operation
fun addLast(@Param(name = "value") value: Int) {
q.addLast(Node(value))
}
@Operation
fun addLastIfNotSame(@Param(name = "value") value: Int) {
q.addLastIfPrev(Node(value)) { !it.isSame(value) }
}
@Operation
fun removeFirst(): Int? {
val node = q.removeFirstOrNull() ?: return null
return (node as Node).value
}
@Operation
fun removeFirstOrPeekIfNotSame(@Param(name = "value") value: Int): Int? {
val node = q.removeFirstIfIsInstanceOfOrPeekIf<Node> { !it.isSame(value) } ?: return null
return node.value
}
private fun Any.isSame(value: Int) = this is Node && this.value == value
override fun extractState(): Any {
val elements = ArrayList<Int>()
q.forEach<Node> { elements.add(it.value) }
return elements
}
override fun ModelCheckingOptions.customize(isStressTest: Boolean) =
checkObstructionFreedom()
} | kotlinx-coroutines-core/jvm/test/lincheck/LockFreeListLincheckTest.kt | 2576348610 |
/*
* Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.rx3
import io.reactivex.rxjava3.core.*
import io.reactivex.rxjava3.plugins.*
fun <T> checkSingleValue(
observable: Observable<T>,
checker: (T) -> Unit
) {
val singleValue = observable.blockingSingle()
checker(singleValue)
}
fun checkErroneous(
observable: Observable<*>,
checker: (Throwable) -> Unit
) {
val singleNotification = observable.materialize().blockingSingle()
val error = singleNotification.error ?: error("Excepted error")
checker(error)
}
fun <T> checkSingleValue(
single: Single<T>,
checker: (T) -> Unit
) {
val singleValue = single.blockingGet()
checker(singleValue)
}
fun checkErroneous(
single: Single<*>,
checker: (Throwable) -> Unit
) {
try {
single.blockingGet()
error("Should have failed")
} catch (e: Throwable) {
checker(e)
}
}
fun <T> checkMaybeValue(
maybe: Maybe<T>,
checker: (T?) -> Unit
) {
val maybeValue = maybe.toFlowable().blockingIterable().firstOrNull()
checker(maybeValue)
}
@Suppress("UNCHECKED_CAST")
fun checkErroneous(
maybe: Maybe<*>,
checker: (Throwable) -> Unit
) {
try {
(maybe as Maybe<Any>).blockingGet()
error("Should have failed")
} catch (e: Throwable) {
checker(e)
}
}
inline fun withExceptionHandler(noinline handler: (Throwable) -> Unit, block: () -> Unit) {
val original = RxJavaPlugins.getErrorHandler()
RxJavaPlugins.setErrorHandler { handler(it) }
try {
block()
} finally {
RxJavaPlugins.setErrorHandler(original)
}
}
| reactive/kotlinx-coroutines-rx3/test/Check.kt | 2783858533 |
package com.yeungeek.avsample.activities.opengl.book.programs
import android.content.Context
import android.opengl.GLES20
import com.yeungeek.avsample.activities.opengl.book.helper.ShaderHelper
import com.yeungeek.avsample.activities.opengl.book.helper.ShaderResReader
abstract class ShaderProgram {
// Uniform constants
protected val U_MATRIX = "u_Matrix"
protected val U_TEXTURE_UNIT = "u_TextureUnit"
// Attribute constants
protected val A_POSITION = "a_Position"
protected val A_COLOR = "a_Color"
protected val A_TEXTURE_COORDINATES = "a_TextureCoordinates"
protected val program: Int
constructor(
context: Context,
vertexShaderFile: String,
fragmentShaderFile: String
) {
val vertexShaderSource = ShaderResReader.loadFromAssetsFile(
vertexShaderFile,
context.resources
)
val fragmentShaderSource = ShaderResReader.loadFromAssetsFile(
fragmentShaderFile,
context.resources
)
program = ShaderHelper.buildProgram(vertexShaderSource, fragmentShaderSource)
}
fun useProgram() {
GLES20.glUseProgram(program)
}
} | AVSample/app/src/main/java/com/yeungeek/avsample/activities/opengl/book/programs/ShaderProgram.kt | 3612685757 |
// 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.intellij.ide.IdeBundle
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.projectImport.ProjectAttachProcessor
import com.intellij.ui.IdeUICustomization
class CloseProjectAction : CloseProjectsActionBase() {
init {
@Suppress("DialogTitleCapitalization")
templatePresentation.setText { IdeUICustomization.getInstance().projectMessage("action.close.project.text") }
templatePresentation.setDescription { IdeUICustomization.getInstance().projectMessage("action.close.project.description") }
}
override fun canClose(project: Project, currentProject: Project) = project === currentProject
override fun shouldShow(e: AnActionEvent) = e.project != null
override fun update(e: AnActionEvent) {
super.update(e)
if (ProjectAttachProcessor.canAttachToProject() && e.project != null && ModuleManager.getInstance(e.project!!).modules.size > 1) {
e.presentation.setText(IdeBundle.messagePointer("action.close.projects.in.current.window"))
}
else {
@Suppress("DialogTitleCapitalization")
e.presentation.text = IdeUICustomization.getInstance().projectMessage("action.close.project.text")
e.presentation.description = IdeUICustomization.getInstance().projectMessage("action.close.project.description")
}
}
} | platform/platform-impl/src/com/intellij/ide/actions/CloseProjectAction.kt | 436074557 |
package com.github.triplet.gradle.play.tasks.internal
import com.github.triplet.gradle.androidpublisher.ReleaseStatus
import com.github.triplet.gradle.androidpublisher.ResolutionStrategy
import com.github.triplet.gradle.common.utils.orNull
import com.github.triplet.gradle.play.PlayPublisherExtension
import org.gradle.api.file.Directory
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.options.Option
import org.gradle.api.tasks.options.OptionValues
import java.util.concurrent.atomic.AtomicBoolean
internal interface ArtifactExtensionOptions {
@get:Internal
@set:Option(
option = "artifact-dir",
description = "Set the prebuilt artifact (APKs/App Bundles) directory"
)
var artifactDirOption: String
}
internal interface WriteTrackExtensionOptions {
@get:Internal
@set:Option(
option = "no-commit",
description = "Don't commit changes from this build."
)
var noCommitOption: Boolean
}
internal interface TrackExtensionOptions : WriteTrackExtensionOptions {
@get:Internal
@set:Option(
option = "user-fraction",
description = "Set the user fraction intended to receive an 'inProgress' release. " +
"Ex: 0.1 == 10%"
)
var userFractionOption: String
@get:Internal
@set:Option(
option = "update-priority",
description = "Set the update priority for your release."
)
var updatePriorityOption: String
@get:OptionValues("release-status")
val releaseStatusOptions: List<String>
@get:Internal
@set:Option(
option = "release-status",
description = "Set the app release status."
)
var releaseStatusOption: ReleaseStatus
@get:Internal
@set:Option(
option = "release-name",
description = "Set the Play Console developer facing release name."
)
var releaseName: String
}
internal interface UpdatableTrackExtensionOptions : TrackExtensionOptions {
@get:Internal
@set:Option(
option = "from-track",
description = "Set the track from which to promote a release."
)
var fromTrackOption: String
@get:Internal
@set:Option(
option = "promote-track",
description = "Set the track to promote a release to."
)
var promoteTrackOption: String
@get:Internal
@set:Option(
option = "update",
description = "Set the track to update when promoting releases. This is the same as " +
"using 'from-track' and 'track' with the same value."
)
var updateTrackOption: String
}
internal interface PublishableTrackExtensionOptions : TrackExtensionOptions,
ArtifactExtensionOptions {
@get:Internal
@set:Option(
option = "track",
description = "Set the track in which to upload your app."
)
var trackOption: String
@get:OptionValues("resolution-strategy")
val resolutionStrategyOptions: List<String>
@get:Internal
@set:Option(
option = "resolution-strategy",
description = "Set the version conflict resolution strategy."
)
var resolutionStrategyOption: ResolutionStrategy
}
internal interface GlobalPublishableArtifactExtensionOptions : PublishableTrackExtensionOptions {
@get:Internal
@set:Option(
option = "default-to-app-bundles",
description = "Prioritize App Bundles over APKs where applicable."
)
var defaultToAppBundlesOption: Boolean
}
internal class CliOptionsImpl(
private val extension: PlayPublisherExtension,
private val executionDir: Directory,
) : ArtifactExtensionOptions, WriteTrackExtensionOptions, TrackExtensionOptions,
UpdatableTrackExtensionOptions, PublishableTrackExtensionOptions,
GlobalPublishableArtifactExtensionOptions {
override var artifactDirOption: String
get() = throw UnsupportedOperationException()
set(value) {
val dir = executionDir.file(value).asFile
val f = requireNotNull(dir.orNull()) {
"Folder '$dir' does not exist."
}
extension.artifactDir.set(f)
}
override var noCommitOption: Boolean
get() = throw UnsupportedOperationException()
set(value) {
extension.commit.set(!value)
}
override var userFractionOption: String
get() = throw UnsupportedOperationException()
set(value) {
extension.userFraction.set(value.toDouble())
}
override var updatePriorityOption: String
get() = throw UnsupportedOperationException()
set(value) {
extension.updatePriority.set(value.toInt())
}
override val releaseStatusOptions: List<String>
get() = ReleaseStatus.values().map { it.publishedName }
override var releaseStatusOption: ReleaseStatus
get() = throw UnsupportedOperationException()
set(value) {
extension.releaseStatus.set(value)
}
override var releaseName: String
get() = throw UnsupportedOperationException()
set(value) {
extension.releaseName.set(value)
}
override var fromTrackOption: String
get() = throw UnsupportedOperationException()
set(value) {
extension.fromTrack.set(value)
}
override var promoteTrackOption: String
get() = throw UnsupportedOperationException()
set(value) {
extension.promoteTrack.set(value)
}
override var updateTrackOption: String
get() = throw UnsupportedOperationException()
set(value) {
fromTrackOption = value
promoteTrackOption = value
}
override var trackOption: String
get() = throw UnsupportedOperationException()
set(value) {
extension.track.set(value)
}
override val resolutionStrategyOptions: List<String>
get() = ResolutionStrategy.values().map { it.publishedName }
override var resolutionStrategyOption: ResolutionStrategy
get() = throw UnsupportedOperationException()
set(value) {
extension.resolutionStrategy.set(value)
}
override var defaultToAppBundlesOption: Boolean
get() = throw UnsupportedOperationException()
set(value) {
extension.defaultToAppBundles.set(value)
}
}
internal interface BootstrapOptions {
@get:Internal
@set:Option(
option = "app-details",
description = "Download app details such as your contact email."
)
var downloadAppDetails: Boolean
@get:Internal
@set:Option(
option = "listings",
description = "Download listings for each language such as your app title and graphics."
)
var downloadListings: Boolean
@get:Internal
@set:Option(option = "release-notes", description = "Download release notes for each language.")
var downloadReleaseNotes: Boolean
@get:Internal
@set:Option(option = "products", description = "Download in-app purchases and subscriptions.")
var downloadProducts: Boolean
class Holder : BootstrapOptions {
private val isRequestingSpecificFeature = AtomicBoolean()
override var downloadAppDetails = true
set(value) {
onSet()
field = value
}
override var downloadListings = true
set(value) {
onSet()
field = value
}
override var downloadReleaseNotes = true
set(value) {
onSet()
field = value
}
override var downloadProducts = true
set(value) {
onSet()
field = value
}
/**
* By default, we download all features. However, if they are specified with CLI options, we
* only download those features.
*
* Note: this method must be called before updating the field since it may overwrite them.
*/
private fun onSet() {
if (isRequestingSpecificFeature.compareAndSet(false, true)) {
downloadAppDetails = false
downloadListings = false
downloadReleaseNotes = false
downloadProducts = false
}
}
}
}
| play/plugin/src/main/kotlin/com/github/triplet/gradle/play/tasks/internal/CliOptions.kt | 1499194162 |
package com.alibaba.ttl.threadpool
import com.alibaba.*
import com.alibaba.ttl.TtlRunnable
import com.alibaba.ttl.testmodel.Task
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import java.util.concurrent.*
private const val POOL_SIZE = 3
val threadFactory = ThreadFactory { Thread(it).apply { isDaemon = true } }
val executorService = ThreadPoolExecutor(
POOL_SIZE, POOL_SIZE,
10L, TimeUnit.SECONDS,
LinkedBlockingQueue(), threadFactory
)
val scheduledExecutorService = ScheduledThreadPoolExecutor(POOL_SIZE, threadFactory)
class ExecutorClassesTest {
@Test
fun checkThreadPoolExecutorForRemoveMethod() {
val futures = (0 until POOL_SIZE * 2).map {
executorService.submit { Thread.sleep(10) }
}
Runnable {
println("Task should be removed!")
}.let {
if (noTtlAgentRun()) TtlRunnable.get(it) else it
}.let {
executorService.execute(it)
// Does ThreadPoolExecutor#remove method take effect?
assertTrue(executorService.remove(it))
assertFalse(executorService.remove(it))
}
// wait sleep task finished.
futures.forEach { it.get(1, TimeUnit.SECONDS) }
}
@Test
fun checkScheduledExecutorService() {
val ttlInstances = createParentTtlInstances(ConcurrentHashMap())
val tag = "2"
val task = Task(tag, ttlInstances)
val future = scheduledExecutorService.schedule(
if (noTtlAgentRun()) TtlRunnable.get(task) else task,
10,
TimeUnit.MILLISECONDS
)
// create after new Task, won't see parent value in in task!
createParentTtlInstancesAfterCreateChild(ttlInstances)
future.get(1, TimeUnit.SECONDS)
// child Inheritable
assertChildTtlValues(tag, task.copied)
// child do not affect parent
assertParentTtlValues(copyTtlValues(ttlInstances))
}
}
| ttl2-compatible/src/test/java/com/alibaba/ttl/threadpool/ExecutorClassesTest.kt | 517128476 |
package example1
object Example1 {
fun hello(): String = "[KOTLIN]Hello, I'm writing something in the console."
fun sayHello() = println(hello())
@JvmStatic fun main(args: Array<String>) {
sayHello()
}
}
| PrinterKotlinExample/src/example1/Example1.kt | 489315984 |
abstract class Base {
abstract fun foo(a: String = "abc"): String
}
class Derived: Base() {
override fun foo(a: String): String {
return a
}
}
fun box(): String {
val result = Derived().foo()
if (result != "abc") return "Fail: $result"
return "OK"
} | backend.native/tests/external/codegen/box/defaultArguments/function/abstractClass.kt | 848699626 |
import kotlin.test.*
fun box() {
assertEquals(0, 1 and 0)
}
| backend.native/tests/external/stdlib/numbers/BitwiseOperationsTest/andForInt.kt | 3204465096 |
// FILE: 1.kt
class A {
inline fun foo() {}
}
// FILE: 2.kt
fun box(): String {
A().foo()
return "OK"
}
// FILE: 2.smap
SMAP
2.kt
Kotlin
*S Kotlin
*F
+ 1 2.kt
_2Kt
+ 2 1.kt
A
*L
1#1,9:1
4#2:10
*E
*S KotlinDebug
*F
+ 1 2.kt
_2Kt
*L
4#1:10
*E | backend.native/tests/external/codegen/boxInline/smap/classFromDefaultPackage.kt | 2104182984 |
/**
* This file is part of Todo.txt Touch, an Android app for managing your todo.txt file (http://todotxt.com).
* Copyright (c) 2009-2012 Todo.txt contributors (http://todotxt.com)
* LICENSE:
* Todo.txt Touch 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 2 of the License, or (at your option) any
* later version.
* Todo.txt Touch 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 Todo.txt Touch. If not, see
* //www.gnu.org/licenses/>.
* @author Todo.txt contributors @yahoogroups.com>
* *
* @license http://www.gnu.org/licenses/gpl.html
* *
* @copyright 2009-2012 Todo.txt contributors (http://todotxt.com)
*/
package nl.mpcjanssen.simpletask.remote
import android.Manifest
import android.content.Intent
import android.os.Bundle
import androidx.core.app.ActivityCompat
import nl.mpcjanssen.simpletask.R
import nl.mpcjanssen.simpletask.Simpletask
import nl.mpcjanssen.simpletask.ThemedNoActionBarActivity
import nl.mpcjanssen.simpletask.TodoApplication
import nl.mpcjanssen.simpletask.databinding.LoginBinding
import nl.mpcjanssen.simpletask.util.Config
import nl.mpcjanssen.simpletask.util.showToastLong
class LoginScreen : ThemedNoActionBarActivity() {
private lateinit var binding: LoginBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (FileStore.isAuthenticated) {
switchToTodolist()
}
setTheme(TodoApplication.config.activeTheme)
binding = LoginBinding.inflate(layoutInflater)
setContentView(binding.root)
val loginButton = binding.login
loginButton.setOnClickListener {
startLogin()
}
}
private fun switchToTodolist() {
val intent = Intent(this, Simpletask::class.java)
startActivity(intent)
finish()
}
private fun finishLogin() {
if (FileStore.isAuthenticated) {
switchToTodolist()
} else {
showToastLong(this, "Storage access denied")
}
}
internal fun startLogin() {
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_PERMISSION)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
REQUEST_PERMISSION -> finishLogin()
}
}
companion object {
private val REQUEST_PERMISSION = 1
internal val TAG = LoginScreen::class.java.simpleName
}
}
| app/src/encrypted/java/nl/mpcjanssen/simpletask/remote/LoginScreen.kt | 3069888898 |
package com.xenoage.zong.core.info
/**
* Information about a single score,
* like title or composer.
*/
class ScoreInfo(
/** Title of the work */
var workTitle: String? = null,
/** Number of the work */
var workNumber: String? = null,
/** Title of the movement */
var movementTitle: String? = null,
/** Number of the movement */
var movementNumber: String? = null,
/** List of creators (composers, arrangers, ...) */
var creators: MutableList<Creator> = mutableListOf(),
/** List of rights. */
var rights: MutableList<Rights> = mutableListOf()
) {
/**
* Gets the first mentioned composer of this score, or null
* if unavailable.
*/
val composer: String?
get() = creators.find { it.type == "composer" }?.name
/**
* Gets the title of the score. This is the movement-title, or if unknown,
* the work-title. If both are unknown, null is returned.
*/
val title: String?
get() = movementTitle ?: workTitle
}
| core/src/com/xenoage/zong/core/info/ScoreInfo.kt | 1363774594 |
// "Make 'Foo' data class" "true"
class Foo(val bar: String, var baz: Int)
fun test() {
val foo = Foo("A", 1)
var (bar, baz) = foo<caret>
} | plugins/kotlin/idea/tests/testData/quickfix/addDataModifier/test2.kt | 926016694 |
package com.goldenpiedevs.schedule.app.ui.teachers
import com.goldenpiedevs.schedule.app.core.dao.timetable.DaoTeacherModel
import com.goldenpiedevs.schedule.app.ui.base.BaseView
import io.realm.OrderedRealmCollection
interface TeachersView : BaseView {
fun showTeachersData(data: OrderedRealmCollection<DaoTeacherModel>)
} | app/src/main/java/com/goldenpiedevs/schedule/app/ui/teachers/TeachersView.kt | 3363445904 |
// PROBLEM: Fewer arguments provided (1) than placeholders specified (3)
// FIX: none
package org.apache.logging.log4j
private val logger: Logger? = null
fun foo(a: Int, b: Int) {
logger?.atDebug()?.log("<caret>test {} {} {}", 1, Exception())
}
interface LogBuilder:{
fun log(format: String, param1: Any, param2: Any)
}
interface Logger {
fun atDebug(): LogBuilder
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/logging/placeholderCountMatchesArgumentCount/log4jBuilder/logException2.kt | 925393885 |
// 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.compilerPlugin.kotlinxSerialization.compiler.extensions
import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
import org.jetbrains.kotlin.codegen.ImplementationBodyCodegen
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.ir.ObsoleteDescriptorBasedAPI
import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
import org.jetbrains.kotlin.js.translate.context.TranslationContext
import org.jetbrains.kotlin.js.translate.declaration.DeclarationBodyVisitor
import org.jetbrains.kotlin.psi.KtPureClassOrObject
import org.jetbrains.kotlin.idea.compilerPlugin.kotlinxSerialization.runIfEnabledIn
import org.jetbrains.kotlin.idea.compilerPlugin.kotlinxSerialization.runIfEnabledOn
import org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationCodegenExtension
import org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationJsExtension
import org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationLoweringExtension
class SerializationIDECodegenExtension : SerializationCodegenExtension() {
override fun generateClassSyntheticParts(codegen: ImplementationBodyCodegen) =
runIfEnabledOn(codegen.descriptor) { super.generateClassSyntheticParts(codegen) }
}
class SerializationIDEJsExtension : SerializationJsExtension() {
override fun generateClassSyntheticParts(
declaration: KtPureClassOrObject,
descriptor: ClassDescriptor,
translator: DeclarationBodyVisitor,
context: TranslationContext
) = runIfEnabledOn(descriptor) {
super.generateClassSyntheticParts(declaration, descriptor, translator, context)
}
}
class SerializationIDEIrExtension : SerializationLoweringExtension() {
@OptIn(ObsoleteDescriptorBasedAPI::class)
override fun generate(moduleFragment: IrModuleFragment, pluginContext: IrPluginContext) {
runIfEnabledIn(pluginContext.moduleDescriptor) {
super.generate(moduleFragment, pluginContext)
}
}
} | plugins/kotlin/compiler-plugins/kotlinx-serialization/common/src/org/jetbrains/kotlin/idea/compilerPlugin/kotlinxSerialization/compiler/extensions/SerializationIDECodegenExtensions.kt | 691286291 |
fun foo(a: Any, b: Any) {
<selection>a as String</selection>
a is String
b as String
a as? String
} | plugins/kotlin/idea/tests/testData/unifier/equivalence/expressions/casts/as.kt | 9493287 |
//ALLOW_AST_ACCESS
package test
class ClassVal() {
val property1 = { 1 }()
get
internal val property2 = { 1 }()
get
private val property3 = Object()
get
protected val property4: String = { "" }()
get
public val property5: Int = { 1 }()
get
}
| plugins/kotlin/idea/tests/testData/compiler/loadJava/compiledKotlin/prop/defaultAccessors/ClassValWithGet.kt | 2255796789 |
/*
* Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("NOTHING_TO_INLINE")
package splitties.views.dsl.core
import android.widget.LinearLayout
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
inline fun LinearLayout.lParams(
width: Int = wrapContent,
height: Int = wrapContent,
initParams: LinearLayout.LayoutParams.() -> Unit = {}
): LinearLayout.LayoutParams {
contract { callsInPlace(initParams, InvocationKind.EXACTLY_ONCE) }
return LinearLayout.LayoutParams(width, height).apply(initParams)
}
inline fun LinearLayout.lParams(
width: Int = wrapContent,
height: Int = wrapContent,
gravity: Int = -1,
weight: Float = 0f,
initParams: LinearLayout.LayoutParams.() -> Unit = {}
): LinearLayout.LayoutParams {
contract { callsInPlace(initParams, InvocationKind.EXACTLY_ONCE) }
return LinearLayout.LayoutParams(width, height).also {
it.gravity = gravity
it.weight = weight
}.apply(initParams)
}
| modules/views-dsl/src/androidMain/kotlin/splitties/views/dsl/core/LinearLayout.kt | 2279020458 |
// "Create class 'A'" "true"
package p
// TARGET_PARENT:
class Foo: <caret>A() {
} | plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createClass/delegationSpecifier/createSuperclassInsideSubclass.kt | 3955655575 |
fun Int?.foo() = this?.hashCode() ?: 0
val x = { arg: Int? -> arg.foo() <caret>} | plugins/kotlin/idea/tests/testData/intentions/convertLambdaToReference/nullable.kt | 89012085 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.causeway.client.kroviz.ui.core
import io.kvision.core.*
import io.kvision.html.Button
import io.kvision.html.ButtonStyle
import io.kvision.navbar.Nav
import io.kvision.navbar.Navbar
import io.kvision.navbar.NavbarType
import io.kvision.panel.SimplePanel
import kotlinx.browser.window
import org.apache.causeway.client.kroviz.core.event.EventState
import org.apache.causeway.client.kroviz.core.event.LogEntry
import org.apache.causeway.client.kroviz.core.event.StatusPo
import org.apache.causeway.client.kroviz.core.model.DiagramDM
import org.apache.causeway.client.kroviz.ui.diagram.ClassDiagram
import org.apache.causeway.client.kroviz.ui.dialog.DiagramDialog
import org.apache.causeway.client.kroviz.ui.dialog.EventDialog
import org.apache.causeway.client.kroviz.ui.dialog.NotificationDialog
import org.apache.causeway.client.kroviz.utils.IconManager
class RoStatusBar {
val navbar = Navbar(type = NavbarType.FIXEDBOTTOM)
private val nav = Nav(rightAlign = true)
private val userBtn: Button = buildButton("", "Me", ButtonStyle.OUTLINEWARNING)
private val classDiagram = buildButton("", "Diagram", ButtonStyle.OUTLINEWARNING)
private val success = buildButton("0", "OK", ButtonStyle.OUTLINESUCCESS)
private val running = buildButton("0", "Run", ButtonStyle.OUTLINEWARNING)
private val errors = buildButton("0", "Error", ButtonStyle.OUTLINEDANGER)
private val views = buildButton("0", "Visualize", ButtonStyle.LIGHT)
private val dialogs = buildButton("0", "Dialog", ButtonStyle.LIGHT)
private fun buildButton(text: String, iconName: String, style: ButtonStyle): Button {
return Button(
text = text,
icon = IconManager.find(iconName),
style = style
).apply {
padding = CssSize(-16, UNIT.px)
margin = CssSize(0, UNIT.px)
}
}
init {
navbar.addCssClass("status-bar")
navbar.add(nav)
// nav.add(causewayButton())
// nav.add(kvisionButton())
nav.add(success)
nav.add(running)
nav.add(errors)
nav.add(views)
nav.add(dialogs)
nav.add(userBtn)
initRunning()
initErrors()
initViews()
initDialogs()
}
fun update(status: StatusPo) {
success.text = status.successCnt.toString()
running.text = status.runningCnt.toString()
errors.text = status.errorCnt.toString()
views.text = status.viewsCnt.toString()
dialogs.text = status.dialogsCnt.toString()
}
private fun initRunning() {
running.setAttribute(name = "title", value = "Number of Requests in State RUNNING")
running.onClick {
EventDialog(EventState.RUNNING).open()
}
}
private fun initErrors() {
errors.setAttribute(name = "title", value = "Number of Requests in State ERROR")
errors.onClick {
EventDialog(EventState.ERROR).open()
}
}
private fun initViews() {
views.setAttribute(name = "title", value = "Number of VIEWS")
views.onClick {
EventDialog(EventState.VIEW).open()
}
}
private fun initDialogs() {
views.setAttribute(name = "title", value = "Number of DIALOGS")
views.onClick {
EventDialog(EventState.DIALOG).open()
}
}
fun updateDiagram(dd: DiagramDM) {
classDiagram.style = ButtonStyle.OUTLINESUCCESS
classDiagram.onClick {
val title = dd.title
val code = ClassDiagram.build(dd)
DiagramDialog(title, code).open()
}
}
fun updateUser(user: String) {
userBtn.setAttribute(name = "title", value = user)
userBtn.style = ButtonStyle.OUTLINESUCCESS
}
private fun notify(text: String) {
views.setAttribute(name = "title", value = text)
views.style = ButtonStyle.OUTLINEDANGER
views.onClick {
NotificationDialog(text).open()
}
}
fun acknowledge() {
views.setAttribute(name = "title", value = "no new notifications")
views.style = ButtonStyle.OUTLINELIGHT
}
fun update(le: LogEntry?) {
when (le?.state) {
EventState.ERROR -> turnRed(le)
EventState.MISSING -> turnRed(le)
else -> turnGreen(nav)
}
}
private fun turnGreen(panel: SimplePanel) {
panel.removeCssClass(IconManager.DANGER)
panel.removeCssClass(IconManager.WARN)
panel.addCssClass(IconManager.OK)
navbar.background = Background(color = Color.name(Col.LIGHTGRAY))
}
private fun turnRed(logEntry: LogEntry) {
var text = logEntry.url
if (text.length > 50) text = text.substring(0, 49)
errors.text = text
errors.style = ButtonStyle.OUTLINEDANGER
errors.icon = IconManager.find("Error")
notify(text)
}
private fun causewayButton(): Button {
val classes = "causeway-logo-button-image logo-button"
val b = Button("", style = ButtonStyle.LINK)
b.addCssClass(classes)
return b.onClick {
window.open("https://causeway.apache.org")
}
}
private fun kvisionButton(): Button {
val classes = "kvision-logo-button-image logo-button"
val b = Button("", style = ButtonStyle.LINK)
b.addCssClass(classes)
return b.onClick {
window.open("https://kvision.io")
}
}
/*
http://tabulator.info/images/tabulator_favicon_simple.png
http://tabulator.info/images/tabulator_small.png
https://kroki.io/assets/logo.svg
*/
}
| incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/ui/core/RoStatusBar.kt | 580120220 |
package com.habitrpg.android.habitica.ui.adapter.inventory
import android.content.Context
import android.text.Html
import android.text.method.LinkMovementMethod
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.extensions.inflate
import com.habitrpg.android.habitica.helpers.AppConfigManager
import com.habitrpg.android.habitica.helpers.MainNavigationController
import com.habitrpg.android.habitica.models.shops.Shop
import com.habitrpg.android.habitica.models.shops.ShopCategory
import com.habitrpg.android.habitica.models.shops.ShopItem
import com.habitrpg.android.habitica.models.user.OwnedItem
import com.habitrpg.android.habitica.models.user.User
import com.habitrpg.android.habitica.ui.helpers.bindView
import com.habitrpg.android.habitica.ui.viewHolders.SectionViewHolder
import com.habitrpg.android.habitica.ui.viewHolders.ShopItemViewHolder
import com.habitrpg.android.habitica.ui.views.NPCBannerView
class ShopRecyclerAdapter(private val configManager: AppConfigManager) : androidx.recyclerview.widget.RecyclerView.Adapter<androidx.recyclerview.widget.RecyclerView.ViewHolder>() {
private val items: MutableList<Any> = ArrayList()
private var shopIdentifier: String? = null
private var ownedItems: Map<String, OwnedItem> = HashMap()
var shopSpriteSuffix: String = ""
set(value) {
field = value
notifyItemChanged(0)
}
var context: Context? = null
var user: User? = null
set(value) {
field = value
this.notifyDataSetChanged()
}
private var pinnedItemKeys: List<String> = ArrayList()
var gearCategories: MutableList<ShopCategory> = ArrayList()
set(value) {
field = value
notifyDataSetChanged()
}
internal var selectedGearCategory: String = ""
set(value) {
field = value
if (field != "") {
notifyDataSetChanged()
}
}
private val emptyViewResource: Int
get() = when (this.shopIdentifier) {
Shop.SEASONAL_SHOP -> R.layout.empty_view_seasonal_shop
Shop.TIME_TRAVELERS_SHOP -> R.layout.empty_view_timetravelers
else -> R.layout.simple_textview
}
fun setShop(shop: Shop?) {
if (shop == null) {
return
}
shopIdentifier = shop.identifier
items.clear()
items.add(shop)
for (category in shop.categories) {
if (category.items.size > 0) {
items.add(category)
for (item in category.items) {
item.categoryIdentifier = category.identifier
items.add(item)
}
}
}
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): androidx.recyclerview.widget.RecyclerView.ViewHolder =
when (viewType) {
0 -> {
val view = parent.inflate(R.layout.shop_header)
ShopHeaderViewHolder(view)
}
1 -> {
val view = parent.inflate(R.layout.shop_section_header)
SectionViewHolder(view)
}
2 -> {
val view = parent.inflate(emptyViewResource)
EmptyStateViewHolder(view)
}
else -> {
val view = parent.inflate(R.layout.row_shopitem)
val viewHolder = ShopItemViewHolder(view)
viewHolder.shopIdentifier = shopIdentifier
viewHolder
}
}
@Suppress("ReturnCount")
override fun onBindViewHolder(holder: androidx.recyclerview.widget.RecyclerView.ViewHolder, position: Int) {
val obj = getItem(position)
if (obj != null) {
when (obj.javaClass) {
Shop::class.java -> (obj as? Shop)?.let { (holder as? ShopHeaderViewHolder)?.bind(it, shopSpriteSuffix) }
ShopCategory::class.java -> {
val category = obj as? ShopCategory
val sectionHolder = holder as? SectionViewHolder ?: return
sectionHolder.bind(category?.text ?: "")
if (gearCategories.contains(category)) {
context?.let {context ->
val adapter = HabiticaClassArrayAdapter(context, R.layout.class_spinner_dropdown_item, gearCategories.map { it.identifier })
sectionHolder.spinnerAdapter = adapter
sectionHolder.selectedItem = gearCategories.indexOf(category)
sectionHolder.spinnerSelectionChanged = {
if (selectedGearCategory != gearCategories[holder.selectedItem].identifier) {
selectedGearCategory = gearCategories[holder.selectedItem].identifier
}
}
if (user?.stats?.habitClass != category?.identifier && category?.identifier != "none") {
sectionHolder.notesView?.text = context.getString(R.string.class_gear_disclaimer)
sectionHolder.notesView?.visibility = View.VISIBLE
} else {
sectionHolder.notesView?.visibility = View.GONE
}
}
} else {
sectionHolder.spinnerAdapter = null
sectionHolder.notesView?.visibility = View.GONE
}
}
ShopItem::class.java -> {
val item = obj as? ShopItem ?: return
val itemHolder = holder as? ShopItemViewHolder ?: return
itemHolder.bind(item, item.canAfford(user, 1))
if (ownedItems.containsKey(item.key+"-"+item.pinType)) {
itemHolder.itemCount = ownedItems[item.key+"-"+item.pinType]?.numberOwned ?: 0
}
itemHolder.isPinned = pinnedItemKeys.contains(item.key)
}
String::class.java -> (holder as? EmptyStateViewHolder)?.text = obj as? String
}
}
}
@Suppress("ReturnCount")
private fun getItem(position: Int): Any? {
if (items.size == 0) {
return null
}
if (position == 0) {
return items[0]
}
if (position <= getGearItemCount()) {
return when {
position == 1 -> {
val category = getSelectedShopCategory()
category?.text = context?.getString(R.string.class_equipment) ?: ""
category
}
getSelectedShopCategory()?.items?.size ?: 0 <= position-2 -> return context?.getString(R.string.equipment_empty)
else -> getSelectedShopCategory()?.items?.get(position-2)
}
} else {
val itemPosition = position - getGearItemCount()
if (itemPosition > items.size-1) {
return null
}
return items[itemPosition]
}
}
override fun getItemViewType(position: Int): Int = when(getItem(position)?.javaClass) {
Shop::class.java -> 0
ShopCategory::class.java -> 1
ShopItem::class.java -> 3
else -> 2
}
override fun getItemCount(): Int {
val size = items.size + getGearItemCount()
return if (size == 1) {
2
} else size
}
private fun getGearItemCount(): Int {
return if (selectedGearCategory == "") {
0
} else {
val selectedCategory: ShopCategory? = getSelectedShopCategory()
if (selectedCategory != null) {
if (selectedCategory.items.size == 0) {
2
} else {
selectedCategory.items.size+1
}
} else {
0
}
}
}
private fun getSelectedShopCategory() =
gearCategories.firstOrNull { selectedGearCategory == it.identifier }
fun setOwnedItems(ownedItems: Map<String, OwnedItem>) {
this.ownedItems = ownedItems
this.notifyDataSetChanged()
}
fun setPinnedItemKeys(pinnedItemKeys: List<String>) {
this.pinnedItemKeys = pinnedItemKeys
this.notifyDataSetChanged()
}
internal class ShopHeaderViewHolder(itemView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView) {
private val descriptionView: TextView by bindView(itemView, R.id.descriptionView)
private val npcBannerView: NPCBannerView by bindView(itemView, R.id.npcBannerView)
private val namePlate: TextView by bindView(itemView, R.id.namePlate)
init {
descriptionView.movementMethod = LinkMovementMethod.getInstance()
}
fun bind(shop: Shop, shopSpriteSuffix: String) {
npcBannerView.shopSpriteSuffix = shopSpriteSuffix
npcBannerView.identifier = shop.identifier
@Suppress("DEPRECATION")
descriptionView.text = Html.fromHtml(shop.notes)
namePlate.setText(shop.npcNameResource)
}
}
class EmptyStateViewHolder(view: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(view) {
private val subscribeButton: Button? by bindView(itemView, R.id.subscribeButton)
private val textView: TextView? by bindView(itemView, R.id.textView)
init {
subscribeButton?.setOnClickListener { MainNavigationController.navigate(R.id.gemPurchaseActivity) }
}
var text: String? = null
set(value) {
field = value
textView?.text = field
}
}
}
| Habitica/src/main/java/com/habitrpg/android/habitica/ui/adapter/inventory/ShopRecyclerAdapter.kt | 1294902495 |
package com.cn29.aac.datasource.auth.db
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.cn29.aac.repo.user.LoginBean
@Dao
interface AuthDao {
@Query("SELECT * FROM Auth Where email = :email limit 1")
fun getLogin(email: String?): LiveData<LoginBean>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(loginBean: LoginBean?): Long
} | app/src/main/java/com/cn29/aac/datasource/auth/db/AuthDao.kt | 3703985919 |
package com.mpierucci.android.uiformvalidation
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumentation test, which will execute on an Android device.
*
* @see [Testing documentation](http://d.android.com/tools/testing)
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
@Throws(Exception::class)
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getTargetContext()
assertEquals("com.mpierucci.android.uiformvalidation", appContext.packageName)
}
}
| app/src/androidTest/java/com/mpierucci/android/uiformvalidation/ExampleInstrumentedTest.kt | 2964474164 |
package com.jlangen.vaultbox.vaults
import com.jlangen.vaultbox.architecture.coordinators.Coordinator
import com.jlangen.vaultbox.vaults.VaultService
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.schedulers.Schedulers
class VaultsViewCoordinator(var vaultService: VaultService) : Coordinator<VaultsViewState, VaultsView>() {
override var state: VaultsViewState = VaultsViewState(true, emptyList())
private val disposables = CompositeDisposable()
override fun attach(view: VaultsView) {
view.render(state)
disposables += view.showVaultIntents
.observeOn(AndroidSchedulers.mainThread())
.subscribe { vaultService.show(it) }
disposables += vaultService.findAll()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { vaults ->
state = VaultsViewState(false, vaults)
view.render(state)
}
}
override fun detach(view: VaultsView) {
disposables.dispose()
}
} | app/src/main/java/com/jlangen/vaultbox/vaults/VaultsViewCoordinator.kt | 2035119620 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.ignore.psi.util
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.application.runUndoTransparentWriteAction
import com.intellij.openapi.editor.Document
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.vcs.VcsKey
import com.intellij.openapi.vcs.changes.IgnoredFileContentProvider
import com.intellij.openapi.vcs.changes.IgnoredFileDescriptor
import com.intellij.openapi.vcs.changes.ignore.lang.IgnoreFileConstants
import com.intellij.openapi.vcs.changes.ignore.lang.IgnoreLanguage
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiManager
import com.intellij.vcsUtil.VcsImplUtil
import com.intellij.vcsUtil.VcsUtil
import org.jetbrains.annotations.TestOnly
@TestOnly
fun updateIgnoreBlock(project: Project,
ignoreFile: VirtualFile,
ignoredGroupDescription: String,
vararg newEntries: IgnoredFileDescriptor) {
changeIgnoreFile(project, ignoreFile) { provider ->
updateIgnoreBlock(ignoredGroupDescription, ignoreFile, newEntries, provider)
}
}
fun addNewElementsToIgnoreBlock(project: Project,
ignoreFile: VirtualFile,
ignoredGroupDescription: String,
vararg newEntries: IgnoredFileDescriptor) {
addNewElementsToIgnoreBlock(project, ignoreFile, ignoredGroupDescription, null, *newEntries)
}
fun addNewElementsToIgnoreBlock(project: Project,
ignoreFile: VirtualFile,
ignoredGroupDescription: String,
vcs: VcsKey? = null,
vararg newEntries: IgnoredFileDescriptor) {
changeIgnoreFile(project, ignoreFile, vcs) { provider ->
addNewElementsToIgnoreBlock(ignoredGroupDescription, ignoreFile, newEntries, provider)
}
}
fun addNewElements(project: Project,
ignoreFile: VirtualFile,
newEntries: List<IgnoredFileDescriptor>,
vcs: VcsKey? = null,
ignoreEntryRoot: VirtualFile? = null) {
changeIgnoreFile(project, ignoreFile, vcs) { provider ->
val document = FileDocumentManager.getInstance().getDocument(ignoreFile) ?: return@changeIgnoreFile
if (document.textLength != 0 && document.charsSequence.last() != '\n') {
document.insertString(document.textLength, IgnoreFileConstants.NEWLINE)
}
val textEndOffset = document.textLength
val text = newEntries.joinToString(
separator = IgnoreFileConstants.NEWLINE,
postfix = IgnoreFileConstants.NEWLINE
) { it.toText(provider, ignoreFile, ignoreEntryRoot) }
document.insertString(textEndOffset, text)
}
}
private fun changeIgnoreFile(project: Project,
ignoreFile: VirtualFile,
vcs: VcsKey? = null,
action: (IgnoredFileContentProvider) -> Unit) {
val determinedVcs = (vcs ?: VcsUtil.getVcsFor(project, ignoreFile)?.keyInstanceMethod) ?: return
val ignoredFileContentProvider = VcsImplUtil.findIgnoredFileContentProvider(project, determinedVcs) ?: return
invokeAndWaitIfNeeded {
runUndoTransparentWriteAction {
if (PsiManager.getInstance(project).findFile(ignoreFile)?.language !is IgnoreLanguage) return@runUndoTransparentWriteAction
action(ignoredFileContentProvider)
ignoreFile.save()
}
}
}
private fun updateIgnoreBlock(ignoredGroupDescription: String,
ignoreFile: VirtualFile,
newEntries: Array<out IgnoredFileDescriptor>,
provider: IgnoredFileContentProvider) {
val document = FileDocumentManager.getInstance().getDocument(ignoreFile) ?: return
val contentTextRange = getOrCreateIgnoreBlockContentTextRange(document, ignoredGroupDescription)
val newEntriesText = newEntries.joinToString(
separator = IgnoreFileConstants.NEWLINE,
postfix = IgnoreFileConstants.NEWLINE
) { it.toText(provider, ignoreFile) }
document.replaceString(contentTextRange.startOffset, contentTextRange.endOffset, newEntriesText)
}
private fun addNewElementsToIgnoreBlock(ignoredGroupDescription: String,
ignoreFile: VirtualFile,
newEntries: Array<out IgnoredFileDescriptor>,
provider: IgnoredFileContentProvider) {
val document = FileDocumentManager.getInstance().getDocument(ignoreFile) ?: return
val contentRange = getOrCreateIgnoreBlockContentTextRange(document, ignoredGroupDescription)
val existingEntries = document.charsSequence.subSequence(contentRange.startOffset, contentRange.endOffset).lines().toSet()
val newEntriesText = newEntries
.map { it.toText(provider, ignoreFile) }
.filterNot { it in existingEntries }
.joinToString(separator = IgnoreFileConstants.NEWLINE, postfix = IgnoreFileConstants.NEWLINE)
document.insertString(contentRange.endOffset, newEntriesText)
}
private fun getOrCreateIgnoreBlockContentTextRange(
ignoreFile: Document,
ignoredGroupDescription: String
): TextRange {
val text = ignoreFile.charsSequence
val groupDescrLine = text.lineSequence().indexOfFirst { it == ignoredGroupDescription }
return if (groupDescrLine == -1) {
val ignoreGroupToAppend = createIgnoreGroup(text, ignoredGroupDescription)
ignoreFile.insertString(ignoreFile.textLength, ignoreGroupToAppend)
val lastIndex = ignoreFile.textLength
TextRange(lastIndex, lastIndex)
}
else {
val groupDescrStartOffset = ignoreFile.getLineStartOffset(groupDescrLine)
val tail = text.subSequence(groupDescrStartOffset, ignoreFile.textLength)
val emptyLine = tail.lineSequence()
.drop(1)
.indexOfFirst {
it.isBlank() || it.startsWith(IgnoreFileConstants.HASH)
}
val groupEndOffset = if (emptyLine == -1) {
ignoreFile.insertString(ignoreFile.textLength, IgnoreFileConstants.NEWLINE)
ignoreFile.textLength
}
else {
ignoreFile.getLineStartOffset(emptyLine + 1 + groupDescrLine)
}
val contentStartOffset = if (ignoreFile.lineCount <= groupDescrLine + 1) {
groupEndOffset
}
else {
ignoreFile.getLineStartOffset(groupDescrLine + 1)
}
TextRange(contentStartOffset, groupEndOffset)
}
}
private fun createIgnoreGroup(text: CharSequence, ignoredGroupDescription: String): String {
val newlineRequired = text.isNotEmpty() && text.last() != IgnoreFileConstants.NEWLINE[0]
return buildString {
if (newlineRequired) {
append(IgnoreFileConstants.NEWLINE)
}
append(ignoredGroupDescription)
append(IgnoreFileConstants.NEWLINE)
}
}
private fun IgnoredFileDescriptor.toText(ignoredFileContentProvider: IgnoredFileContentProvider,
ignoreFile: VirtualFile,
ignoreEntryRoot: VirtualFile? = null): String {
val ignorePath = path
val ignoreMask = mask
return if (ignorePath != null) {
val ignoreFileContainingDir = ignoreEntryRoot ?: ignoreFile.parent ?: throw IllegalStateException(
"Cannot determine ignore file path for $ignoreFile")
ignoredFileContentProvider.buildIgnoreEntryContent(ignoreFileContainingDir, this)
}
else {
ignoreMask ?: throw IllegalStateException("IgnoredFileBean: path and mask cannot be null at the same time")
}
}
// Requires write action
private fun VirtualFile.save() {
if (isDirectory || !isValid) {
return
}
val documentManager = FileDocumentManager.getInstance()
if (documentManager.isFileModified(this)) {
documentManager.getDocument(this)?.let(documentManager::saveDocumentAsIs)
}
}
| platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ignore/psi/util/IgnoreFileUtil.kt | 3159535456 |
package com.twobbble.application
import android.app.Application
import android.os.Environment
import com.facebook.drawee.backends.pipeline.Fresco
import com.liulishuo.filedownloader.FileDownloader
import com.tencent.bugly.Bugly
import com.tencent.bugly.beta.Beta
import com.twobbble.R
import com.twobbble.tools.Constant
import com.twobbble.tools.delegates.NotNullSingleValueVar
import com.twobbble.view.activity.MainActivity
import uk.co.chrisjenx.calligraphy.CalligraphyConfig
/**
* Created by liuzipeng on 2017/2/15.
*/
class App : Application() {
//将Application 单利化,可供全局调用 Context
companion object {
var instance: App by NotNullSingleValueVar.DelegatesExt.notNullSingleValue()
}
override fun onCreate() {
super.onCreate()
init()
// initFont()
}
private fun initFont() {
// CalligraphyConfig.initDefault(CalligraphyConfig.Builder().
// setDefaultFontPath("fonts/yuehei.ttf").setFontAttrId(R.attr.fontPath).build())
}
private fun init() {
instance = this
FileDownloader.init(applicationContext)
Thread {
Fresco.initialize(this)
}.start()
initBugLy()
}
fun initBugLy() {
Beta.initDelay = 3000
Beta.largeIconId = R.mipmap.ic_launcher
Beta.canShowUpgradeActs.add(MainActivity::class.java)
Beta.smallIconId = R.drawable.ic_update_black_24dp
Beta.upgradeDialogLayoutId = R.layout.upgrade_dialog
Beta.storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
Bugly.init(applicationContext, Constant.BUGLY_ID, true)
}
} | app/src/main/java/com/twobbble/application/App.kt | 3288755804 |
// 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.openapi.updateSettings.impl
import com.intellij.execution.process.ProcessIOExecutorService
import com.intellij.ide.IdeBundle
import com.intellij.ide.externalComponents.ExternalComponentManager
import com.intellij.ide.externalComponents.ExternalComponentSource
import com.intellij.ide.plugins.*
import com.intellij.ide.plugins.marketplace.MarketplaceRequests
import com.intellij.ide.util.PropertiesComponent
import com.intellij.internal.statistic.eventLog.fus.MachineIdManager
import com.intellij.notification.*
import com.intellij.notification.impl.NotificationsConfigurationImpl
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.application.*
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.diagnostic.IdeaLoggingEvent
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.*
import com.intellij.openapi.util.text.HtmlBuilder
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame
import com.intellij.reference.SoftReference
import com.intellij.util.Urls
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.concurrency.annotations.RequiresNoReadLock
import com.intellij.util.containers.MultiMap
import com.intellij.util.io.HttpRequests
import com.intellij.util.io.URLUtil
import com.intellij.util.ui.UIUtil
import com.intellij.xml.util.XmlStringUtil
import org.jdom.JDOMException
import org.jetbrains.annotations.ApiStatus
import java.io.File
import java.io.IOException
import java.net.HttpURLConnection
import java.nio.file.Files
import java.nio.file.Path
import java.util.*
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.ReentrantLock
import javax.swing.JComponent
import kotlin.Result
import kotlin.concurrent.withLock
/**
* See XML file by [ApplicationInfoEx.getUpdateUrls] for reference.
*/
object UpdateChecker {
private val LOG = logger<UpdateChecker>()
private const val DISABLED_UPDATE = "disabled_update.txt"
private const val DISABLED_PLUGIN_UPDATE = "plugin_disabled_updates.txt"
private const val PRODUCT_DATA_TTL_MIN = 5L
private const val MACHINE_ID_DISABLED_PROPERTY = "machine.id.disabled"
private const val MACHINE_ID_PARAMETER = "mid"
private enum class NotificationKind { PLATFORM, PLUGINS, EXTERNAL }
private val updateUrl: String
get() = System.getProperty("idea.updates.url") ?: ApplicationInfoEx.getInstanceEx().updateUrls!!.checkingUrl
private val productDataLock = ReentrantLock()
private var productDataCache: SoftReference<Result<Product?>>? = null
private val ourUpdatedPlugins: MutableMap<PluginId, PluginDownloader> = HashMap()
private val ourShownNotifications = MultiMap<NotificationKind, Notification>()
private var machineIdInitialized = false
/**
* Adding a plugin ID to this collection allows to exclude a plugin from a regular update check.
* Has no effect on non-bundled plugins.
*/
@Suppress("MemberVisibilityCanBePrivate")
val excludedFromUpdateCheckPlugins: HashSet<String> = hashSetOf()
init {
UpdateRequestParameters.addParameter("build", ApplicationInfo.getInstance().build.asString())
UpdateRequestParameters.addParameter("uid", PermanentInstallationID.get())
UpdateRequestParameters.addParameter("os", SystemInfo.OS_NAME + ' ' + SystemInfo.OS_VERSION)
if (ExternalUpdateManager.ACTUAL != null) {
val name = if (ExternalUpdateManager.ACTUAL == ExternalUpdateManager.TOOLBOX) "Toolbox" else ExternalUpdateManager.ACTUAL.toolName
UpdateRequestParameters.addParameter("manager", name)
}
if (ApplicationInfoEx.getInstanceEx().isEAP) {
UpdateRequestParameters.addParameter("eap", "")
}
}
@JvmStatic
fun getNotificationGroup(): NotificationGroup =
NotificationGroupManager.getInstance().getNotificationGroup("IDE and Plugin Updates")
@JvmStatic
fun getNotificationGroupForUpdateResults(): NotificationGroup =
NotificationGroupManager.getInstance().getNotificationGroup("Plugin Update Results")
/**
* For scheduled update checks.
*/
@JvmStatic
fun updateAndShowResult(): ActionCallback {
return ActionCallback().also {
ProcessIOExecutorService.INSTANCE.execute {
doUpdateAndShowResult(
userInitiated = false,
preferDialog = false,
showSettingsLink = true,
callback = it,
)
}
}
}
/**
* For manual update checks (Help | Check for Updates, Settings | Updates | Check Now)
* (the latter action passes customized update settings and forces results presentation in a dialog).
*/
@JvmStatic
@JvmOverloads
fun updateAndShowResult(
project: Project?,
customSettings: UpdateSettings? = null,
) {
ProgressManager.getInstance().run(object : Task.Backgroundable(project, IdeBundle.message("updates.checking.progress"), true) {
override fun run(indicator: ProgressIndicator) = doUpdateAndShowResult(
getProject(),
customSettings,
userInitiated = true,
preferDialog = isConditionalModal,
showSettingsLink = shouldStartInBackground(),
indicator = indicator,
)
override fun isConditionalModal(): Boolean = customSettings != null
override fun shouldStartInBackground(): Boolean = !isConditionalModal
})
}
@JvmStatic
private fun doUpdateAndShowResult(
project: Project? = null,
customSettings: UpdateSettings? = null,
userInitiated: Boolean,
preferDialog: Boolean,
showSettingsLink: Boolean,
indicator: ProgressIndicator? = null,
callback: ActionCallback? = null,
) {
if (!PropertiesComponent.getInstance().getBoolean(MACHINE_ID_DISABLED_PROPERTY, false) && !machineIdInitialized) {
machineIdInitialized = true
val machineId = MachineIdManager.getAnonymizedMachineId("JetBrainsUpdates", "")
if (machineId != null) {
UpdateRequestParameters.addParameter(MACHINE_ID_PARAMETER, machineId)
}
}
val updateSettings = customSettings ?: UpdateSettings.getInstance()
val platformUpdates = getPlatformUpdates(updateSettings, indicator)
if (platformUpdates is PlatformUpdates.ConnectionError) {
if (userInitiated) {
showErrors(project, IdeBundle.message("updates.error.connection.failed", platformUpdates.error.message), preferDialog)
}
callback?.setRejected()
return
}
val (pluginUpdates, customRepoPlugins, internalErrors) = getInternalPluginUpdates(
(platformUpdates as? PlatformUpdates.Loaded)?.newBuild?.apiVersion,
indicator,
)
indicator?.text = IdeBundle.message("updates.external.progress")
val (externalUpdates, externalErrors) = getExternalPluginUpdates(updateSettings, indicator)
UpdateSettings.getInstance().saveLastCheckedInfo()
if (userInitiated && (internalErrors.isNotEmpty() || externalErrors.isNotEmpty())) {
val builder = HtmlBuilder()
internalErrors.forEach { (host, ex) ->
if (!builder.isEmpty) builder.br()
val message = host?.let {
IdeBundle.message("updates.plugins.error.message2", it, ex.message)
} ?: IdeBundle.message("updates.plugins.error.message1", ex.message)
builder.append(message)
}
externalErrors.forEach { (key, value) ->
if (!builder.isEmpty) builder.br()
builder.append(IdeBundle.message("updates.external.error.message", key.name, value.message))
}
showErrors(project, builder.wrapWithHtmlBody().toString(), preferDialog)
}
ApplicationManager.getApplication().invokeLater {
fun nonIgnored(downloaders: Collection<PluginDownloader>) = downloaders.filterNot { isIgnored(it.descriptor) }
val enabledPlugins = nonIgnored(pluginUpdates.allEnabled)
val updatedPlugins = enabledPlugins + nonIgnored(pluginUpdates.allDisabled)
val forceDialog = preferDialog || userInitiated && !notificationsEnabled()
if (platformUpdates is PlatformUpdates.Loaded) {
showResults(
project,
platformUpdates,
updatedPlugins,
pluginUpdates.incompatible,
showNotification = userInitiated || WelcomeFrame.getInstance() != null,
forceDialog,
showSettingsLink,
)
}
else {
showResults(
project,
updatedPlugins,
customRepoPlugins,
externalUpdates,
enabledPlugins.isNotEmpty(),
userInitiated,
forceDialog,
showSettingsLink,
)
}
callback?.setDone()
}
}
@JvmOverloads
@JvmStatic
@JvmName("getPlatformUpdates")
internal fun getPlatformUpdates(
settings: UpdateSettings = UpdateSettings.getInstance(),
indicator: ProgressIndicator? = null,
): PlatformUpdates =
try {
indicator?.text = IdeBundle.message("updates.checking.platform")
val productData = loadProductData(indicator)
if (!settings.isPlatformUpdateEnabled || productData == null) {
PlatformUpdates.Empty
}
else {
UpdateStrategy(ApplicationInfo.getInstance().build, productData, settings).checkForUpdates()
}
}
catch (e: Exception) {
LOG.infoWithDebug(e)
when (e) {
is JDOMException -> PlatformUpdates.Empty // corrupted content, don't bother telling user
else -> PlatformUpdates.ConnectionError(e)
}
}
@JvmStatic
@Throws(IOException::class, JDOMException::class)
fun loadProductData(indicator: ProgressIndicator?): Product? =
productDataLock.withLock {
val cached = SoftReference.dereference(productDataCache)
if (cached != null) return@withLock cached.getOrThrow()
val result = runCatching {
var url = Urls.newFromEncoded(updateUrl)
if (url.scheme != URLUtil.FILE_PROTOCOL) {
url = UpdateRequestParameters.amendUpdateRequest(url)
}
LOG.debug { "loading ${url}" }
HttpRequests.request(url)
.connect { JDOMUtil.load(it.getReader(indicator)) }
.let { parseUpdateData(it) }
?.also {
if (it.disableMachineId) {
PropertiesComponent.getInstance().setValue(MACHINE_ID_DISABLED_PROPERTY, true)
UpdateRequestParameters.removeParameter(MACHINE_ID_PARAMETER)
}
}
}
productDataCache = SoftReference(result)
AppExecutorUtil.getAppScheduledExecutorService().schedule(this::clearProductDataCache, PRODUCT_DATA_TTL_MIN, TimeUnit.MINUTES)
return@withLock result.getOrThrow()
}
private fun clearProductDataCache() {
if (productDataLock.tryLock(1, TimeUnit.MILLISECONDS)) { // longer means loading now, no much sense in clearing
productDataCache = null
productDataLock.unlock()
}
}
@ApiStatus.Internal
@JvmStatic
fun updateDescriptorsForInstalledPlugins(state: InstalledPluginsState) {
if (ApplicationInfoEx.getInstanceEx().usesJetBrainsPluginRepository()) {
ApplicationManager.getApplication().executeOnPooledThread {
val updateable = collectUpdateablePlugins()
if (updateable.isNotEmpty()) {
findUpdatesInJetBrainsRepository(updateable, mutableMapOf(), mutableMapOf(), null, state, null)
}
}
}
}
/**
* When [buildNumber] is null, returns new versions of plugins compatible with the current IDE version,
* otherwise, returns versions compatible with the specified build.
*/
@RequiresBackgroundThread
@RequiresNoReadLock
@JvmOverloads
@JvmStatic
fun getInternalPluginUpdates(
buildNumber: BuildNumber? = null,
indicator: ProgressIndicator? = null,
): InternalPluginResults {
indicator?.text = IdeBundle.message("updates.checking.plugins")
if (System.getProperty("idea.ignore.disabled.plugins") == null) {
val brokenPlugins = MarketplaceRequests.Instance.getBrokenPlugins(ApplicationInfo.getInstance().build)
if (brokenPlugins.isNotEmpty()) {
PluginManagerCore.updateBrokenPlugins(brokenPlugins)
}
}
val updateable = collectUpdateablePlugins()
if (updateable.isEmpty()) {
return InternalPluginResults(PluginUpdates())
}
val toUpdate = HashMap<PluginId, PluginDownloader>()
val toUpdateDisabled = HashMap<PluginId, PluginDownloader>()
val customRepoPlugins = HashMap<PluginId, PluginNode>()
val errors = LinkedHashMap<String?, Exception>()
val state = InstalledPluginsState.getInstance()
for (host in RepositoryHelper.getPluginHosts()) {
try {
if (host == null && ApplicationInfoEx.getInstanceEx().usesJetBrainsPluginRepository()) {
findUpdatesInJetBrainsRepository(updateable, toUpdate, toUpdateDisabled, buildNumber, state, indicator)
}
else {
RepositoryHelper.loadPlugins(host, buildNumber, indicator).forEach { descriptor ->
val id = descriptor.pluginId
if (updateable.remove(id) != null) {
prepareDownloader(state, descriptor, buildNumber, toUpdate, toUpdateDisabled, indicator, host)
}
// collect latest plugins from custom repos
val storedDescriptor = customRepoPlugins[id]
if (storedDescriptor == null || StringUtil.compareVersionNumbers(descriptor.version, storedDescriptor.version) > 0) {
customRepoPlugins[id] = descriptor
}
}
}
}
catch (e: Exception) {
LOG.info(
"failed to load plugins from ${host ?: "default repository"}: ${e.message}",
if (LOG.isDebugEnabled) e else null,
)
errors[host] = e
}
}
val incompatible = if (buildNumber == null) emptyList() else {
// collecting plugins that aren't going to be updated and are incompatible with the new build
// (the map may contain updateable bundled plugins - those are expected to have a compatible version in IDE)
updateable.values.asSequence()
.filterNotNull()
.filter { it.isEnabled && !it.isBundled && !PluginManagerCore.isCompatible(it, buildNumber) }
.toSet()
}
return InternalPluginResults(PluginUpdates(toUpdate.values, toUpdateDisabled.values, incompatible), customRepoPlugins.values, errors)
}
private fun collectUpdateablePlugins(): MutableMap<PluginId, IdeaPluginDescriptor?> {
val updateable = HashMap<PluginId, IdeaPluginDescriptor?>()
// installed plugins that could be updated (either downloaded or updateable bundled)
PluginManagerCore.getPlugins()
.filter { !it.isBundled || it.allowBundledUpdate() }
.associateByTo(updateable) { it.pluginId }
// plugins installed in an instance from which the settings were imported
val onceInstalled = PluginManager.getOnceInstalledIfExists()
if (onceInstalled != null) {
try {
Files.readAllLines(onceInstalled).forEach { line ->
val id = PluginId.getId(line.trim { it <= ' ' })
updateable.putIfAbsent(id, null)
}
}
catch (e: IOException) {
LOG.error(onceInstalled.toString(), e)
}
@Suppress("SSBasedInspection")
onceInstalled.toFile().deleteOnExit()
}
// excluding plugins that take care about their own updates
if (excludedFromUpdateCheckPlugins.isNotEmpty() && !ApplicationManager.getApplication().isInternal) {
excludedFromUpdateCheckPlugins.forEach {
val id = PluginId.getId(it)
val plugin = updateable[id]
if (plugin != null && plugin.isBundled) {
updateable.remove(id)
}
}
}
return updateable
}
@RequiresBackgroundThread
@RequiresNoReadLock
private fun findUpdatesInJetBrainsRepository(updateable: MutableMap<PluginId, IdeaPluginDescriptor?>,
toUpdate: MutableMap<PluginId, PluginDownloader>,
toUpdateDisabled: MutableMap<PluginId, PluginDownloader>,
buildNumber: BuildNumber?,
state: InstalledPluginsState,
indicator: ProgressIndicator?) {
val marketplacePluginIds = MarketplaceRequests.Instance.getMarketplacePlugins(indicator)
val idsToUpdate = updateable.keys.filter { it in marketplacePluginIds }.toSet()
val updates = MarketplaceRequests.getLastCompatiblePluginUpdate(idsToUpdate, buildNumber)
updateable.forEach { (id, descriptor) ->
val lastUpdate = updates.find { it.pluginId == id.idString }
if (lastUpdate != null &&
(descriptor == null || PluginDownloader.compareVersionsSkipBrokenAndIncompatible(lastUpdate.version, descriptor,
buildNumber) > 0)) {
runCatching { MarketplaceRequests.loadPluginDescriptor(id.idString, lastUpdate, indicator) }
.onFailure { if (it !is HttpRequests.HttpStatusException || it.statusCode != HttpURLConnection.HTTP_NOT_FOUND) throw it }
.onSuccess { prepareDownloader(state, it, buildNumber, toUpdate, toUpdateDisabled, indicator, null) }
}
}
(toUpdate.keys.asSequence() + toUpdateDisabled.keys.asSequence()).forEach { updateable.remove(it) }
}
private fun prepareDownloader(state: InstalledPluginsState,
descriptor: PluginNode,
buildNumber: BuildNumber?,
toUpdate: MutableMap<PluginId, PluginDownloader>,
toUpdateDisabled: MutableMap<PluginId, PluginDownloader>,
indicator: ProgressIndicator?,
host: String?) {
val downloader = PluginDownloader.createDownloader(descriptor, host, buildNumber)
state.onDescriptorDownload(descriptor)
checkAndPrepareToInstall(downloader, state, if (PluginManagerCore.isDisabled(downloader.id)) toUpdateDisabled else toUpdate, buildNumber, indicator)
}
@JvmOverloads
@JvmStatic
fun getExternalPluginUpdates(
updateSettings: UpdateSettings,
indicator: ProgressIndicator? = null,
): ExternalPluginResults {
val result = ArrayList<ExternalUpdate>()
val errors = LinkedHashMap<ExternalComponentSource, Exception>()
val manager = ExternalComponentManager.getInstance()
for (source in ExternalComponentManager.getComponentSources()) {
indicator?.checkCanceled()
try {
val siteResult = source.getAvailableVersions(indicator, updateSettings)
.filter { it.isUpdateFor(manager.findExistingComponentMatching(it, source)) }
if (siteResult.isNotEmpty()) {
result += ExternalUpdate(source, siteResult)
}
}
catch (e: Exception) {
LOG.info("failed to load updates for ${source}: ${e.message}", if (LOG.isDebugEnabled) e else null)
errors[source] = e
}
}
return ExternalPluginResults(result, errors)
}
@Throws(IOException::class)
@JvmOverloads
@JvmStatic
fun checkAndPrepareToInstall(
originalDownloader: PluginDownloader,
state: InstalledPluginsState,
toUpdate: MutableMap<PluginId, PluginDownloader>,
buildNumber: BuildNumber? = null,
indicator: ProgressIndicator? = null,
) {
val pluginId = originalDownloader.id
val pluginVersion = originalDownloader.pluginVersion
val installedPlugin = PluginManagerCore.getPlugin(pluginId)
if (installedPlugin == null
|| pluginVersion == null
|| PluginDownloader.compareVersionsSkipBrokenAndIncompatible(pluginVersion, installedPlugin, buildNumber) > 0) {
val oldDownloader = ourUpdatedPlugins[pluginId]
val downloader = if (PluginManagerCore.isDisabled(pluginId)) {
originalDownloader
}
else if (oldDownloader == null || StringUtil.compareVersionNumbers(pluginVersion, oldDownloader.pluginVersion) > 0) {
val descriptor = originalDownloader.descriptor
if (descriptor is PluginNode && descriptor.isIncomplete) {
originalDownloader.prepareToInstall(indicator ?: EmptyProgressIndicator())
ourUpdatedPlugins[pluginId] = originalDownloader
}
originalDownloader
}
else {
oldDownloader
}
val descriptor = downloader.descriptor
if (PluginManagerCore.isCompatible(descriptor, downloader.buildNumber) && !state.wasUpdated(descriptor.pluginId)) {
toUpdate[pluginId] = downloader
}
}
}
private fun showErrors(project: Project?, @NlsContexts.DialogMessage message: String, preferDialog: Boolean) {
if (preferDialog) {
UIUtil.invokeLaterIfNeeded { Messages.showErrorDialog(project, message, IdeBundle.message("updates.error.connection.title")) }
}
else {
getNotificationGroup().createNotification(message, NotificationType.WARNING).notify(project)
}
}
@RequiresEdt
private fun showResults(
project: Project?,
updatedPlugins: List<PluginDownloader>,
customRepoPlugins: Collection<PluginNode>,
externalUpdates: Collection<ExternalUpdate>,
pluginsEnabled: Boolean,
userInitiated: Boolean,
forceDialog: Boolean,
showSettingsLink: Boolean,
) {
if (pluginsEnabled) {
if (userInitiated) {
ourShownNotifications.remove(NotificationKind.PLUGINS)?.forEach { it.expire() }
}
val runnable = { PluginUpdateDialog(project, updatedPlugins, customRepoPlugins).show() }
if (forceDialog) {
runnable()
}
else {
UpdateSettingsEntryPointActionProvider.newPluginUpdates(updatedPlugins, customRepoPlugins)
if (userInitiated) {
val updatedPluginNames = updatedPlugins.map { it.pluginName }
val (title, message) = when (updatedPluginNames.size) {
1 -> "" to IdeBundle.message("updates.plugin.ready.title", updatedPluginNames[0])
else -> IdeBundle.message("updates.plugins.ready.title") to updatedPluginNames.joinToString { """"$it"""" }
}
showNotification(
project,
NotificationKind.PLUGINS,
"plugins.update.available",
title,
message,
NotificationAction.createExpiring(IdeBundle.message("updates.all.plugins.action", updatedPlugins.size)) { e, _ ->
PluginUpdateDialog.runUpdateAll(updatedPlugins, e.getData(PlatformDataKeys.CONTEXT_COMPONENT) as JComponent?, null)
},
NotificationAction.createSimpleExpiring(IdeBundle.message("updates.plugins.dialog.action"), runnable),
NotificationAction.createSimpleExpiring(IdeBundle.message("updates.ignore.updates.link", updatedPlugins.size)) {
ignorePlugins(updatedPlugins.map { it.descriptor })
})
}
}
}
if (externalUpdates.isNotEmpty()) {
ourShownNotifications.remove(NotificationKind.EXTERNAL)?.forEach { it.expire() }
for (update in externalUpdates) {
val runnable = { update.source.installUpdates(update.components) }
if (forceDialog) {
runnable()
}
else {
val message = IdeBundle.message("updates.external.ready.message", update.components.size, update.components.joinToString(", "))
showNotification(
project, NotificationKind.EXTERNAL, "external.components.available", "", message,
NotificationAction.createSimpleExpiring(IdeBundle.message("updates.notification.update.action"), runnable))
}
}
}
else if (!pluginsEnabled) {
if (forceDialog) {
NoUpdatesDialog(showSettingsLink).show()
}
else if (userInitiated) {
if (UpdateSettings.getInstance().isPlatformUpdateEnabled) {
showNotification(project, NotificationKind.PLUGINS, "no.updates.available", "", IdeBundle.message("updates.no.updates.notification"))
}
else {
showNotification(project, NotificationKind.PLUGINS, "no.updates.available", "", IdeBundle.message("updates.no.plugin.updates.notification"))
}
}
}
}
@RequiresEdt
private fun showResults(
project: Project?,
platformUpdates: PlatformUpdates.Loaded,
updatedPlugins: List<PluginDownloader>,
incompatiblePlugins: Collection<IdeaPluginDescriptor>,
showNotification: Boolean,
forceDialog: Boolean,
showSettingsLink: Boolean,
) {
if (showNotification) {
ourShownNotifications.remove(NotificationKind.PLATFORM)?.forEach { it.expire() }
}
val runnable = {
UpdateInfoDialog(
project,
platformUpdates,
showSettingsLink,
updatedPlugins,
incompatiblePlugins,
).show()
}
if (forceDialog) {
runnable()
}
else {
UpdateSettingsEntryPointActionProvider.newPlatformUpdate(platformUpdates, updatedPlugins, incompatiblePlugins)
if (showNotification) {
IdeUpdateUsageTriggerCollector.trigger("notification.shown")
val message = IdeBundle.message(
"updates.new.build.notification.title",
ApplicationNamesInfo.getInstance().fullProductName,
platformUpdates.newBuild.version,
)
showNotification(
project,
NotificationKind.PLATFORM,
"ide.update.available",
"",
message,
NotificationAction.createSimpleExpiring(IdeBundle.message("updates.notification.update.action")) {
IdeUpdateUsageTriggerCollector.trigger("notification.clicked")
runnable()
})
}
}
}
private fun notificationsEnabled(): Boolean =
NotificationsConfigurationImpl.getInstanceImpl().SHOW_BALLOONS &&
NotificationsConfigurationImpl.getSettings(getNotificationGroup().displayId).displayType != NotificationDisplayType.NONE
private fun showNotification(project: Project?,
kind: NotificationKind,
displayId: String,
@NlsContexts.NotificationTitle title: String,
@NlsContexts.NotificationContent message: String,
vararg actions: NotificationAction) {
val type = if (kind == NotificationKind.PLATFORM) NotificationType.IDE_UPDATE else NotificationType.INFORMATION
val notification = getNotificationGroup().createNotification(title, XmlStringUtil.wrapInHtml(message), type)
.setDisplayId(displayId)
.setCollapseDirection(Notification.CollapseActionsDirection.KEEP_LEFTMOST)
notification.whenExpired { ourShownNotifications.remove(kind, notification) }
actions.forEach { notification.addAction(it) }
notification.notify(project)
ourShownNotifications.putValue(kind, notification)
}
@JvmStatic
val disabledToUpdate: Set<PluginId> by lazy { TreeSet(readConfigLines(DISABLED_UPDATE).map { PluginId.getId(it) }) }
@JvmStatic
fun saveDisabledToUpdatePlugins() {
runCatching { DisabledPluginsState.savePluginsList(disabledToUpdate, Path.of(PathManager.getConfigPath(), DISABLED_UPDATE)) }
.onFailure { LOG.error(it) }
}
@JvmStatic
@JvmName("isIgnored")
internal fun isIgnored(descriptor: IdeaPluginDescriptor): Boolean =
descriptor.ignoredKey in ignoredPlugins
@JvmStatic
@JvmName("ignorePlugins")
internal fun ignorePlugins(descriptors: List<IdeaPluginDescriptor>) {
ignoredPlugins += descriptors.map { it.ignoredKey }
runCatching { Files.write(Path.of(PathManager.getConfigPath(), DISABLED_PLUGIN_UPDATE), ignoredPlugins) }
.onFailure { LOG.error(it) }
UpdateSettingsEntryPointActionProvider.removePluginsUpdate(descriptors)
}
private val ignoredPlugins: MutableSet<String> by lazy { TreeSet(readConfigLines(DISABLED_PLUGIN_UPDATE)) }
private val IdeaPluginDescriptor.ignoredKey: String
get() = "${pluginId.idString}+${version}"
private fun readConfigLines(fileName: String): List<String> {
if (!ApplicationManager.getApplication().isUnitTestMode) {
runCatching {
val file = Path.of(PathManager.getConfigPath(), fileName)
if (Files.isRegularFile(file)) {
return Files.readAllLines(file)
}
}.onFailure { LOG.error(it) }
}
return emptyList()
}
private var ourHasFailedPlugins = false
@JvmStatic
fun checkForUpdate(event: IdeaLoggingEvent) {
if (!ourHasFailedPlugins) {
val app = ApplicationManager.getApplication()
if (app != null && !app.isDisposed && UpdateSettings.getInstance().isPluginsCheckNeeded) {
val pluginDescriptor = PluginManagerCore.getPlugin(PluginUtil.getInstance().findPluginId(event.throwable))
if (pluginDescriptor != null && !pluginDescriptor.isBundled) {
ourHasFailedPlugins = true
updateAndShowResult()
}
}
}
}
/** A helper method for manually testing platform updates (see [com.intellij.internal.ShowUpdateInfoDialogAction]). */
@ApiStatus.Internal
fun testPlatformUpdate(
project: Project?,
updateDataText: String,
patchFile: File?,
forceUpdate: Boolean,
) {
if (!ApplicationManager.getApplication().isInternal) {
throw IllegalStateException()
}
val currentBuild = ApplicationInfo.getInstance().build
val productCode = currentBuild.productCode
val checkForUpdateResult = if (forceUpdate) {
val node = JDOMUtil.load(updateDataText)
.getChild("product")
?.getChild("channel")
?: throw IllegalArgumentException("//channel missing")
val channel = UpdateChannel(node, productCode)
val newBuild = channel.builds.firstOrNull()
?: throw IllegalArgumentException("//build missing")
val patches = newBuild.patches.firstOrNull()
?.let { UpdateChain(listOf(it.fromBuild, newBuild.number), it.size) }
PlatformUpdates.Loaded(newBuild, channel, patches)
}
else {
UpdateStrategy(
currentBuild,
parseUpdateData(updateDataText, productCode),
).checkForUpdates()
}
val dialog = when (checkForUpdateResult) {
is PlatformUpdates.Loaded -> UpdateInfoDialog(project, checkForUpdateResult, patchFile)
else -> NoUpdatesDialog(true)
}
dialog.show()
}
//<editor-fold desc="Deprecated stuff.">
@ApiStatus.ScheduledForRemoval(inVersion = "2022.1")
@Deprecated(level = DeprecationLevel.ERROR, replaceWith = ReplaceWith("getNotificationGroup()"), message = "Use getNotificationGroup()")
@Suppress("DEPRECATION")
@JvmField
val NOTIFICATIONS =
NotificationGroup("IDE and Plugin Updates", NotificationDisplayType.STICKY_BALLOON, true, null, null, null, PluginManagerCore.CORE_ID)
@get:ApiStatus.ScheduledForRemoval(inVersion = "2022.1")
@get:Deprecated(message = "Use disabledToUpdate", replaceWith = ReplaceWith("disabledToUpdate"))
@Deprecated(message = "Use disabledToUpdate", replaceWith = ReplaceWith("disabledToUpdate"))
@JvmStatic
val disabledToUpdatePlugins: Set<String>
get() = disabledToUpdate.mapTo(TreeSet()) { it.idString }
@ApiStatus.ScheduledForRemoval(inVersion = "2022.1")
@Deprecated(message = "Use checkForPluginUpdates", replaceWith = ReplaceWith(""))
@JvmStatic
fun getPluginUpdates(): Collection<PluginDownloader>? =
getInternalPluginUpdates().pluginUpdates.allEnabled.ifEmpty { null }
//</editor-fold>
}
| platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateChecker.kt | 628254244 |
// WITH_RUNTIME
import java.lang.System.out
fun x() {
out.<caret>print("test")
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceJavaStaticMethodWithKotlinAnalog/io/print2.kt | 2780178969 |
// 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.findUsages.handlers
import com.intellij.find.findUsages.FindUsagesHandler
import com.intellij.find.findUsages.FindUsagesOptions
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.impl.light.LightMemberReference
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.SearchScope
import com.intellij.usageView.UsageInfo
import com.intellij.util.CommonProcessors
import com.intellij.util.Processor
import org.jetbrains.kotlin.idea.findUsages.KotlinFindUsagesHandlerFactory
import org.jetbrains.kotlin.idea.findUsages.KotlinReferencePreservingUsageInfo
import org.jetbrains.kotlin.idea.findUsages.KotlinReferenceUsageInfo
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.application.runReadActionInSmartMode
import java.util.*
abstract class KotlinFindUsagesHandler<T : PsiElement>(
psiElement: T,
private val elementsToSearch: Collection<PsiElement>,
val factory: KotlinFindUsagesHandlerFactory
) : FindUsagesHandler(psiElement) {
@Suppress("UNCHECKED_CAST")
fun getElement(): T {
return psiElement as T
}
constructor(psiElement: T, factory: KotlinFindUsagesHandlerFactory) : this(psiElement, emptyList(), factory)
override fun getPrimaryElements(): Array<PsiElement> {
return if (elementsToSearch.isEmpty())
arrayOf(psiElement)
else
elementsToSearch.toTypedArray()
}
private fun searchTextOccurrences(
element: PsiElement,
processor: Processor<in UsageInfo>,
options: FindUsagesOptions
): Boolean {
if (!options.isSearchForTextOccurrences) return true
val scope = options.searchScope
if (scope is GlobalSearchScope) {
if (options.fastTrack == null) {
return processUsagesInText(element, processor, scope)
}
options.fastTrack.searchCustom {
processUsagesInText(element, processor, scope)
}
}
return true
}
override fun processElementUsages(
element: PsiElement,
processor: Processor<in UsageInfo>,
options: FindUsagesOptions
): Boolean {
return searchReferences(element, processor, options, forHighlight = false) && searchTextOccurrences(element, processor, options)
}
private fun searchReferences(
element: PsiElement,
processor: Processor<in UsageInfo>,
options: FindUsagesOptions,
forHighlight: Boolean
): Boolean {
val searcher = createSearcher(element, processor, options)
if (!runReadAction { project }.runReadActionInSmartMode { searcher.buildTaskList(forHighlight) }) return false
return searcher.executeTasks()
}
protected abstract fun createSearcher(
element: PsiElement,
processor: Processor<in UsageInfo>,
options: FindUsagesOptions
): Searcher
override fun findReferencesToHighlight(target: PsiElement, searchScope: SearchScope): Collection<PsiReference> {
val results = Collections.synchronizedList(arrayListOf<PsiReference>())
val options = findUsagesOptions.clone()
options.searchScope = searchScope
searchReferences(target, Processor { info ->
val reference = info.reference
if (reference != null) {
results.add(reference)
}
true
}, options, forHighlight = true)
return results
}
protected abstract class Searcher(
val element: PsiElement,
val processor: Processor<in UsageInfo>,
val options: FindUsagesOptions
) {
private val tasks = ArrayList<() -> Boolean>()
/**
* Adds a time-consuming operation to be executed outside read-action
*/
protected fun addTask(task: () -> Boolean) {
tasks.add(task)
}
/**
* Invoked outside read-action
*/
fun executeTasks(): Boolean {
return tasks.all { it() }
}
/**
* Invoked under read-action, should use [addTask] for all time-consuming operations
*/
abstract fun buildTaskList(forHighlight: Boolean): Boolean
}
companion object {
val LOG = Logger.getInstance(KotlinFindUsagesHandler::class.java)
internal fun processUsage(processor: Processor<in UsageInfo>, ref: PsiReference): Boolean =
processor.processIfNotNull {
when {
ref is LightMemberReference -> KotlinReferencePreservingUsageInfo(ref)
ref.element.isValid -> KotlinReferenceUsageInfo(ref)
else -> null
}
}
internal fun processUsage(
processor: Processor<in UsageInfo>,
element: PsiElement
): Boolean =
processor.processIfNotNull { if (element.isValid) UsageInfo(element) else null }
private fun Processor<in UsageInfo>.processIfNotNull(callback: () -> UsageInfo?): Boolean {
ProgressManager.checkCanceled()
val usageInfo = runReadAction(callback)
return if (usageInfo != null) process(usageInfo) else true
}
internal fun createReferenceProcessor(usageInfoProcessor: Processor<in UsageInfo>): Processor<PsiReference> {
val uniqueProcessor = CommonProcessors.UniqueProcessor(usageInfoProcessor)
return Processor { processUsage(uniqueProcessor, it) }
}
}
}
| plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/findUsages/handlers/KotlinFindUsagesHandler.kt | 4046258473 |
// IS_APPLICABLE: false
// WITH_RUNTIME
fun usage() {
println(p.A.some?.<caret>toString())
} | plugins/kotlin/idea/tests/testData/intentions/importMember/FqReferenceCall.kt | 476518716 |
package eu.kanade.tachiyomi.data.database.models
import java.io.Serializable
interface MangaSync : Serializable {
var id: Long?
var manga_id: Long
var sync_id: Int
var remote_id: Int
var title: String
var last_chapter_read: Int
var total_chapters: Int
var score: Float
var status: Int
var update: Boolean
fun copyPersonalFrom(other: MangaSync) {
last_chapter_read = other.last_chapter_read
score = other.score
status = other.status
}
companion object {
fun create(serviceId: Int): MangaSync = MangaSyncImpl().apply {
sync_id = serviceId
}
}
}
| app/src/main/java/eu/kanade/tachiyomi/data/database/models/MangaSync.kt | 2739860635 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.*
import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.descriptors.ClassConstructorDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyzeAsReplacement
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.compareDescriptors
import org.jetbrains.kotlin.idea.core.unwrapIfFakeOverride
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.intentions.isReferenceToBuiltInEnumFunction
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.references.resolveToDescriptors
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.idea.util.hasNotReceiver
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.ImportedFromObjectCallableDescriptor
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.descriptorUtil.isCompanionObject
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassDescriptor
import org.jetbrains.kotlin.resolve.scopes.utils.findFirstClassifierWithDeprecationStatus
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import javax.swing.JComponent
class RemoveRedundantQualifierNameInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool {
/**
* In order to detect that `foo()` and `GrandBase.foo()` point to the same method,
* we need to unwrap fake overrides from descriptors. If we don't do that, they will
* have different `fqName`s, and the inspection will not detect `GrandBase` as a
* redundant qualifier.
*/
var unwrapFakeOverrides: Boolean = false
override fun createOptionsPanel(): JComponent =
SingleCheckboxOptionsPanel(
KotlinBundle.message("redundant.qualifier.unnecessary.non.direct.parent.class.qualifier"),
this,
::unwrapFakeOverrides.name
)
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor =
object : KtVisitorVoid() {
override fun visitDotQualifiedExpression(expression: KtDotQualifiedExpression) {
val expressionParent = expression.parent
if (expressionParent is KtDotQualifiedExpression || expressionParent is KtPackageDirective || expressionParent is KtImportDirective) return
var expressionForAnalyze = expression.firstExpressionWithoutReceiver() ?: return
if (expressionForAnalyze.selectorExpression?.text == expressionParent.getNonStrictParentOfType<KtProperty>()?.name) return
val context = expression.safeAnalyzeNonSourceRootCode()
val receiver = expressionForAnalyze.receiverExpression
val receiverReference = receiver.declarationDescriptor(context)
var hasCompanion = false
var callingBuiltInEnumFunction = false
when {
receiverReference.isEnumCompanionObject() -> when (receiver) {
is KtDotQualifiedExpression -> {
if (receiver.receiverExpression.declarationDescriptor(context).isEnumClass()) return
expressionForAnalyze = receiver
}
else -> return
}
receiverReference.isEnumClass() -> {
hasCompanion = expressionForAnalyze.selectorExpression?.declarationDescriptor(context).isEnumCompanionObject()
callingBuiltInEnumFunction = expressionForAnalyze.isReferenceToBuiltInEnumFunction()
when {
receiver is KtDotQualifiedExpression -> expressionForAnalyze = receiver
hasCompanion || callingBuiltInEnumFunction -> return
}
}
}
val originalExpression: KtExpression = expressionForAnalyze.parent as? KtClassLiteralExpression ?: expressionForAnalyze
val originalDescriptor = expressionForAnalyze.getQualifiedElementSelector()?.declarationDescriptor(context)?.let {
if (hasCompanion || callingBuiltInEnumFunction) it.safeAs<LazyClassDescriptor>()?.companionObjectDescriptor else it
} ?: return
val applicableExpression = expressionForAnalyze.firstApplicableExpression(
validator = { applicableExpression(originalExpression, context, originalDescriptor, unwrapFakeOverrides) },
generator = { firstChild as? KtDotQualifiedExpression }
) ?: return
reportProblem(holder, applicableExpression)
}
override fun visitUserType(type: KtUserType) {
if (type.parent is KtUserType) return
val context = type.safeAnalyzeNonSourceRootCode()
val applicableExpression = type.firstApplicableExpression(
validator = { applicableExpression(context) },
generator = { firstChild as? KtUserType }
) ?: return
reportProblem(holder, applicableExpression)
}
}
}
private fun KtElement.declarationDescriptor(context: BindingContext): DeclarationDescriptor? =
(safeAs<KtQualifiedExpression>()?.selectorExpression ?: this).mainReference?.resolveToDescriptors(context)?.firstOrNull()
private fun DeclarationDescriptor?.isEnumClass() = safeAs<ClassDescriptor>()?.kind == ClassKind.ENUM_CLASS
private fun DeclarationDescriptor?.isEnumCompanionObject() = this?.isCompanionObject() == true && containingDeclaration.isEnumClass()
private tailrec fun KtDotQualifiedExpression.firstExpressionWithoutReceiver(): KtDotQualifiedExpression? = if (hasNotReceiver())
this
else
(receiverExpression as? KtDotQualifiedExpression)?.firstExpressionWithoutReceiver()
private tailrec fun <T : KtElement> T.firstApplicableExpression(validator: T.() -> T?, generator: T.() -> T?): T? {
ProgressManager.checkCanceled()
return validator() ?: generator()?.firstApplicableExpression(validator, generator)
}
private fun KtDotQualifiedExpression.applicableExpression(
originalExpression: KtExpression,
oldContext: BindingContext,
originalDescriptor: DeclarationDescriptor,
unwrapFakeOverrides: Boolean
): KtDotQualifiedExpression? {
if (!receiverExpression.isApplicableReceiver(oldContext) || !ShortenReferences.canBePossibleToDropReceiver(this, oldContext)) {
return null
}
val expressionText = originalExpression.text.substring(lastChild.startOffset - originalExpression.startOffset)
val newExpression = KtPsiFactory(originalExpression).createExpressionIfPossible(expressionText) ?: return null
val newContext = newExpression.analyzeAsReplacement(originalExpression, oldContext)
val newDescriptor = newExpression.selector()?.declarationDescriptor(newContext) ?: return null
fun DeclarationDescriptor.unwrapFakeOverrideIfNecessary(): DeclarationDescriptor {
return if (unwrapFakeOverrides) this.unwrapIfFakeOverride() else this
}
val originalDescriptorFqName = originalDescriptor.unwrapFakeOverrideIfNecessary().fqNameSafe
val newDescriptorFqName = newDescriptor.unwrapFakeOverrideIfNecessary().fqNameSafe
if (originalDescriptorFqName != newDescriptorFqName) return null
return this.takeIf {
if (newDescriptor is ImportedFromObjectCallableDescriptor<*>)
compareDescriptors(project, newDescriptor.callableFromObject, originalDescriptor)
else
compareDescriptors(project, newDescriptor, originalDescriptor)
}
}
private fun KtExpression.selector(): KtElement? = if (this is KtClassLiteralExpression) receiverExpression?.getQualifiedElementSelector()
else getQualifiedElementSelector()
private fun KtExpression.isApplicableReceiver(context: BindingContext): Boolean {
if (this is KtInstanceExpressionWithLabel) return false
val reference = getQualifiedElementSelector()
val descriptor = reference?.declarationDescriptor(context) ?: return false
return if (!descriptor.isCompanionObject()) true
else descriptor.name.asString() != reference.text
}
private fun KtUserType.applicableExpression(context: BindingContext): KtUserType? {
if (firstChild !is KtUserType) return null
val referenceExpression = referenceExpression as? KtNameReferenceExpression ?: return null
val originalDescriptor = referenceExpression.declarationDescriptor(context)?.let {
it.safeAs<ClassConstructorDescriptor>()?.containingDeclaration ?: it
} ?: return null
if (originalDescriptor is ClassDescriptor
&& originalDescriptor.isInner
&& (originalDescriptor.containingDeclaration as? ClassDescriptor)?.typeConstructor != null
) return null
val shortName = originalDescriptor.importableFqName?.shortName() ?: return null
val scope = referenceExpression.getResolutionScope(context) ?: return null
val descriptor = scope.findFirstClassifierWithDeprecationStatus(shortName, NoLookupLocation.FROM_IDE)?.descriptor ?: return null
return if (descriptor == originalDescriptor) this else null
}
private fun reportProblem(holder: ProblemsHolder, element: KtElement) {
val firstChild = element.firstChild
holder.registerProblem(
element,
KotlinBundle.message("redundant.qualifier.name"),
ProblemHighlightType.LIKE_UNUSED_SYMBOL,
TextRange.from(firstChild.startOffsetInParent, firstChild.textLength + 1),
RemoveRedundantQualifierNameQuickFix()
)
}
class RemoveRedundantQualifierNameQuickFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("remove.redundant.qualifier.name.quick.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val file = descriptor.psiElement.containingFile as KtFile
val range = when (val element = descriptor.psiElement) {
is KtUserType -> IntRange(element.startOffset, element.endOffset)
is KtDotQualifiedExpression -> {
val selectorReference = element.selectorExpression?.declarationDescriptor(element.safeAnalyzeNonSourceRootCode(BodyResolveMode.FULL))
val endOffset = if (selectorReference.isEnumClass() || selectorReference.isEnumCompanionObject()) {
element.endOffset
} else {
element.getLastParentOfTypeInRowWithSelf<KtDotQualifiedExpression>()?.getQualifiedElementSelector()?.endOffset ?: return
}
IntRange(element.startOffset, endOffset)
}
else -> IntRange.EMPTY
}
val substring = file.text.substring(range.first, range.last)
Regex.fromLiteral(substring).findAll(file.text, file.importList?.endOffset ?: 0).toList().asReversed().forEach {
ShortenReferences.DEFAULT.process(file, it.range.first, it.range.last + 1)
}
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RemoveRedundantQualifierNameInspection.kt | 1438848382 |
// FIR_IDENTICAL
// FIR_COMPARISON
annotation class Hello
val v = 1
@<caret>
class C
// INVOCATION_COUNT: 0
// EXIST: Hello
// EXIST: Suppress
// ABSENT: String
// ABSENT: v
| plugins/kotlin/completion/tests/testData/basic/common/annotations/TopLevelAnnotation3.kt | 1488378356 |
// 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.contributors.keywords
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import org.jetbrains.kotlin.idea.completion.createKeywordElement
import org.jetbrains.kotlin.idea.completion.createKeywordElementWithSpace
import org.jetbrains.kotlin.idea.completion.isLikelyInPositionForReturn
import org.jetbrains.kotlin.idea.completion.keywords.CompletionKeywordHandler
import org.jetbrains.kotlin.idea.completion.labelNameToTail
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.symbols.KtFunctionSymbol
import org.jetbrains.kotlin.analysis.api.types.KtType
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.name.StandardClassIds
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.findLabelAndCall
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
internal object ReturnKeywordHandler : CompletionKeywordHandler<KtAnalysisSession>(KtTokens.RETURN_KEYWORD) {
@OptIn(ExperimentalStdlibApi::class)
override fun KtAnalysisSession.createLookups(
parameters: CompletionParameters,
expression: KtExpression?,
lookup: LookupElement,
project: Project
): Collection<LookupElement> {
if (expression == null) return emptyList()
val result = mutableListOf<LookupElement>()
for (parent in expression.parentsWithSelf.filterIsInstance<KtDeclarationWithBody>()) {
val returnType = parent.getReturnKtType()
if (parent is KtFunctionLiteral) {
val (label, call) = parent.findLabelAndCall()
if (label != null) {
addAllReturnVariants(result, returnType, label)
}
// check if the current function literal is inlined and stop processing outer declarations if it's not
if (!isInlineFunctionCall(call)) {
break
}
} else {
if (parent.hasBlockBody()) {
addAllReturnVariants(
result,
returnType,
label = null,
isLikelyInPositionForReturn(expression, parent, returnType.isUnit)
)
}
break
}
}
return result
}
private fun KtAnalysisSession.addAllReturnVariants(
result: MutableList<LookupElement>,
returnType: KtType,
label: Name?,
isLikelyInPositionForReturn: Boolean = false
) {
val isUnit = returnType.isUnit
result.add(createKeywordElementWithSpace("return", tail = label?.labelNameToTail().orEmpty(), addSpaceAfter = !isUnit).also {
it.isReturnAtHighlyLikelyPosition = isLikelyInPositionForReturn
})
getExpressionsToReturnByType(returnType).mapTo(result) { returnTarget ->
val lookupElement = if (label != null || returnTarget.addToLookupElementTail) {
createKeywordElement("return", tail = "${label.labelNameToTail()} ${returnTarget.expressionText}")
} else {
createKeywordElement("return ${returnTarget.expressionText}")
}
lookupElement.isReturnAtHighlyLikelyPosition = isLikelyInPositionForReturn
lookupElement
}
}
@OptIn(ExperimentalStdlibApi::class)
private fun KtAnalysisSession.getExpressionsToReturnByType(returnType: KtType): List<ExpressionTarget> = buildList {
if (returnType.canBeNull) {
add(ExpressionTarget("null", addToLookupElementTail = false))
}
fun emptyListShouldBeSuggested(): Boolean =
returnType.isClassTypeWithClassId(StandardClassIds.Collection)
|| returnType.isClassTypeWithClassId(StandardClassIds.List)
|| returnType.isClassTypeWithClassId(StandardClassIds.Iterable)
when {
returnType.isClassTypeWithClassId(StandardClassIds.Boolean) -> {
add(ExpressionTarget("true", addToLookupElementTail = false))
add(ExpressionTarget("false", addToLookupElementTail = false))
}
emptyListShouldBeSuggested() -> {
add(ExpressionTarget("emptyList()", addToLookupElementTail = true))
}
returnType.isClassTypeWithClassId(StandardClassIds.Set) -> {
add(ExpressionTarget("emptySet()", addToLookupElementTail = true))
}
}
}
private fun KtAnalysisSession.isInlineFunctionCall(call: KtCallExpression?): Boolean {
val callee = call?.calleeExpression as? KtReferenceExpression ?: return false
return (callee.mainReference.resolveToSymbol() as? KtFunctionSymbol)?.isInline == true
}
var LookupElement.isReturnAtHighlyLikelyPosition: Boolean by NotNullableUserDataProperty(
Key("KOTLIN_IS_RETURN_AT_HIGHLY_LIKELY_POSITION"),
false
)
}
private data class ExpressionTarget(
val expressionText: String,
/**
* FE10 completion sometimes add return target to LookupElement tails and sometimes not,
* To ensure consistency (at least for tests) we need to do it to
*/
val addToLookupElementTail: Boolean
) | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/completion/contributors/keywords/ReturnKeywordHandler.kt | 2972548879 |
package alraune.operations
import alraune.*
import alraune.entity.*
import pieces100.*
import vgrechka.*
class AlCtl_CreateAppUserAndDB_Disk : AlCtlCommand() {
override fun dance() {
val config = AlraunePrivateConfigs.into1_diskDB
val db = config.dbs.app
fuckAsAdmin(config) {
AlDB2.execute(sql_disconnectAllAssholesAndDropDatabase(db.name))
AlDB2.execute(sql_dropCreateUser(db.user, db.password))
AlDB2.execute(sql_createDatabase(db.name, owner = db.user))
}
clog("\nOK")
}
}
class AlCtl_ShowPGConnections : AlCtlCommand() {
override fun dance() {
fuckMemoryAsAdmin {
val records = select_pg_stat_activity()
clog("\nTotal ${records.size} connections\n")
clogRecords(records)
}
clog("\nOK")
}
}
private fun clogRecords(records: List<*>) {
for (record in records)
clog(jsonize_withSpacesInObjectEntries(record))
}
class AlCtl_ShowDBStats_LocalDebugDB : AlCtlCommand() {
override fun dance() {
fuckAsAdmin(AlDebug.localDebugDB) {
run {
val records = select_pg_stat_activity()
clog("\nTotal ${records.size} connections\n")
fun keySelector(x: pg_stat_activity) = x.usename + "@" + x.datname
records.groupBy(::keySelector).forEach {key, connections ->
clog("$key: ${connections.size} connections")
}
}
run {
val records = select_pg_database()
clog("\nTotal ${records.size} databases\n")
clogRecords(records)
}
run {
withAppConnection {
val count = AlQueryBuilder()
.text("select count(*) from ${Order.Meta.table}")
.selectOneLong()
clog("\nTotal $count orders in app database\n")
}
}
clog("\nOK")
}
}
}
private fun select_pg_database() = AlQueryBuilder()
.ignoreUnknownColumnsWhenSelecting()
.text("select * from pg_database")
.selectSimple(pg_database::class)
private fun select_pg_stat_activity() = AlQueryBuilder()
.ignoreUnknownColumnsWhenSelecting()
.text("select * from pg_stat_activity where datname is not null")
.selectSimple(pg_stat_activity::class)
private fun fuckMemoryAsAdmin(block: () -> Unit) {
fuckAsAdmin(AlraunePrivateConfigs.into1_memoryDB, block)
}
private fun fuckDiskAsAdmin(block: () -> Unit) {
fuckAsAdmin(AlraunePrivateConfigs.into1_diskDB, block)
}
private fun fuckAsAdmin(config: AlrauneRoutine.Config, block: () -> Unit) {
initStandaloneToolMode(config.dbs)
withNewContext1 {
withConnectionFrom(AlGlobal.makeDataSource(config.dbs.admin!!)) {
block()
}
}
}
class pg_stat_activity {
var datname by maybeNull<String>()
var pid by notNull<Int>()
var usename by notNull<String>()
var application_name by notNull<String>()
}
class pg_database {
var datname by maybeNull<String>()
}
| alraune/alraune/src/main/java/alraune/operations/al-ctl-pg.kt | 2397684354 |
package com.apkfuns.hencodersample.work
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.apkfuns.hencodersample.R
/**
* Created by pengwei on 2017/12/6.
*/
class BubbleActivity:AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_bubble)
}
} | HenCoderSample/app/src/main/java/com/apkfuns/hencodersample/work/BubbleActivity.kt | 2761807636 |
// 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.openapi.updateSettings.impl
import com.intellij.execution.process.ProcessIOExecutorService
import com.intellij.ide.IdeBundle
import com.intellij.ide.externalComponents.ExternalComponentManager
import com.intellij.ide.externalComponents.ExternalComponentSource
import com.intellij.ide.plugins.*
import com.intellij.ide.plugins.marketplace.MarketplaceRequests
import com.intellij.ide.util.PropertiesComponent
import com.intellij.internal.statistic.eventLog.fus.MachineIdManager
import com.intellij.notification.*
import com.intellij.notification.impl.NotificationsConfigurationImpl
import com.intellij.openapi.actionSystem.PlatformCoreDataKeys
import com.intellij.openapi.application.*
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.diagnostic.IdeaLoggingEvent
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.*
import com.intellij.openapi.util.text.HtmlBuilder
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame
import com.intellij.reference.SoftReference
import com.intellij.util.Urls
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.concurrency.annotations.RequiresReadLockAbsence
import com.intellij.util.containers.MultiMap
import com.intellij.util.io.HttpRequests
import com.intellij.util.io.URLUtil
import com.intellij.util.ui.UIUtil
import com.intellij.xml.util.XmlStringUtil
import org.jdom.JDOMException
import org.jetbrains.annotations.ApiStatus
import java.io.File
import java.io.IOException
import java.net.HttpURLConnection
import java.nio.file.Files
import java.nio.file.Path
import java.util.*
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.ReentrantLock
import javax.swing.JComponent
import kotlin.Result
import kotlin.concurrent.withLock
/**
* See XML file by [ApplicationInfoEx.getUpdateUrls] for reference.
*/
object UpdateChecker {
private val LOG = logger<UpdateChecker>()
private const val DISABLED_UPDATE = "disabled_update.txt"
private const val DISABLED_PLUGIN_UPDATE = "plugin_disabled_updates.txt"
private const val PRODUCT_DATA_TTL_MIN = 5L
private const val MACHINE_ID_DISABLED_PROPERTY = "machine.id.disabled"
private const val MACHINE_ID_PARAMETER = "mid"
private enum class NotificationKind { PLATFORM, PLUGINS, EXTERNAL }
private val updateUrl: String
get() = System.getProperty("idea.updates.url") ?: ApplicationInfoEx.getInstanceEx().updateUrls!!.checkingUrl
private val productDataLock = ReentrantLock()
private var productDataCache: SoftReference<Result<Product?>>? = null
private val ourUpdatedPlugins: MutableMap<PluginId, PluginDownloader> = HashMap()
private val ourShownNotifications = MultiMap<NotificationKind, Notification>()
private var machineIdInitialized = false
/**
* Adding a plugin ID to this collection allows to exclude a plugin from a regular update check.
* Has no effect on non-bundled plugins.
*/
@Suppress("MemberVisibilityCanBePrivate")
val excludedFromUpdateCheckPlugins: HashSet<String> = hashSetOf()
init {
UpdateRequestParameters.addParameter("build", ApplicationInfo.getInstance().build.asString())
UpdateRequestParameters.addParameter("uid", PermanentInstallationID.get())
UpdateRequestParameters.addParameter("os", SystemInfo.OS_NAME + ' ' + SystemInfo.OS_VERSION)
if (ExternalUpdateManager.ACTUAL != null) {
val name = if (ExternalUpdateManager.ACTUAL == ExternalUpdateManager.TOOLBOX) "Toolbox" else ExternalUpdateManager.ACTUAL.toolName
UpdateRequestParameters.addParameter("manager", name)
}
if (ApplicationInfoEx.getInstanceEx().isEAP) {
UpdateRequestParameters.addParameter("eap", "")
}
}
@JvmStatic
fun getNotificationGroup(): NotificationGroup =
NotificationGroupManager.getInstance().getNotificationGroup("IDE and Plugin Updates")
@JvmStatic
fun getNotificationGroupForPluginUpdateResults(): NotificationGroup =
NotificationGroupManager.getInstance().getNotificationGroup("Plugin Update Results")
@JvmStatic
fun getNotificationGroupForIdeUpdateResults(): NotificationGroup =
NotificationGroupManager.getInstance().getNotificationGroup("IDE Update Results")
/**
* For scheduled update checks.
*/
@JvmStatic
fun updateAndShowResult(): ActionCallback {
return ActionCallback().also {
ProcessIOExecutorService.INSTANCE.execute {
doUpdateAndShowResult(
userInitiated = false,
preferDialog = false,
showSettingsLink = true,
callback = it,
)
}
}
}
/**
* For manual update checks (Help | Check for Updates, Settings | Updates | Check Now)
* (the latter action passes customized update settings and forces results presentation in a dialog).
*/
@JvmStatic
@JvmOverloads
fun updateAndShowResult(
project: Project?,
customSettings: UpdateSettings? = null,
) {
ProgressManager.getInstance().run(object : Task.Backgroundable(project, IdeBundle.message("updates.checking.progress"), true) {
override fun run(indicator: ProgressIndicator) = doUpdateAndShowResult(
getProject(),
customSettings,
userInitiated = true,
preferDialog = isConditionalModal,
showSettingsLink = shouldStartInBackground(),
indicator = indicator,
)
override fun isConditionalModal(): Boolean = customSettings != null
override fun shouldStartInBackground(): Boolean = !isConditionalModal
})
}
@JvmStatic
private fun doUpdateAndShowResult(
project: Project? = null,
customSettings: UpdateSettings? = null,
userInitiated: Boolean,
preferDialog: Boolean,
showSettingsLink: Boolean,
indicator: ProgressIndicator? = null,
callback: ActionCallback? = null,
) {
if (!PropertiesComponent.getInstance().getBoolean(MACHINE_ID_DISABLED_PROPERTY, false) && !machineIdInitialized) {
machineIdInitialized = true
val machineId = MachineIdManager.getAnonymizedMachineId("JetBrainsUpdates", "")
if (machineId != null) {
UpdateRequestParameters.addParameter(MACHINE_ID_PARAMETER, machineId)
}
}
val updateSettings = customSettings ?: UpdateSettings.getInstance()
val platformUpdates = getPlatformUpdates(updateSettings, indicator)
if (platformUpdates is PlatformUpdates.ConnectionError) {
if (userInitiated) {
showErrors(project, IdeBundle.message("updates.error.connection.failed", platformUpdates.error.message), preferDialog)
}
callback?.setRejected()
return
}
val (pluginUpdates, customRepoPlugins, internalErrors) = getInternalPluginUpdates(
(platformUpdates as? PlatformUpdates.Loaded)?.newBuild?.apiVersion,
indicator,
)
indicator?.text = IdeBundle.message("updates.external.progress")
val (externalUpdates, externalErrors) = getExternalPluginUpdates(updateSettings, indicator)
UpdateSettings.getInstance().saveLastCheckedInfo()
if (userInitiated && (internalErrors.isNotEmpty() || externalErrors.isNotEmpty())) {
val builder = HtmlBuilder()
internalErrors.forEach { (host, ex) ->
if (!builder.isEmpty) builder.br()
val message = host?.let {
IdeBundle.message("updates.plugins.error.message2", it, ex.message)
} ?: IdeBundle.message("updates.plugins.error.message1", ex.message)
builder.append(message)
}
externalErrors.forEach { (key, value) ->
if (!builder.isEmpty) builder.br()
builder.append(IdeBundle.message("updates.external.error.message", key.name, value.message))
}
showErrors(project, builder.wrapWithHtmlBody().toString(), preferDialog)
}
ApplicationManager.getApplication().invokeLater {
fun nonIgnored(downloaders: Collection<PluginDownloader>) = downloaders.filterNot { isIgnored(it.descriptor) }
val enabledPlugins = nonIgnored(pluginUpdates.allEnabled)
val updatedPlugins = enabledPlugins + nonIgnored(pluginUpdates.allDisabled)
val forceDialog = preferDialog || userInitiated && !notificationsEnabled()
if (platformUpdates is PlatformUpdates.Loaded) {
showResults(
project,
platformUpdates,
updatedPlugins,
pluginUpdates.incompatible,
showNotification = userInitiated || WelcomeFrame.getInstance() != null,
forceDialog,
showSettingsLink,
)
}
else {
showResults(
project,
updatedPlugins,
customRepoPlugins,
externalUpdates,
enabledPlugins.isNotEmpty(),
userInitiated,
forceDialog,
showSettingsLink,
)
}
callback?.setDone()
}
}
@JvmOverloads
@JvmStatic
@JvmName("getPlatformUpdates")
internal fun getPlatformUpdates(
settings: UpdateSettings = UpdateSettings.getInstance(),
indicator: ProgressIndicator? = null,
): PlatformUpdates =
try {
indicator?.text = IdeBundle.message("updates.checking.platform")
val productData = loadProductData(indicator)
if (ExternalUpdateManager.ACTUAL != null || productData == null) {
PlatformUpdates.Empty
}
else {
UpdateStrategy(ApplicationInfo.getInstance().build, productData, settings).checkForUpdates()
}
}
catch (e: Exception) {
LOG.infoWithDebug(e)
when (e) {
is JDOMException -> PlatformUpdates.Empty // corrupted content, don't bother telling user
else -> PlatformUpdates.ConnectionError(e)
}
}
@JvmStatic
@Throws(IOException::class, JDOMException::class)
fun loadProductData(indicator: ProgressIndicator?): Product? =
productDataLock.withLock {
val cached = SoftReference.dereference(productDataCache)
if (cached != null) return@withLock cached.getOrThrow()
val result = runCatching {
var url = Urls.newFromEncoded(updateUrl)
if (url.scheme != URLUtil.FILE_PROTOCOL) {
url = UpdateRequestParameters.amendUpdateRequest(url)
}
LOG.debug { "loading ${url}" }
HttpRequests.request(url)
.connect { JDOMUtil.load(it.getReader(indicator)) }
.let { parseUpdateData(it) }
?.also {
if (it.disableMachineId) {
PropertiesComponent.getInstance().setValue(MACHINE_ID_DISABLED_PROPERTY, true)
UpdateRequestParameters.removeParameter(MACHINE_ID_PARAMETER)
}
}
}
productDataCache = SoftReference(result)
AppExecutorUtil.getAppScheduledExecutorService().schedule(this::clearProductDataCache, PRODUCT_DATA_TTL_MIN, TimeUnit.MINUTES)
return@withLock result.getOrThrow()
}
private fun clearProductDataCache() {
if (productDataLock.tryLock(1, TimeUnit.MILLISECONDS)) { // longer means loading now, no much sense in clearing
productDataCache = null
productDataLock.unlock()
}
}
@ApiStatus.Internal
@JvmStatic
fun updateDescriptorsForInstalledPlugins(state: InstalledPluginsState) {
if (ApplicationInfoEx.getInstanceEx().usesJetBrainsPluginRepository()) {
ApplicationManager.getApplication().executeOnPooledThread {
val updateable = collectUpdateablePlugins()
if (updateable.isNotEmpty()) {
findUpdatesInJetBrainsRepository(updateable, mutableMapOf(), mutableMapOf(), null, state, null)
}
}
}
}
/**
* When [buildNumber] is null, returns new versions of plugins compatible with the current IDE version,
* otherwise, returns versions compatible with the specified build.
*/
@RequiresBackgroundThread
@RequiresReadLockAbsence
@JvmOverloads
@JvmStatic
fun getInternalPluginUpdates(
buildNumber: BuildNumber? = null,
indicator: ProgressIndicator? = null,
): InternalPluginResults {
indicator?.text = IdeBundle.message("updates.checking.plugins")
if (System.getProperty("idea.ignore.disabled.plugins") == null) {
val brokenPlugins = MarketplaceRequests.getInstance().getBrokenPlugins(ApplicationInfo.getInstance().build)
if (brokenPlugins.isNotEmpty()) {
PluginManagerCore.updateBrokenPlugins(brokenPlugins)
}
}
val updateable = collectUpdateablePlugins()
if (updateable.isEmpty()) {
return InternalPluginResults(PluginUpdates())
}
val toUpdate = HashMap<PluginId, PluginDownloader>()
val toUpdateDisabled = HashMap<PluginId, PluginDownloader>()
val customRepoPlugins = HashMap<PluginId, PluginNode>()
val errors = LinkedHashMap<String?, Exception>()
val state = InstalledPluginsState.getInstance()
for (host in RepositoryHelper.getPluginHosts()) {
try {
if (host == null && ApplicationInfoEx.getInstanceEx().usesJetBrainsPluginRepository()) {
findUpdatesInJetBrainsRepository(updateable, toUpdate, toUpdateDisabled, buildNumber, state, indicator)
}
else {
RepositoryHelper.loadPlugins(host, buildNumber, indicator).forEach { descriptor ->
val id = descriptor.pluginId
if (updateable.remove(id) != null) {
prepareDownloader(state, descriptor, buildNumber, toUpdate, toUpdateDisabled, indicator, host)
}
// collect latest plugins from custom repos
val storedDescriptor = customRepoPlugins[id]
if (storedDescriptor == null || StringUtil.compareVersionNumbers(descriptor.version, storedDescriptor.version) > 0) {
customRepoPlugins[id] = descriptor
}
}
}
}
catch (e: Exception) {
LOG.info(
"failed to load plugins from ${host ?: "default repository"}: ${e.message}",
if (LOG.isDebugEnabled) e else null,
)
errors[host] = e
}
}
val incompatible = if (buildNumber == null) emptyList() else {
// collecting plugins that aren't going to be updated and are incompatible with the new build
// (the map may contain updateable bundled plugins - those are expected to have a compatible version in IDE)
updateable.values.asSequence()
.filterNotNull()
.filter { it.isEnabled && !it.isBundled && !PluginManagerCore.isCompatible(it, buildNumber) }
.toSet()
}
return InternalPluginResults(PluginUpdates(toUpdate.values, toUpdateDisabled.values, incompatible), customRepoPlugins.values, errors)
}
private fun collectUpdateablePlugins(): MutableMap<PluginId, IdeaPluginDescriptor?> {
val updateable = HashMap<PluginId, IdeaPluginDescriptor?>()
// installed plugins that could be updated (either downloaded or updateable bundled)
PluginManagerCore.getPlugins()
.filter { !it.isBundled || it.allowBundledUpdate() }
.associateByTo(updateable) { it.pluginId }
// plugins installed in an instance from which the settings were imported
val onceInstalled = PluginManager.getOnceInstalledIfExists()
if (onceInstalled != null) {
try {
Files.readAllLines(onceInstalled).forEach { line ->
val id = PluginId.getId(line.trim { it <= ' ' })
updateable.putIfAbsent(id, null)
}
}
catch (e: IOException) {
LOG.error(onceInstalled.toString(), e)
}
@Suppress("SSBasedInspection")
onceInstalled.toFile().deleteOnExit()
}
// excluding plugins that take care about their own updates
if (excludedFromUpdateCheckPlugins.isNotEmpty() && !ApplicationManager.getApplication().isInternal) {
excludedFromUpdateCheckPlugins.forEach {
val id = PluginId.getId(it)
val plugin = updateable[id]
if (plugin != null && plugin.isBundled) {
updateable.remove(id)
}
}
}
return updateable
}
@RequiresBackgroundThread
@RequiresReadLockAbsence
private fun findUpdatesInJetBrainsRepository(updateable: MutableMap<PluginId, IdeaPluginDescriptor?>,
toUpdate: MutableMap<PluginId, PluginDownloader>,
toUpdateDisabled: MutableMap<PluginId, PluginDownloader>,
buildNumber: BuildNumber?,
state: InstalledPluginsState,
indicator: ProgressIndicator?) {
val marketplacePluginIds = MarketplaceRequests.getInstance().getMarketplacePlugins(indicator)
val idsToUpdate = updateable.keys.filter { it in marketplacePluginIds }.toSet()
val updates = MarketplaceRequests.getLastCompatiblePluginUpdate(idsToUpdate, buildNumber)
updateable.forEach { (id, descriptor) ->
val lastUpdate = updates.find { it.pluginId == id.idString }
if (lastUpdate != null &&
(descriptor == null || PluginDownloader.compareVersionsSkipBrokenAndIncompatible(lastUpdate.version, descriptor,
buildNumber) > 0)) {
runCatching { MarketplaceRequests.loadPluginDescriptor(id.idString, lastUpdate, indicator) }
.onFailure { if (it !is HttpRequests.HttpStatusException || it.statusCode != HttpURLConnection.HTTP_NOT_FOUND) throw it }
.onSuccess { prepareDownloader(state, it, buildNumber, toUpdate, toUpdateDisabled, indicator, null) }
}
}
(toUpdate.keys.asSequence() + toUpdateDisabled.keys.asSequence()).forEach { updateable.remove(it) }
}
private fun prepareDownloader(state: InstalledPluginsState,
descriptor: PluginNode,
buildNumber: BuildNumber?,
toUpdate: MutableMap<PluginId, PluginDownloader>,
toUpdateDisabled: MutableMap<PluginId, PluginDownloader>,
indicator: ProgressIndicator?,
host: String?) {
val downloader = PluginDownloader.createDownloader(descriptor, host, buildNumber)
state.onDescriptorDownload(descriptor)
checkAndPrepareToInstall(downloader, state, if (PluginManagerCore.isDisabled(downloader.id)) toUpdateDisabled else toUpdate, buildNumber, indicator)
}
@JvmOverloads
@JvmStatic
fun getExternalPluginUpdates(
updateSettings: UpdateSettings,
indicator: ProgressIndicator? = null,
): ExternalPluginResults {
val result = ArrayList<ExternalUpdate>()
val errors = LinkedHashMap<ExternalComponentSource, Exception>()
val manager = ExternalComponentManager.getInstance()
for (source in ExternalComponentManager.getComponentSources()) {
indicator?.checkCanceled()
try {
val siteResult = source.getAvailableVersions(indicator, updateSettings)
.filter { it.isUpdateFor(manager.findExistingComponentMatching(it, source)) }
if (siteResult.isNotEmpty()) {
result += ExternalUpdate(source, siteResult)
}
}
catch (e: Exception) {
LOG.info("failed to load updates for ${source}: ${e.message}", if (LOG.isDebugEnabled) e else null)
errors[source] = e
}
}
return ExternalPluginResults(result, errors)
}
@Throws(IOException::class)
@JvmOverloads
@JvmStatic
fun checkAndPrepareToInstall(
originalDownloader: PluginDownloader,
state: InstalledPluginsState,
toUpdate: MutableMap<PluginId, PluginDownloader>,
buildNumber: BuildNumber? = null,
indicator: ProgressIndicator? = null,
) {
val pluginId = originalDownloader.id
val pluginVersion = originalDownloader.pluginVersion
val installedPlugin = PluginManagerCore.getPlugin(pluginId)
if (installedPlugin == null
|| pluginVersion == null
|| PluginDownloader.compareVersionsSkipBrokenAndIncompatible(pluginVersion, installedPlugin, buildNumber) > 0) {
val oldDownloader = ourUpdatedPlugins[pluginId]
val downloader = if (PluginManagerCore.isDisabled(pluginId)) {
originalDownloader
}
else if (oldDownloader == null || StringUtil.compareVersionNumbers(pluginVersion, oldDownloader.pluginVersion) > 0) {
val descriptor = originalDownloader.descriptor
if (descriptor is PluginNode && descriptor.isIncomplete) {
originalDownloader.prepareToInstall(indicator ?: EmptyProgressIndicator())
ourUpdatedPlugins[pluginId] = originalDownloader
}
originalDownloader
}
else {
oldDownloader
}
val descriptor = downloader.descriptor
if (PluginManagerCore.isCompatible(descriptor, downloader.buildNumber) && !state.wasUpdated(descriptor.pluginId)) {
toUpdate[pluginId] = downloader
}
}
}
private fun showErrors(project: Project?, @NlsContexts.DialogMessage message: String, preferDialog: Boolean) {
if (preferDialog) {
UIUtil.invokeLaterIfNeeded { Messages.showErrorDialog(project, message, IdeBundle.message("updates.error.connection.title")) }
}
else {
getNotificationGroup().createNotification(message, NotificationType.WARNING).notify(project)
}
}
@RequiresEdt
private fun showResults(
project: Project?,
updatedPlugins: List<PluginDownloader>,
customRepoPlugins: Collection<PluginNode>,
externalUpdates: Collection<ExternalUpdate>,
pluginsEnabled: Boolean,
userInitiated: Boolean,
forceDialog: Boolean,
showSettingsLink: Boolean,
) {
if (pluginsEnabled) {
if (userInitiated) {
ourShownNotifications.remove(NotificationKind.PLUGINS)?.forEach { it.expire() }
}
val runnable = { PluginUpdateDialog(project, updatedPlugins, customRepoPlugins).show() }
if (forceDialog) {
runnable()
}
else {
UpdateSettingsEntryPointActionProvider.newPluginUpdates(updatedPlugins, customRepoPlugins)
if (userInitiated) {
val updatedPluginNames = updatedPlugins.map { it.pluginName }
val (title, message) = when (updatedPluginNames.size) {
1 -> "" to IdeBundle.message("updates.plugin.ready.title", updatedPluginNames[0])
else -> IdeBundle.message("updates.plugins.ready.title") to updatedPluginNames.joinToString { """"$it"""" }
}
showNotification(
project,
NotificationKind.PLUGINS,
"plugins.update.available",
title,
message,
NotificationAction.createExpiring(IdeBundle.message("updates.all.plugins.action", updatedPlugins.size)) { e, _ ->
PluginUpdateDialog.runUpdateAll(updatedPlugins, e.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT) as JComponent?, null)
},
NotificationAction.createSimpleExpiring(IdeBundle.message("updates.plugins.dialog.action"), runnable),
NotificationAction.createSimpleExpiring(IdeBundle.message("updates.ignore.updates.link", updatedPlugins.size)) {
ignorePlugins(updatedPlugins.map { it.descriptor })
})
}
}
}
if (externalUpdates.isNotEmpty()) {
ourShownNotifications.remove(NotificationKind.EXTERNAL)?.forEach { it.expire() }
for (update in externalUpdates) {
val runnable = { update.source.installUpdates(update.components) }
if (forceDialog) {
runnable()
}
else {
val message = IdeBundle.message("updates.external.ready.message", update.components.size, update.components.joinToString(", "))
showNotification(
project, NotificationKind.EXTERNAL, "external.components.available", "", message,
NotificationAction.createSimpleExpiring(IdeBundle.message("updates.notification.update.action"), runnable))
}
}
}
else if (!pluginsEnabled) {
if (forceDialog) {
NoUpdatesDialog(showSettingsLink).show()
}
else if (userInitiated) {
showNotification(project, NotificationKind.PLUGINS, "no.updates.available", "", NoUpdatesDialog.getNoUpdatesText())
}
}
}
@RequiresEdt
private fun showResults(
project: Project?,
platformUpdates: PlatformUpdates.Loaded,
updatedPlugins: List<PluginDownloader>,
incompatiblePlugins: Collection<IdeaPluginDescriptor>,
showNotification: Boolean,
forceDialog: Boolean,
showSettingsLink: Boolean,
) {
if (showNotification) {
ourShownNotifications.remove(NotificationKind.PLATFORM)?.forEach { it.expire() }
}
val runnable = {
UpdateInfoDialog(
project,
platformUpdates,
showSettingsLink,
updatedPlugins,
incompatiblePlugins,
).show()
}
if (forceDialog) {
runnable()
}
else {
UpdateSettingsEntryPointActionProvider.newPlatformUpdate(platformUpdates, updatedPlugins, incompatiblePlugins)
if (showNotification) {
IdeUpdateUsageTriggerCollector.NOTIFICATION_SHOWN.log(project)
val message = IdeBundle.message(
"updates.new.build.notification.title",
ApplicationNamesInfo.getInstance().fullProductName,
platformUpdates.newBuild.version,
)
showNotification(
project,
NotificationKind.PLATFORM,
"ide.update.available",
"",
message,
NotificationAction.createSimpleExpiring(IdeBundle.message("updates.notification.update.action")) {
IdeUpdateUsageTriggerCollector.NOTIFICATION_CLICKED.log(project)
runnable()
})
}
}
}
private fun notificationsEnabled(): Boolean =
NotificationsConfigurationImpl.getInstanceImpl().SHOW_BALLOONS &&
NotificationsConfigurationImpl.getSettings(getNotificationGroup().displayId).displayType != NotificationDisplayType.NONE
private fun showNotification(project: Project?,
kind: NotificationKind,
displayId: String,
@NlsContexts.NotificationTitle title: String,
@NlsContexts.NotificationContent message: String,
vararg actions: NotificationAction) {
val type = if (kind == NotificationKind.PLATFORM) NotificationType.IDE_UPDATE else NotificationType.INFORMATION
val notification = getNotificationGroup().createNotification(title, XmlStringUtil.wrapInHtml(message), type)
.setDisplayId(displayId)
.setCollapseDirection(Notification.CollapseActionsDirection.KEEP_LEFTMOST)
notification.whenExpired { ourShownNotifications.remove(kind, notification) }
actions.forEach { notification.addAction(it) }
notification.notify(project)
ourShownNotifications.putValue(kind, notification)
}
@JvmStatic
val disabledToUpdate: Set<PluginId> by lazy { TreeSet(readConfigLines(DISABLED_UPDATE).map { PluginId.getId(it) }) }
@JvmStatic
fun saveDisabledToUpdatePlugins() {
runCatching { DisabledPluginsState.savePluginsList(disabledToUpdate, Path.of(PathManager.getConfigPath(), DISABLED_UPDATE)) }
.onFailure { LOG.error(it) }
}
@JvmStatic
@JvmName("isIgnored")
internal fun isIgnored(descriptor: IdeaPluginDescriptor): Boolean =
descriptor.ignoredKey in ignoredPlugins
@JvmStatic
@JvmName("ignorePlugins")
internal fun ignorePlugins(descriptors: List<IdeaPluginDescriptor>) {
ignoredPlugins += descriptors.map { it.ignoredKey }
runCatching { Files.write(Path.of(PathManager.getConfigPath(), DISABLED_PLUGIN_UPDATE), ignoredPlugins) }
.onFailure { LOG.error(it) }
UpdateSettingsEntryPointActionProvider.removePluginsUpdate(descriptors)
}
private val ignoredPlugins: MutableSet<String> by lazy { TreeSet(readConfigLines(DISABLED_PLUGIN_UPDATE)) }
private val IdeaPluginDescriptor.ignoredKey: String
get() = "${pluginId.idString}+${version}"
private fun readConfigLines(fileName: String): List<String> {
if (!ApplicationManager.getApplication().isUnitTestMode) {
runCatching {
val file = Path.of(PathManager.getConfigPath(), fileName)
if (Files.isRegularFile(file)) {
return Files.readAllLines(file)
}
}.onFailure { LOG.error(it) }
}
return emptyList()
}
private var ourHasFailedPlugins = false
@JvmStatic
fun checkForUpdate(event: IdeaLoggingEvent) {
if (!ourHasFailedPlugins) {
val app = ApplicationManager.getApplication()
if (app != null && !app.isDisposed && UpdateSettings.getInstance().isPluginsCheckNeeded) {
val pluginDescriptor = PluginManagerCore.getPlugin(PluginUtil.getInstance().findPluginId(event.throwable))
if (pluginDescriptor != null && !pluginDescriptor.isBundled) {
ourHasFailedPlugins = true
updateAndShowResult()
}
}
}
}
/** A helper method for manually testing platform updates (see [com.intellij.internal.ShowUpdateInfoDialogAction]). */
@ApiStatus.Internal
fun testPlatformUpdate(
project: Project?,
updateDataText: String,
patchFile: File?,
forceUpdate: Boolean,
) {
if (!ApplicationManager.getApplication().isInternal) {
throw IllegalStateException()
}
val currentBuild = ApplicationInfo.getInstance().build
val productCode = currentBuild.productCode
val checkForUpdateResult = if (forceUpdate) {
val node = JDOMUtil.load(updateDataText)
.getChild("product")
?.getChild("channel")
?: throw IllegalArgumentException("//channel missing")
val channel = UpdateChannel(node, productCode)
val newBuild = channel.builds.firstOrNull()
?: throw IllegalArgumentException("//build missing")
val patches = newBuild.patches.firstOrNull()
?.let { UpdateChain(listOf(it.fromBuild, newBuild.number), it.size) }
PlatformUpdates.Loaded(newBuild, channel, patches)
}
else {
UpdateStrategy(
currentBuild,
parseUpdateData(updateDataText, productCode),
).checkForUpdates()
}
val dialog = when (checkForUpdateResult) {
is PlatformUpdates.Loaded -> UpdateInfoDialog(project, checkForUpdateResult, patchFile)
else -> NoUpdatesDialog(true)
}
dialog.show()
}
//<editor-fold desc="Deprecated stuff.">
@ApiStatus.ScheduledForRemoval
@Deprecated(level = DeprecationLevel.ERROR, replaceWith = ReplaceWith("getNotificationGroup()"), message = "Use getNotificationGroup()")
@Suppress("DEPRECATION")
@JvmField
val NOTIFICATIONS =
NotificationGroup("IDE and Plugin Updates", NotificationDisplayType.STICKY_BALLOON, true, null, null, null, PluginManagerCore.CORE_ID)
@get:ApiStatus.ScheduledForRemoval
@get:Deprecated(message = "Use disabledToUpdate", replaceWith = ReplaceWith("disabledToUpdate"))
@Deprecated(message = "Use disabledToUpdate", replaceWith = ReplaceWith("disabledToUpdate"))
@JvmStatic
val disabledToUpdatePlugins: Set<String>
get() = disabledToUpdate.mapTo(TreeSet()) { it.idString }
@ApiStatus.ScheduledForRemoval
@Deprecated(message = "Use checkForPluginUpdates", replaceWith = ReplaceWith(""))
@JvmStatic
fun getPluginUpdates(): Collection<PluginDownloader>? =
getInternalPluginUpdates().pluginUpdates.allEnabled.ifEmpty { null }
//</editor-fold>
} | platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateChecker.kt | 1269435846 |
fun foo(list: List<String>){}
fun f(){
foo(<caret>)
}
// EXIST: { lookupString: "listOf", tailText: "() (kotlin.collections)", typeText: "List<String>" }
// EXIST: { lookupString: "listOf", tailText: "(vararg elements: String) (kotlin.collections)", typeText: "List<String>" }
// EXIST: { lookupString: "arrayListOf", tailText: "(vararg elements: String) (kotlin.collections)", typeText: "ArrayList<String> /* = ArrayList<String> */" }
| plugins/kotlin/completion/tests/testData/smart/generics/GenericFunction3.kt | 1694042873 |
// IS_APPLICABLE: false
import A.*
enum class A { A1, A2 }
enum class B { B1, B2 }
fun foo() {
A1
A2
valueOf("A1")
<caret>B.B1
B.B2
B.values()
}
| plugins/kotlin/idea/tests/testData/intentions/importAllMembers/EnumSyntheticMethods5.kt | 321347724 |
/*
* 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.room
import com.google.common.truth.Truth.assertThat
import java.util.Arrays
import kotlin.test.assertNull
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class ObservedTableTrackerTest {
private lateinit var mTracker: InvalidationTracker.ObservedTableTracker
@Before
fun setup() {
mTracker = InvalidationTracker.ObservedTableTracker(TABLE_COUNT)
}
@Test
fun basicAdd() {
mTracker.onAdded(2, 3)
assertThat(
mTracker.getTablesToSync()
).isEqualTo(
createResponse(
2,
InvalidationTracker.ObservedTableTracker.ADD,
3,
InvalidationTracker.ObservedTableTracker.ADD
)
)
}
@Test
fun basicRemove() {
initState(2, 3)
mTracker.onRemoved(3)
assertThat(
mTracker.getTablesToSync()
).isEqualTo(
createResponse(3, InvalidationTracker.ObservedTableTracker.REMOVE)
)
}
@Test
fun noChange() {
initState(1, 3)
mTracker.onAdded(3)
assertNull(
mTracker.getTablesToSync()
)
}
@Test
fun multipleAdditionsDeletions() {
initState(2, 4)
mTracker.onAdded(2)
assertNull(
mTracker.getTablesToSync()
)
mTracker.onAdded(2, 4)
assertNull(
mTracker.getTablesToSync()
)
mTracker.onRemoved(2)
assertNull(
mTracker.getTablesToSync()
)
mTracker.onRemoved(2, 4)
assertNull(
mTracker.getTablesToSync()
)
mTracker.onAdded(1, 3)
mTracker.onRemoved(2, 4)
assertThat(
mTracker.getTablesToSync()
).isEqualTo(
createResponse(
1,
InvalidationTracker.ObservedTableTracker.ADD,
2,
InvalidationTracker.ObservedTableTracker.REMOVE,
3,
InvalidationTracker.ObservedTableTracker.ADD,
4,
InvalidationTracker.ObservedTableTracker.REMOVE
)
)
}
private fun initState(vararg tableIds: Int) {
mTracker.onAdded(*tableIds)
mTracker.getTablesToSync()
}
companion object {
private const val TABLE_COUNT = 5
private fun createResponse(vararg tuples: Int): IntArray {
val result = IntArray(TABLE_COUNT)
Arrays.fill(result, InvalidationTracker.ObservedTableTracker.NO_OP)
var i = 0
while (i < tuples.size) {
result[tuples[i]] = tuples[i + 1]
i += 2
}
return result
}
}
} | room/room-runtime/src/test/java/androidx/room/ObservedTableTrackerTest.kt | 1683659749 |
/*
* 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.work
import android.content.Context
import androidx.work.impl.utils.SerialExecutorImpl
import androidx.work.impl.utils.SynchronousExecutor
import androidx.work.impl.utils.taskexecutor.TaskExecutor
import io.reactivex.Single
import io.reactivex.schedulers.Schedulers
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.mockito.Mockito.mock
import java.util.UUID
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executor
import java.util.concurrent.TimeUnit
@RunWith(JUnit4::class)
class RxWorkerTest {
private val syncExecutor = SynchronousExecutor()
private val result = ListenableWorker.Result.success()
@Test
fun simple() {
val worker = Single.just(result).toWorker()
assertThat(worker.startWork().get(), `is`(result))
}
@Test
fun cancelForwarding() {
val latch = CountDownLatch(1)
val worker = Single
.never<ListenableWorker.Result>()
.doOnDispose {
latch.countDown()
}.toWorker(createWorkerParams(syncExecutor))
val future = worker.startWork()
future.cancel(false)
if (!latch.await(1, TimeUnit.MINUTES)) {
throw AssertionError("should've been disposed")
}
}
@Test
fun failedWork() {
val error: Throwable = RuntimeException("a random error")
val worker = Single
.error<ListenableWorker.Result>(error)
.toWorker(createWorkerParams(syncExecutor))
val future = worker.startWork()
try {
future.get()
Assert.fail("should've throw an exception")
} catch (t: Throwable) {
assertThat(t.cause, `is`(error))
}
}
@Test
fun verifyCorrectDefaultScheduler() {
var executorDidRun = false
var runnerDidRun = false
val runner = Runnable {
runnerDidRun = true
}
val executor = Executor {
executorDidRun = true
it.run()
}
val rxWorker = Single.just(result).toWorker(createWorkerParams(executor))
rxWorker.backgroundScheduler.scheduleDirect(runner)
assertThat(runnerDidRun, `is`(true))
assertThat(executorDidRun, `is`(true))
}
@Test
fun customScheduler() {
var executorDidRun = false
val executor = Executor {
executorDidRun = true
it.run()
}
var testSchedulerDidRun = false
val testScheduler = Schedulers.from {
testSchedulerDidRun = true
it.run()
}
val params = createWorkerParams(executor)
val worker = object : RxWorker(mock(Context::class.java), params) {
override fun createWork() = Single.just(result)
override fun getBackgroundScheduler() = testScheduler
}
assertThat(worker.startWork().get(), `is`(result))
assertThat(executorDidRun, `is`(false))
assertThat(testSchedulerDidRun, `is`(true))
}
private fun createWorkerParams(
executor: Executor = SynchronousExecutor(),
progressUpdater: ProgressUpdater = mock(ProgressUpdater::class.java),
foregroundUpdater: ForegroundUpdater = mock(ForegroundUpdater::class.java)
) = WorkerParameters(
UUID.randomUUID(),
Data.EMPTY,
emptyList(),
WorkerParameters.RuntimeExtras(),
1,
0,
executor,
InstantWorkTaskExecutor(),
WorkerFactory.getDefaultWorkerFactory(),
progressUpdater,
foregroundUpdater
)
private fun Single<ListenableWorker.Result>.toWorker(
params: WorkerParameters = createWorkerParams()
): RxWorker {
return object : RxWorker(mock(Context::class.java), params) {
override fun createWork() = this@toWorker
}
}
class InstantWorkTaskExecutor : TaskExecutor {
private val mSynchronousExecutor = SynchronousExecutor()
private val mSerialExecutor = SerialExecutorImpl(mSynchronousExecutor)
override fun getMainThreadExecutor(): Executor {
return mSynchronousExecutor
}
override fun getSerialTaskExecutor(): SerialExecutorImpl {
return mSerialExecutor
}
}
}
| work/work-rxjava2/src/test/java/androidx/work/RxWorkerTest.kt | 3733803290 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.compiler.processing.profiling
import org.junit.AssumptionViolatedException
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
import kotlin.time.Duration
import kotlin.time.Duration.Companion.nanoseconds
import kotlin.time.DurationUnit
import kotlin.time.ExperimentalTime
/**
* Helper rule to run profiling tests.
*
* These tests are run along with `scripts/profile.sh` to build an async profile
* output based on a test scenario.
*
* If this rule is applied outside a profiling session, it will ignore the test.
*/
@OptIn(ExperimentalTime::class)
class ProfileRule : TestRule {
/**
* Runs the given block, repeatedly :).
*
* It will first run it [warmUps] times with a fake tracer. Then it will run
* the block [repeat] times with a real profiling scope that will be captured by
* profile.sh.
*/
fun runRepeated(
warmUps: Int,
repeat: Int,
block: (ProfileScope) -> Unit
) {
val warmUpScope = WarmUpProfileScope()
repeat(warmUps) {
block(warmUpScope)
}
val realProfileScope = RealProfileScope()
repeat(repeat) {
block(realProfileScope)
}
println(buildReport(realProfileScope.measurements).toString())
}
private fun buildReport(measurements: List<Duration>): Stats {
check(measurements.isNotEmpty())
val min = measurements.minByOrNull { it.toLong(DurationUnit.NANOSECONDS) }!!
val max = measurements.maxByOrNull { it.toLong(DurationUnit.NANOSECONDS) }!!
val avg = measurements.fold(Duration.ZERO) { acc, next -> acc + next } / measurements.size
val mean = if (measurements.size % 2 == 0) {
(measurements[measurements.size / 2] + measurements[measurements.size / 2 - 1]) / 2
} else {
measurements[measurements.size / 2]
}
return Stats(
allMeasurements = measurements,
min = min,
max = max,
avg = avg,
mean = mean
)
}
override fun apply(base: Statement, description: Description): Statement {
return object : Statement() {
override fun evaluate() {
assumeProfiling()
base.evaluate()
}
}
}
private fun assumeProfiling() {
if (!isProfilingEnabled) {
throw AssumptionViolatedException("No reason to run while not profiling")
}
}
interface ProfileScope {
/**
* Utility function for tests to mark certain areas of their code for tracking.
*
* This method is explicitly not marked as inline to ensure it shows up in the
* profiling output.
*/
fun trace(block: () -> Unit)
}
private class RealProfileScope : ProfileScope {
private val _measurements = mutableListOf<Duration>()
val measurements: List<Duration>
get() = _measurements
@OptIn(ExperimentalTime::class)
override fun trace(block: () -> Unit) {
// this doesn't do anything but profile.sh trace profiler checks
// this class while filtering stacktraces
val start = now()
try {
block()
} finally {
val end = now()
_measurements.add(end - start)
}
}
private fun now() = System.nanoTime().nanoseconds
}
private class WarmUpProfileScope : ProfileScope {
override fun trace(block: () -> Unit) {
block()
}
}
data class Stats(
val min: Duration,
val max: Duration,
val avg: Duration,
val mean: Duration,
val allMeasurements: List<Duration>,
)
companion object {
val isProfilingEnabled by lazy {
// set by profile.sh
System.getenv("ANDROIDX_ROOM_ENABLE_PROFILE_TESTS") != null
}
}
} | room/room-compiler-processing/src/test/java/androidx/room/compiler/processing/profiling/ProfileRule.kt | 2480036761 |
package taiwan.no1.app.ssfm.internal.di.annotations.scopes
import javax.inject.Scope
/**
* A scoping annotation to permit objects whose lifetime should depend to the life of the application to be
* memorized in the correct component.
*
* @author jieyi
* @since 8/16/17
*/
@Scope
@Retention
@MustBeDocumented
annotation class LocalData | app/src/main/kotlin/taiwan/no1/app/ssfm/internal/di/annotations/scopes/LocalData.kt | 1496194783 |
package taiwan.no1.app.ssfm.internal.di.components
import dagger.Component
import taiwan.no1.app.ssfm.internal.di.annotations.scopes.LocalData
import taiwan.no1.app.ssfm.internal.di.modules.DatabaseModule
import taiwan.no1.app.ssfm.models.data.local.LocalDataStore
/**
*
* @author jieyi
* @since 8/16/17
*/
@LocalData
@Component(dependencies = [AppComponent::class], modules = [DatabaseModule::class])
interface DatabaseComponent {
object Initializer {
// fun rendered(): DatabaseComponent = DaggerDatabaseComponent.builder()
// .appComponent(App.appComponent)
// .roomModule(DatabaseModule())
// .build()
}
fun inject(localDataStore: LocalDataStore)
} | app/src/main/kotlin/taiwan/no1/app/ssfm/internal/di/components/DatabaseComponent.kt | 4262496605 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.build.resources
import androidx.build.getSupportRootFolder
import com.android.build.gradle.LibraryExtension
import org.gradle.api.Project
import org.gradle.api.tasks.Copy
import java.io.File
fun Project.configurePublicResourcesStub(extension: LibraryExtension) {
val targetResFolder = File(project.buildDir, "generated/res/public-stub")
val generatePublicResourcesTask = tasks.register(
"generatePublicResourcesStub",
Copy::class.java
) { task ->
task.from(File(project.getSupportRootFolder(), "buildSrc/res"))
task.into(targetResFolder)
}
extension.libraryVariants.all { variant ->
variant.registerGeneratedResFolders(
project.files(targetResFolder).builtBy(generatePublicResourcesTask)
)
}
}
| buildSrc/private/src/main/kotlin/androidx/build/resources/PublicResourcesStubHelper.kt | 946244388 |
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.vo
interface HasFields {
val fields: Fields
}
// we need to make it class to enable caching (see columnNames by lazy), extension properties
// and functions don't have a way to store calculated value.
data class Fields(private val fields: List<Field> = emptyList()) : List<Field> by fields {
constructor(field: Field) : this(listOf(field))
internal val columnNames by lazy(LazyThreadSafetyMode.NONE) { map { it.columnName } }
}
val HasFields.columnNames
get() = fields.columnNames
fun HasFields.findFieldByColumnName(columnName: String) =
fields.find { it.columnName == columnName } | room/room-compiler/src/main/kotlin/androidx/room/vo/HasFields.kt | 1202198663 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.editorconfig.language.codeinsight
import com.intellij.openapi.application.ex.PathManagerEx
import com.intellij.testFramework.fixtures.BasePlatformTestCase
class EditorConfigFoldingBuilderTest : BasePlatformTestCase() {
override fun getTestDataPath() =
"${PathManagerEx.getCommunityHomePath()}/plugins/editorconfig/testData/org/editorconfig/language/codeinsight/folding/"
fun testSection() = doTest()
fun testSimpleComment() = doTest()
fun testBlankLineBetweenComments() = doTest()
fun testCommentInsideSection() = doTest()
fun testCommentBetweenHeaderAndOption() = doTest()
fun testMultipleSections() = doTest()
fun testTrailingComment() = doTest()
fun testLongComment() = doTest()
private fun doTest() =
myFixture.testFolding("${testDataPath}${getTestName(true)}/.editorconfig")
}
| plugins/editorconfig/test/org/editorconfig/language/codeinsight/EditorConfigFoldingBuilderTest.kt | 4094421663 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.autoimport.changes
import com.intellij.openapi.Disposable
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.externalSystem.autoimport.ExternalSystemModificationType
import com.intellij.openapi.externalSystem.autoimport.changes.vfs.VirtualFileChangesListener.Companion.installAsyncVirtualFileListener
import com.intellij.openapi.externalSystem.autoimport.settings.AsyncSupplier
import com.intellij.openapi.externalSystem.util.PathPrefixTreeMap
import java.util.concurrent.ConcurrentHashMap
/**
* Filters and delegates files and documents events into subscribed listeners.
* Allows to use heavy paths filer, that is defined by [filesProvider].
* Call sequences of [changesListener]'s functions will be skipped if change events didn't happen in watched files.
*/
class AsyncFilesChangesListener(
private val filesProvider: AsyncSupplier<Set<String>>,
private val changesListener: FilesChangesListener,
private val parentDisposable: Disposable
) : FilesChangesListener {
private val updatedFiles = ConcurrentHashMap<String, ModificationData>()
override fun init() {
updatedFiles.clear()
}
override fun onFileChange(path: String, modificationStamp: Long, modificationType: ExternalSystemModificationType) {
updatedFiles[path] = ModificationData(modificationStamp, modificationType)
}
override fun apply() {
val updatedFilesSnapshot = HashMap(updatedFiles)
filesProvider.supply(parentDisposable) { filesToWatch ->
val index = PathPrefixTreeMap<Boolean>()
filesToWatch.forEach { index[it] = true }
val updatedWatchedFiles = updatedFilesSnapshot.flatMap { (path, modificationData) ->
index.getAllDescendantKeys(path)
.map { it to modificationData }
}
if (updatedWatchedFiles.isNotEmpty()) {
changesListener.init()
for ((path, modificationData) in updatedWatchedFiles) {
val (modificationStamp, modificationType) = modificationData
changesListener.onFileChange(path, modificationStamp, modificationType)
}
changesListener.apply()
}
}
}
private data class ModificationData(val modificationStamp: Long, val modificationType: ExternalSystemModificationType)
companion object {
@JvmStatic
fun subscribeOnDocumentsAndVirtualFilesChanges(
filesProvider: AsyncSupplier<Set<String>>,
listener: FilesChangesListener,
parentDisposable: Disposable
) {
subscribeOnVirtualFilesChanges(true, filesProvider, listener, parentDisposable)
subscribeOnDocumentsChanges(true, filesProvider, listener, parentDisposable)
}
@JvmStatic
fun subscribeOnVirtualFilesChanges(
isIgnoreInternalChanges: Boolean,
filesProvider: AsyncSupplier<Set<String>>,
listener: FilesChangesListener,
parentDisposable: Disposable
) {
val changesProvider = VirtualFilesChangesProvider(isIgnoreInternalChanges)
installAsyncVirtualFileListener(changesProvider, parentDisposable)
val asyncListener = AsyncFilesChangesListener(filesProvider, listener, parentDisposable)
changesProvider.subscribe(asyncListener, parentDisposable)
}
@JvmStatic
fun subscribeOnDocumentsChanges(
isIgnoreExternalChanges: Boolean,
filesProvider: AsyncSupplier<Set<String>>,
listener: FilesChangesListener,
parentDisposable: Disposable
) {
val changesProvider = DocumentsChangesProvider(isIgnoreExternalChanges)
val eventMulticaster = EditorFactory.getInstance().eventMulticaster
eventMulticaster.addDocumentListener(changesProvider, parentDisposable)
val asyncListener = AsyncFilesChangesListener(filesProvider, listener, parentDisposable)
changesProvider.subscribe(asyncListener, parentDisposable)
}
}
} | platform/external-system-impl/src/com/intellij/openapi/externalSystem/autoimport/changes/AsyncFilesChangesListener.kt | 2459304175 |
// 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.debugger.test.mock
import com.intellij.debugger.SourcePosition
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
class MockSourcePosition(
private val myFile: PsiFile? = null,
private val myElementAt: PsiElement? = null,
private val myLine: Int? = null,
private val myOffset: Int? = null,
private val myEditor: Editor? = null
) : SourcePosition() {
override fun getFile(): PsiFile {
return myFile ?: throw UnsupportedOperationException("Parameter file isn't set for MockSourcePosition")
}
override fun getElementAt(): PsiElement {
return myElementAt ?: throw UnsupportedOperationException("Parameter elementAt isn't set for MockSourcePosition")
}
override fun getLine(): Int {
return myLine ?: throw UnsupportedOperationException("Parameter line isn't set for MockSourcePosition")
}
override fun getOffset(): Int {
return myOffset ?: throw UnsupportedOperationException("Parameter offset isn't set for MockSourcePosition")
}
override fun openEditor(requestFocus: Boolean): Editor {
return myEditor ?: throw UnsupportedOperationException("Parameter editor isn't set for MockSourcePosition")
}
override fun navigate(requestFocus: Boolean) {
throw UnsupportedOperationException("navigate() isn't supported for MockSourcePosition")
}
override fun canNavigate(): Boolean {
throw UnsupportedOperationException("canNavigate() isn't supported for MockSourcePosition")
}
override fun canNavigateToSource(): Boolean {
throw UnsupportedOperationException("canNavigateToSource() isn't supported for MockSourcePosition")
}
}
| plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/mock/MockSourcePosition.kt | 600111190 |
// "Create label foo@" "true"
fun test() {
while (true) {
while (true) {
break@<caret>foo
}
}
} | plugins/kotlin/idea/tests/testData/quickfix/createLabel/breakInOuterLoop.kt | 271111788 |
/*
* Copyright 2000-2021 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.teamcity.aad
interface AADAccessTokenFactory {
fun create() : String
} | azure-active-directory-server/src/main/kotlin/org/jetbrains/teamcity/aad/AADAccessTokenFactory.kt | 3567292132 |
// 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.mlCompletion
import com.intellij.internal.ml.catboost.CatBoostJarCompletionModelProvider
import com.intellij.internal.ml.completion.DecoratingItemsPolicy
import com.intellij.lang.Language
class KotlinMLRankingProvider : CatBoostJarCompletionModelProvider(
KotlinMlCompletionBundle.message("kotlin.ml.completion.model"),
"kotlin_features",
"kotlin_model"
) {
override fun isLanguageSupported(language: Language): Boolean = language.id.equals("kotlin", ignoreCase = true)
override fun isEnabledByDefault(): Boolean = true
override fun getDecoratingPolicy(): DecoratingItemsPolicy = DecoratingItemsPolicy.Composite(
DecoratingItemsPolicy.ByAbsoluteThreshold(3.0),
DecoratingItemsPolicy.ByRelativeThreshold(2.0)
)
} | plugins/kotlin/ml-completion/src/org/jetbrains/kotlin/idea/mlCompletion/KotlinMLRankingProvider.kt | 3916131893 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.navbar.vm
import com.intellij.ide.navbar.NavBarItemPresentation
import kotlinx.coroutines.flow.StateFlow
interface NavBarItemVm {
val presentation: NavBarItemPresentation
val isModuleContentRoot: Boolean
val isFirst: Boolean
val isLast: Boolean
val selected: StateFlow<Boolean>
fun isNextSelected(): Boolean
fun isInactive(): Boolean
fun select()
fun showPopup()
fun activate()
}
| platform/lang-impl/src/com/intellij/ide/navbar/vm/NavBarItemVm.kt | 673300571 |
// IS_APPLICABLE: false
fun test(x: Int) {
when (x) {
0 -> {
foo()
}<caret>
else -> bar()
}
}
fun foo() {}
fun bar() {}
fun baz() {}
| plugins/kotlin/code-insight/intentions-shared/tests/testData/intentions/removeBracesFromAllBranches/oneLeft/whenEntry2.kt | 1938790991 |
package org.jetbrains.protocolModelGenerator
import org.jetbrains.jsonProtocol.ProtocolMetaModel
internal abstract class CreateStandaloneTypeBindingVisitorBase(private val generator: DomainGenerator, protected val type: ProtocolMetaModel.StandaloneType) : TypeVisitor<StandaloneTypeBinding> {
override fun visitString(): StandaloneTypeBinding {
return generator.createTypedefTypeBinding(type, PredefinedTarget.STRING, generator.generator.naming.commonTypedef, null)
}
override fun visitInteger() = generator.createTypedefTypeBinding(type, PredefinedTarget.INT, generator.generator.naming.commonTypedef, null)
override fun visitRef(refName: String) = throw RuntimeException()
override fun visitBoolean() = throw RuntimeException()
override fun visitNumber(): StandaloneTypeBinding {
return generator.createTypedefTypeBinding(type, PredefinedTarget.NUMBER, generator.generator.naming.commonTypedef, null)
}
override fun visitMap(): StandaloneTypeBinding {
return generator.createTypedefTypeBinding(type, PredefinedTarget.MAP, generator.generator.naming.commonTypedef, null)
}
override fun visitUnknown(): StandaloneTypeBinding {
throw RuntimeException()
}
}
| platform/script-debugger/protocol/protocol-model-generator/src/CreateStandaloneTypeBindingVisitorBase.kt | 2427594998 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.changeSignature.ui
import com.intellij.psi.PsiElement
import com.intellij.refactoring.changeSignature.ParameterTableModelItemBase
import com.intellij.ui.BooleanTableCellEditor
import com.intellij.ui.BooleanTableCellRenderer
import com.intellij.util.ui.ColumnInfo
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinMethodDescriptor
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinParameterInfo
import javax.swing.table.TableCellEditor
import javax.swing.table.TableCellRenderer
class KotlinFunctionParameterTableModel(
methodDescriptor: KotlinMethodDescriptor,
defaultValueContext: PsiElement
) : KotlinCallableParameterTableModel(
methodDescriptor,
defaultValueContext,
NameColumn<KotlinParameterInfo, ParameterTableModelItemBase<KotlinParameterInfo>>(defaultValueContext.project),
TypeColumn<KotlinParameterInfo, ParameterTableModelItemBase<KotlinParameterInfo>>(defaultValueContext.project, KotlinFileType.INSTANCE),
DefaultValueColumn<KotlinParameterInfo, ParameterTableModelItemBase<KotlinParameterInfo>>(
defaultValueContext.project,
KotlinFileType.INSTANCE
),
DefaultParameterColumn(),
ReceiverColumn(methodDescriptor),
) {
override fun removeRow(idx: Int) {
if (getRowValue(idx).parameter == receiver) {
receiver = null
}
super.removeRow(idx)
}
override var receiver: KotlinParameterInfo?
get() = (columnInfos[columnCount - 1] as ReceiverColumn).receiver
set(receiver) {
(columnInfos[columnCount - 1] as ReceiverColumn).receiver = receiver
}
private class ReceiverColumn(methodDescriptor: KotlinMethodDescriptor) :
ColumnInfoBase<KotlinParameterInfo, ParameterTableModelItemBase<KotlinParameterInfo>, Boolean>(KotlinBundle.message("column.name.receiver")) {
var receiver: KotlinParameterInfo? = methodDescriptor.receiver
override fun valueOf(item: ParameterTableModelItemBase<KotlinParameterInfo>): Boolean = item.parameter == receiver
override fun setValue(item: ParameterTableModelItemBase<KotlinParameterInfo>, value: Boolean?) {
if (value == null) return
receiver = if (value) item.parameter else null
}
override fun isCellEditable(pParameterTableModelItemBase: ParameterTableModelItemBase<KotlinParameterInfo>): Boolean = true
public override fun doCreateRenderer(item: ParameterTableModelItemBase<KotlinParameterInfo>): TableCellRenderer =
BooleanTableCellRenderer()
public override fun doCreateEditor(o: ParameterTableModelItemBase<KotlinParameterInfo>): TableCellEditor =
BooleanTableCellEditor()
}
companion object {
fun isReceiverColumn(column: ColumnInfo<*, *>?): Boolean = column is ReceiverColumn
}
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/ui/KotlinFunctionParameterTableModel.kt | 3133923748 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections.dfa
import com.intellij.codeInsight.Nullability
import com.intellij.codeInspection.dataFlow.TypeConstraint
import com.intellij.codeInspection.dataFlow.TypeConstraints
import com.intellij.codeInspection.dataFlow.interpreter.DataFlowInterpreter
import com.intellij.codeInspection.dataFlow.java.inst.*
import com.intellij.codeInspection.dataFlow.jvm.SpecialField
import com.intellij.codeInspection.dataFlow.jvm.TrapTracker
import com.intellij.codeInspection.dataFlow.jvm.transfer.*
import com.intellij.codeInspection.dataFlow.jvm.transfer.TryCatchTrap.CatchClauseDescriptor
import com.intellij.codeInspection.dataFlow.lang.ir.*
import com.intellij.codeInspection.dataFlow.lang.ir.ControlFlow.ControlFlowOffset
import com.intellij.codeInspection.dataFlow.lang.ir.ControlFlow.DeferredOffset
import com.intellij.codeInspection.dataFlow.memory.DfaMemoryState
import com.intellij.codeInspection.dataFlow.rangeSet.LongRangeBinOp
import com.intellij.codeInspection.dataFlow.rangeSet.LongRangeSet
import com.intellij.codeInspection.dataFlow.types.*
import com.intellij.codeInspection.dataFlow.value.*
import com.intellij.codeInspection.dataFlow.value.DfaControlTransferValue.TransferTarget
import com.intellij.codeInspection.dataFlow.value.DfaControlTransferValue.Trap
import com.intellij.codeInspection.dataFlow.value.VariableDescriptor
import com.intellij.openapi.diagnostic.logger
import com.intellij.psi.*
import com.intellij.psi.tree.TokenSet
import com.intellij.psi.util.MethodSignatureUtil
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtil
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.FList
import com.siyeh.ig.psiutils.TypeUtils
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.getReturnTypeFromFunctionType
import org.jetbrains.kotlin.contracts.description.CallsEffectDeclaration
import org.jetbrains.kotlin.contracts.description.ContractProviderKey
import org.jetbrains.kotlin.contracts.description.EventOccurrencesRange
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.core.resolveType
import org.jetbrains.kotlin.idea.inspections.dfa.KotlinAnchor.*
import org.jetbrains.kotlin.idea.inspections.dfa.KotlinProblem.*
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.targetLoop
import org.jetbrains.kotlin.idea.project.builtIns
import org.jetbrains.kotlin.idea.refactoring.move.moveMethod.type
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClass
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getAbbreviatedTypeOrType
import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunction
import org.jetbrains.kotlin.resolve.calls.model.ExpressionValueArgument
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.VarargValueArgument
import org.jetbrains.kotlin.resolve.constants.IntegerLiteralTypeConstructor
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.*
import org.jetbrains.kotlin.utils.addIfNotNull
import java.util.concurrent.ConcurrentHashMap
class KtControlFlowBuilder(val factory: DfaValueFactory, val context: KtExpression) {
private val flow = ControlFlow(factory, context)
private var broken: Boolean = false
private val trapTracker = TrapTracker(factory, context)
private val stringType = PsiType.getJavaLangString(context.manager, context.resolveScope)
fun buildFlow(): ControlFlow? {
processExpression(context)
if (broken) return null
addInstruction(PopInstruction()) // return value
flow.finish()
return flow
}
private fun processExpression(expr: KtExpression?) {
flow.startElement(expr)
when (expr) {
null -> pushUnknown()
is KtBlockExpression -> processBlock(expr)
is KtParenthesizedExpression -> processExpression(expr.expression)
is KtBinaryExpression -> processBinaryExpression(expr)
is KtBinaryExpressionWithTypeRHS -> processAsExpression(expr)
is KtPrefixExpression -> processPrefixExpression(expr)
is KtPostfixExpression -> processPostfixExpression(expr)
is KtIsExpression -> processIsExpression(expr)
is KtCallExpression -> processCallExpression(expr)
is KtConstantExpression -> processConstantExpression(expr)
is KtSimpleNameExpression -> processReferenceExpression(expr)
is KtDotQualifiedExpression -> processQualifiedReferenceExpression(expr)
is KtSafeQualifiedExpression -> processQualifiedReferenceExpression(expr)
is KtReturnExpression -> processReturnExpression(expr)
is KtContinueExpression -> processLabeledJumpExpression(expr)
is KtBreakExpression -> processLabeledJumpExpression(expr)
is KtThrowExpression -> processThrowExpression(expr)
is KtIfExpression -> processIfExpression(expr)
is KtWhenExpression -> processWhenExpression(expr)
is KtWhileExpression -> processWhileExpression(expr)
is KtDoWhileExpression -> processDoWhileExpression(expr)
is KtForExpression -> processForExpression(expr)
is KtProperty -> processDeclaration(expr)
is KtLambdaExpression -> processLambda(expr)
is KtStringTemplateExpression -> processStringTemplate(expr)
is KtArrayAccessExpression -> processArrayAccess(expr)
is KtAnnotatedExpression -> processExpression(expr.baseExpression)
is KtClassLiteralExpression -> processClassLiteralExpression(expr)
is KtLabeledExpression -> processExpression(expr.baseExpression)
is KtThisExpression -> processThisExpression(expr)
is KtSuperExpression -> pushUnknown()
is KtCallableReferenceExpression -> processCallableReference(expr)
is KtTryExpression -> processTryExpression(expr)
is KtDestructuringDeclaration -> processDestructuringDeclaration(expr)
is KtObjectLiteralExpression -> processObjectLiteral(expr)
is KtNamedFunction -> processCodeDeclaration(expr)
is KtClass -> processCodeDeclaration(expr)
else -> {
// unsupported construct
if (LOG.isDebugEnabled) {
val className = expr.javaClass.name
if (unsupported.add(className)) {
LOG.debug("Unsupported expression in control flow: $className")
}
}
broken = true
}
}
flow.finishElement(expr)
}
private fun processCodeDeclaration(expr: KtExpression) {
processEscapes(expr)
pushUnknown()
}
private fun processObjectLiteral(expr: KtObjectLiteralExpression) {
processEscapes(expr)
for (superTypeListEntry in expr.objectDeclaration.superTypeListEntries) {
if (superTypeListEntry is KtSuperTypeCallEntry) {
// super-constructor call: may be impure
addInstruction(FlushFieldsInstruction())
}
}
val dfType = expr.getKotlinType().toDfType(expr)
addInstruction(PushValueInstruction(dfType, KotlinExpressionAnchor(expr)))
}
private fun processDestructuringDeclaration(expr: KtDestructuringDeclaration) {
processExpression(expr.initializer)
for (entry in expr.entries) {
addInstruction(FlushVariableInstruction(factory.varFactory.createVariableValue(KtVariableDescriptor(entry))))
}
}
data class KotlinCatchClauseDescriptor(val clause : KtCatchClause): CatchClauseDescriptor {
override fun parameter(): VariableDescriptor? {
val parameter = clause.catchParameter ?: return null
return KtVariableDescriptor(parameter)
}
override fun constraints(): MutableList<TypeConstraint> {
val parameter = clause.catchParameter ?: return mutableListOf()
return mutableListOf(TypeConstraint.fromDfType(parameter.type().toDfType(clause)))
}
}
private fun processTryExpression(statement: KtTryExpression) {
inlinedBlock(statement) {
val tryBlock = statement.tryBlock
val finallyBlock = statement.finallyBlock
val finallyStart = DeferredOffset()
val finallyDescriptor = if (finallyBlock != null) EnterFinallyTrap(finallyBlock, finallyStart) else null
finallyDescriptor?.let { trapTracker.pushTrap(it) }
val tempVar = flow.createTempVariable(DfType.TOP)
val sections = statement.catchClauses
val clauses = LinkedHashMap<CatchClauseDescriptor, DeferredOffset>()
if (sections.isNotEmpty()) {
for (section in sections) {
val catchBlock = section.catchBody
if (catchBlock != null) {
clauses[KotlinCatchClauseDescriptor(section)] = DeferredOffset()
}
}
trapTracker.pushTrap(TryCatchTrap(statement, clauses))
}
processExpression(tryBlock)
addInstruction(JvmAssignmentInstruction(null, tempVar))
val gotoEnd = createTransfer(statement, tryBlock, tempVar, true)
val singleFinally = FList.createFromReversed<Trap>(ContainerUtil.createMaybeSingletonList(finallyDescriptor))
controlTransfer(gotoEnd, singleFinally)
if (sections.isNotEmpty()) {
trapTracker.popTrap(TryCatchTrap::class.java)
}
for (section in sections) {
val offset = clauses[KotlinCatchClauseDescriptor(section)]
if (offset == null) continue
setOffset(offset)
val catchBlock = section.catchBody
processExpression(catchBlock)
addInstruction(JvmAssignmentInstruction(null, tempVar))
controlTransfer(gotoEnd, singleFinally)
}
if (finallyBlock != null) {
setOffset(finallyStart)
trapTracker.popTrap(EnterFinallyTrap::class.java)
trapTracker.pushTrap(InsideFinallyTrap(finallyBlock))
processExpression(finallyBlock.finalExpression)
addInstruction(PopInstruction())
controlTransfer(ExitFinallyTransfer(finallyDescriptor!!), FList.emptyList())
trapTracker.popTrap(InsideFinallyTrap::class.java)
}
}
}
private fun processCallableReference(expr: KtCallableReferenceExpression) {
processExpression(expr.receiverExpression)
addInstruction(KotlinCallableReferenceInstruction(expr))
}
private fun processThisExpression(expr: KtThisExpression) {
val exprType = expr.getKotlinType()
val bindingContext = expr.safeAnalyzeNonSourceRootCode(BodyResolveMode.FULL)
// Might differ from expression type if smartcast occurred
val thisType = bindingContext[BindingContext.EXPRESSION_TYPE_INFO, expr.instanceReference]?.type
val dfType = thisType.toDfType(expr)
val descriptor = bindingContext[BindingContext.REFERENCE_TARGET, expr.instanceReference]
if (descriptor != null) {
val varDesc = KtThisDescriptor(descriptor, dfType)
addInstruction(JvmPushInstruction(factory.varFactory.createVariableValue(varDesc), KotlinExpressionAnchor(expr)))
addImplicitConversion(expr, thisType, exprType)
} else {
addInstruction(PushValueInstruction(dfType, KotlinExpressionAnchor(expr)))
}
}
private fun processClassLiteralExpression(expr: KtClassLiteralExpression) {
val kotlinType = expr.getKotlinType()
val receiver = expr.receiverExpression
if (kotlinType != null) {
if (receiver is KtSimpleNameExpression && receiver.mainReference.resolve() is KtClass) {
val arguments = kotlinType.arguments
if (arguments.size == 1) {
val kType = arguments[0].type
val kClassPsiType = kotlinType.toPsiType(expr)
if (kClassPsiType != null) {
val kClassConstant: DfType = DfTypes.referenceConstant(kType, kClassPsiType)
addInstruction(PushValueInstruction(kClassConstant, KotlinExpressionAnchor(expr)))
return
}
}
}
}
processExpression(receiver)
addInstruction(PopInstruction())
addInstruction(PushValueInstruction(kotlinType.toDfType(expr)))
// TODO: support kotlin-class as a variable; link to TypeConstraint
}
private fun processAsExpression(expr: KtBinaryExpressionWithTypeRHS) {
val operand = expr.left
val typeReference = expr.right
val type = getTypeCheckDfType(typeReference)
val ref = expr.operationReference
if (ref.text != "as?" && ref.text != "as") {
broken = true
return
}
processExpression(operand)
val operandType = operand.getKotlinType()
if (operandType.toDfType(expr) is DfPrimitiveType) {
addInstruction(WrapDerivedVariableInstruction(DfTypes.NOT_NULL_OBJECT, SpecialField.UNBOX))
}
if (ref.text == "as?") {
val tempVariable: DfaVariableValue = flow.createTempVariable(DfTypes.OBJECT_OR_NULL)
addInstruction(JvmAssignmentInstruction(null, tempVariable))
addInstruction(PushValueInstruction(type, null))
addInstruction(InstanceofInstruction(null, false))
val offset = DeferredOffset()
addInstruction(ConditionalGotoInstruction(offset, DfTypes.FALSE))
val anchor = KotlinExpressionAnchor(expr)
addInstruction(JvmPushInstruction(tempVariable, anchor))
val endOffset = DeferredOffset()
addInstruction(GotoInstruction(endOffset))
setOffset(offset)
addInstruction(PushValueInstruction(DfTypes.NULL, anchor))
setOffset(endOffset)
} else {
val transfer = trapTracker.maybeTransferValue("java.lang.ClassCastException")
addInstruction(EnsureInstruction(KotlinCastProblem(operand, expr), RelationType.IS, type, transfer))
if (typeReference != null) {
val castType = typeReference.getAbbreviatedTypeOrType(typeReference.safeAnalyzeNonSourceRootCode(BodyResolveMode.FULL))
if (castType.toDfType(typeReference) is DfPrimitiveType) {
addInstruction(UnwrapDerivedVariableInstruction(SpecialField.UNBOX))
}
}
}
}
private fun processArrayAccess(expr: KtArrayAccessExpression, storedValue: KtExpression? = null) {
val arrayExpression = expr.arrayExpression
processExpression(arrayExpression)
val kotlinType = arrayExpression?.getKotlinType()
var curType = kotlinType
val indexes = expr.indexExpressions
for (idx in indexes) {
processExpression(idx)
val lastIndex = idx == indexes.last()
val anchor = if (lastIndex) KotlinExpressionAnchor(expr) else null
val expectedType = if (lastIndex) expr.getKotlinType()?.toDfType(expr) ?: DfType.TOP else DfType.TOP
var indexType = idx.getKotlinType()
val constructor = indexType?.constructor as? IntegerLiteralTypeConstructor
if (constructor != null) {
indexType = constructor.getApproximatedType()
}
if (indexType == null || !indexType.fqNameEquals("kotlin.Int")) {
if (lastIndex && storedValue != null) {
processExpression(storedValue)
addInstruction(PopInstruction())
}
addInstruction(EvalUnknownInstruction(anchor, 2, expectedType))
addInstruction(FlushFieldsInstruction())
continue
}
if (curType != null && KotlinBuiltIns.isArrayOrPrimitiveArray(curType)) {
if (indexType.canBeNull()) {
addInstruction(UnwrapDerivedVariableInstruction(SpecialField.UNBOX))
}
val transfer = trapTracker.maybeTransferValue("java.lang.ArrayIndexOutOfBoundsException")
val elementType = expr.builtIns.getArrayElementType(curType)
if (lastIndex && storedValue != null) {
processExpression(storedValue)
addImplicitConversion(storedValue, storedValue.getKotlinType(), curType.getArrayElementType(expr))
addInstruction(ArrayStoreInstruction(anchor, KotlinArrayIndexProblem(SpecialField.ARRAY_LENGTH, idx), transfer, null))
} else {
addInstruction(ArrayAccessInstruction(anchor, KotlinArrayIndexProblem(SpecialField.ARRAY_LENGTH, idx), transfer, null))
addImplicitConversion(expr, curType.getArrayElementType(expr), elementType)
}
curType = elementType
} else {
if (KotlinBuiltIns.isString(kotlinType)) {
if (indexType.canBeNull()) {
addInstruction(UnwrapDerivedVariableInstruction(SpecialField.UNBOX))
}
val transfer = trapTracker.maybeTransferValue("java.lang.StringIndexOutOfBoundsException")
addInstruction(EnsureIndexInBoundsInstruction(KotlinArrayIndexProblem(SpecialField.STRING_LENGTH, idx), transfer))
if (lastIndex && storedValue != null) {
processExpression(storedValue)
addInstruction(PopInstruction())
}
addInstruction(PushValueInstruction(DfTypes.typedObject(PsiType.CHAR, Nullability.UNKNOWN), anchor))
} else if (kotlinType != null && (KotlinBuiltIns.isListOrNullableList(kotlinType) ||
kotlinType.supertypes().any { type -> KotlinBuiltIns.isListOrNullableList(type) })) {
if (indexType.canBeNull()) {
addInstruction(UnwrapDerivedVariableInstruction(SpecialField.UNBOX))
}
val transfer = trapTracker.maybeTransferValue("java.lang.IndexOutOfBoundsException")
addInstruction(EnsureIndexInBoundsInstruction(KotlinArrayIndexProblem(SpecialField.COLLECTION_SIZE, idx), transfer))
if (lastIndex && storedValue != null) {
processExpression(storedValue)
addInstruction(PopInstruction())
}
pushUnknown()
} else {
if (lastIndex && storedValue != null) {
processExpression(storedValue)
addInstruction(PopInstruction())
}
addInstruction(EvalUnknownInstruction(anchor, 2, expectedType))
addInstruction(FlushFieldsInstruction())
}
}
}
}
private fun processIsExpression(expr: KtIsExpression) {
processExpression(expr.leftHandSide)
val type = getTypeCheckDfType(expr.typeReference)
if (type == DfType.TOP) {
pushUnknown()
} else {
addInstruction(PushValueInstruction(type))
if (expr.isNegated) {
addInstruction(InstanceofInstruction(null, false))
addInstruction(NotInstruction(KotlinExpressionAnchor(expr)))
} else {
addInstruction(InstanceofInstruction(KotlinExpressionAnchor(expr), false))
}
}
}
private fun processStringTemplate(expr: KtStringTemplateExpression) {
var first = true
val entries = expr.entries
if (entries.isEmpty()) {
addInstruction(PushValueInstruction(DfTypes.constant("", stringType)))
return
}
val lastEntry = entries.last()
for (entry in entries) {
when (entry) {
is KtEscapeStringTemplateEntry ->
addInstruction(PushValueInstruction(DfTypes.constant(entry.unescapedValue, stringType)))
is KtLiteralStringTemplateEntry ->
addInstruction(PushValueInstruction(DfTypes.constant(entry.text, stringType)))
is KtStringTemplateEntryWithExpression ->
processExpression(entry.expression)
else ->
pushUnknown()
}
if (!first) {
val anchor = if (entry == lastEntry) KotlinExpressionAnchor(expr) else null
addInstruction(StringConcatInstruction(anchor, stringType))
}
first = false
}
if (entries.size == 1 && entries[0] !is KtLiteralStringTemplateEntry) {
// Implicit toString conversion for "$myVar" string
addInstruction(PushValueInstruction(DfTypes.constant("", stringType)))
addInstruction(StringConcatInstruction(KotlinExpressionAnchor(expr), stringType))
}
}
private fun processLambda(expr: KtLambdaExpression) {
val element = expr.bodyExpression
if (element != null) {
processEscapes(element)
addInstruction(ClosureInstruction(listOf(element)))
}
pushUnknown()
}
private fun processEscapes(expr: KtExpression) {
val vars = mutableSetOf<DfaVariableValue>()
val existingVars = factory.values.asSequence()
.filterIsInstance<DfaVariableValue>()
.filter { v -> v.qualifier == null }
.map { v -> v.descriptor }
.filterIsInstance<KtVariableDescriptor>()
.map { v -> v.variable }
.toSet()
PsiTreeUtil.processElements(expr, KtSimpleNameExpression::class.java) { ref ->
val target = ref.mainReference.resolve()
if (target != null && existingVars.contains(target)) {
vars.addIfNotNull(KtVariableDescriptor.createFromSimpleName(factory, ref))
}
return@processElements true
}
if (vars.isNotEmpty()) {
addInstruction(EscapeInstruction(vars))
}
}
private fun processCallExpression(expr: KtCallExpression, qualifierOnStack: Boolean = false) {
val call = expr.resolveToCall()
var argCount: Int
if (call != null) {
argCount = pushResolvedCallArguments(call, expr)
} else {
argCount = pushUnresolvedCallArguments(expr)
}
if (inlineKnownMethod(expr, argCount, qualifierOnStack)) return
val lambda = getInlineableLambda(expr)
if (lambda != null) {
if (qualifierOnStack && inlineKnownLambdaCall(expr, lambda.lambda)) return
val kind = getLambdaOccurrenceRange(expr, lambda.descriptor.original)
inlineLambda(lambda.lambda, kind)
} else {
for (lambdaArg in expr.lambdaArguments) {
processExpression(lambdaArg.getLambdaExpression())
argCount++
}
}
addCall(expr, argCount, qualifierOnStack)
}
private fun pushUnresolvedCallArguments(expr: KtCallExpression): Int {
val args = expr.valueArgumentList?.arguments
var argCount = 0
if (args != null) {
for (arg: KtValueArgument in args) {
val argExpr = arg.getArgumentExpression()
if (argExpr != null) {
processExpression(argExpr)
argCount++
}
}
}
return argCount
}
private fun pushResolvedCallArguments(call: ResolvedCall<out CallableDescriptor>, expr: KtCallExpression): Int {
val valueArguments = call.valueArguments
var argCount = 0
for ((descriptor, valueArg) in valueArguments) {
when (valueArg) {
is VarargValueArgument -> {
val arguments = valueArg.arguments
val singleArg = arguments.singleOrNull()
if (singleArg?.getSpreadElement() != null) {
processExpression(singleArg.getArgumentExpression())
} else {
for (arg in arguments) {
processExpression(arg.getArgumentExpression())
}
addInstruction(FoldArrayInstruction(null, descriptor.type.toDfType(expr), arguments.size))
}
argCount++
}
is ExpressionValueArgument -> {
val valueArgument = valueArg.valueArgument
if (valueArgument !is KtLambdaArgument) {
processExpression(valueArgument?.getArgumentExpression())
argCount++
}
}
else -> {
pushUnknown()
argCount++
}
}
}
return argCount
}
private fun inlineKnownMethod(expr: KtCallExpression, argCount: Int, qualifierOnStack: Boolean): Boolean {
if (argCount == 0 && qualifierOnStack) {
val descriptor = expr.resolveToCall()?.resultingDescriptor ?: return false
val name = descriptor.name.asString()
if (name == "isEmpty" || name == "isNotEmpty") {
val containingDeclaration = descriptor.containingDeclaration
val containingPackage = if (containingDeclaration is PackageFragmentDescriptor) containingDeclaration.fqName
else (containingDeclaration as? ClassDescriptor)?.containingPackage()
if (containingPackage?.asString() == "kotlin.collections") {
addInstruction(UnwrapDerivedVariableInstruction(SpecialField.COLLECTION_SIZE))
addInstruction(PushValueInstruction(DfTypes.intValue(0)))
addInstruction(
BooleanBinaryInstruction(
if (name == "isEmpty") RelationType.EQ else RelationType.NE, false,
KotlinExpressionAnchor(expr)
)
)
val kotlinType = expr.getKotlinType()
if (kotlinType?.isMarkedNullable == true) {
addInstruction(WrapDerivedVariableInstruction(kotlinType.toDfType(expr), SpecialField.UNBOX))
}
return true
}
}
}
return false
}
private fun inlineKnownLambdaCall(expr: KtCallExpression, lambda: KtLambdaExpression): Boolean {
// TODO: this-binding methods (apply, run)
// TODO: non-qualified methods (run, repeat)
// TODO: collection methods (forEach, map, etc.)
val resolvedCall = expr.resolveToCall() ?: return false
val descriptor = resolvedCall.resultingDescriptor
val packageFragment = descriptor.containingDeclaration as? PackageFragmentDescriptor ?: return false
val bodyExpression = lambda.bodyExpression
val receiver = (expr.parent as? KtQualifiedExpression)?.receiverExpression
if (packageFragment.fqName.asString() == "kotlin" && resolvedCall.valueArguments.size == 1) {
val name = descriptor.name.asString()
if (name == "let" || name == "also" || name == "takeIf" || name == "takeUnless") {
val parameter = KtVariableDescriptor.getSingleLambdaParameter(factory, lambda) ?: return false
// qualifier is on stack
val receiverType = receiver?.getKotlinType()
val argType = if (expr.parent is KtSafeQualifiedExpression) receiverType?.makeNotNullable() else receiverType
addImplicitConversion(receiver, argType)
addInstruction(JvmAssignmentInstruction(null, parameter))
when (name) {
"let" -> {
addInstruction(PopInstruction())
val lambdaResultType = lambda.resolveType()?.getReturnTypeFromFunctionType()
val result = flow.createTempVariable(lambdaResultType.toDfType(expr))
inlinedBlock(lambda) {
processExpression(bodyExpression)
flow.finishElement(lambda.functionLiteral)
addInstruction(JvmAssignmentInstruction(null, result))
addInstruction(PopInstruction())
}
addInstruction(JvmPushInstruction(result, null))
addImplicitConversion(expr, lambdaResultType, expr.getKotlinType())
}
"also" -> {
inlinedBlock(lambda) {
processExpression(bodyExpression)
flow.finishElement(lambda.functionLiteral)
addInstruction(PopInstruction())
}
addImplicitConversion(receiver, argType, expr.getKotlinType())
addInstruction(ResultOfInstruction(KotlinExpressionAnchor(expr)))
}
"takeIf", "takeUnless" -> {
val result = flow.createTempVariable(DfTypes.BOOLEAN)
inlinedBlock(lambda) {
processExpression(bodyExpression)
flow.finishElement(lambda.functionLiteral)
addInstruction(JvmAssignmentInstruction(null, result))
addInstruction(PopInstruction())
}
addInstruction(JvmPushInstruction(result, null))
val offset = DeferredOffset()
addInstruction(ConditionalGotoInstruction(offset, DfTypes.booleanValue(name == "takeIf")))
addInstruction(PopInstruction())
addInstruction(PushValueInstruction(DfTypes.NULL))
val endOffset = DeferredOffset()
addInstruction(GotoInstruction(endOffset))
setOffset(offset)
addImplicitConversion(receiver, argType, expr.getKotlinType())
setOffset(endOffset)
}
}
addInstruction(ResultOfInstruction(KotlinExpressionAnchor(expr)))
return true
}
}
return false
}
private fun getLambdaOccurrenceRange(expr: KtCallExpression, descriptor: ValueParameterDescriptor): EventOccurrencesRange {
val contractDescription = expr.resolveToCall()?.resultingDescriptor?.getUserData(ContractProviderKey)?.getContractDescription()
if (contractDescription != null) {
val callEffect = contractDescription.effects
.singleOrNull { e -> e is CallsEffectDeclaration && e.variableReference.descriptor == descriptor }
as? CallsEffectDeclaration
if (callEffect != null) {
return callEffect.kind
}
}
return EventOccurrencesRange.UNKNOWN
}
private fun inlineLambda(lambda: KtLambdaExpression, kind: EventOccurrencesRange) {
/*
We encode unknown call with inlineable lambda as
unknownCode()
while(condition1) {
if(condition2) {
lambda()
}
unknownCode()
}
*/
addInstruction(FlushFieldsInstruction())
val offset = ControlFlow.FixedOffset(flow.instructionCount)
val endOffset = DeferredOffset()
if (kind != EventOccurrencesRange.EXACTLY_ONCE && kind != EventOccurrencesRange.MORE_THAN_ONCE &&
kind != EventOccurrencesRange.AT_LEAST_ONCE) {
pushUnknown()
addInstruction(ConditionalGotoInstruction(endOffset, DfTypes.TRUE))
}
inlinedBlock(lambda) {
val functionLiteral = lambda.functionLiteral
val bodyExpression = lambda.bodyExpression
if (bodyExpression != null) {
val singleParameter = KtVariableDescriptor.getSingleLambdaParameter(factory, lambda)
if (singleParameter != null) {
addInstruction(FlushVariableInstruction(singleParameter))
} else {
for (parameter in lambda.valueParameters) {
flushParameter(parameter)
}
}
}
processExpression(bodyExpression)
flow.finishElement(functionLiteral)
addInstruction(PopInstruction())
}
setOffset(endOffset)
addInstruction(FlushFieldsInstruction())
if (kind != EventOccurrencesRange.AT_MOST_ONCE && kind != EventOccurrencesRange.EXACTLY_ONCE) {
pushUnknown()
addInstruction(ConditionalGotoInstruction(offset, DfTypes.TRUE))
}
}
private inline fun inlinedBlock(element: KtElement, fn : () -> Unit) {
// Transfer value is pushed to avoid emptying stack beyond this point
trapTracker.pushTrap(InsideInlinedBlockTrap(element))
addInstruction(JvmPushInstruction(factory.controlTransfer(DfaControlTransferValue.RETURN_TRANSFER, FList.emptyList()), null))
fn()
trapTracker.popTrap(InsideInlinedBlockTrap::class.java)
// Pop transfer value
addInstruction(PopInstruction())
}
private fun addCall(expr: KtExpression, args: Int, qualifierOnStack: Boolean = false) {
val transfer = trapTracker.maybeTransferValue(CommonClassNames.JAVA_LANG_THROWABLE)
addInstruction(KotlinFunctionCallInstruction(expr, args, qualifierOnStack, transfer))
}
private fun processQualifiedReferenceExpression(expr: KtQualifiedExpression) {
val receiver = expr.receiverExpression
processExpression(receiver)
val offset = DeferredOffset()
if (expr is KtSafeQualifiedExpression) {
addInstruction(DupInstruction())
addInstruction(ConditionalGotoInstruction(offset, DfTypes.NULL))
}
val selector = expr.selectorExpression
if (!pushJavaClassField(receiver, selector, expr)) {
val specialField = findSpecialField(expr)
if (specialField != null) {
addInstruction(UnwrapDerivedVariableInstruction(specialField))
if (expr is KtSafeQualifiedExpression) {
addInstruction(WrapDerivedVariableInstruction(expr.getKotlinType().toDfType(expr), SpecialField.UNBOX))
}
} else {
when (selector) {
is KtCallExpression -> processCallExpression(selector, true)
is KtSimpleNameExpression -> processReferenceExpression(selector, true)
else -> {
addInstruction(PopInstruction())
processExpression(selector)
}
}
}
addInstruction(ResultOfInstruction(KotlinExpressionAnchor(expr)))
}
if (expr is KtSafeQualifiedExpression) {
val endOffset = DeferredOffset()
addInstruction(GotoInstruction(endOffset))
setOffset(offset)
addInstruction(PopInstruction())
addInstruction(PushValueInstruction(DfTypes.NULL, KotlinExpressionAnchor(expr)))
setOffset(endOffset)
}
}
private fun pushJavaClassField(receiver: KtExpression, selector: KtExpression?, expr: KtQualifiedExpression): Boolean {
if (selector == null || !selector.textMatches("java")) return false
if (!receiver.getKotlinType().fqNameEquals("kotlin.reflect.KClass")) return false
val kotlinType = expr.getKotlinType() ?: return false
val classPsiType = kotlinType.toPsiType(expr) ?: return false
if (!classPsiType.equalsToText(CommonClassNames.JAVA_LANG_CLASS)) return false
addInstruction(KotlinClassToJavaClassInstruction(KotlinExpressionAnchor(expr), classPsiType))
return true
}
private fun findSpecialField(type: KotlinType?): SpecialField? {
type ?: return null
return when {
type.isEnum() -> SpecialField.ENUM_ORDINAL
KotlinBuiltIns.isArray(type) || KotlinBuiltIns.isPrimitiveArray(type) -> SpecialField.ARRAY_LENGTH
KotlinBuiltIns.isCollectionOrNullableCollection(type) ||
KotlinBuiltIns.isMapOrNullableMap(type) ||
type.supertypes().any { st -> KotlinBuiltIns.isCollectionOrNullableCollection(st) || KotlinBuiltIns.isMapOrNullableMap(st)}
-> SpecialField.COLLECTION_SIZE
KotlinBuiltIns.isStringOrNullableString(type) -> SpecialField.STRING_LENGTH
else -> null
}
}
private fun findSpecialField(expr: KtQualifiedExpression): SpecialField? {
val selector = expr.selectorExpression ?: return null
val receiver = expr.receiverExpression
val selectorText = selector.text
if (selectorText != "size" && selectorText != "length" && selectorText != "ordinal") return null
val field = findSpecialField(receiver.getKotlinType()) ?: return null
val expectedFieldName = if (field == SpecialField.ARRAY_LENGTH) "size" else field.toString()
if (selectorText != expectedFieldName) return null
return field
}
private fun processPrefixExpression(expr: KtPrefixExpression) {
val operand = expr.baseExpression
processExpression(operand)
val anchor = KotlinExpressionAnchor(expr)
if (operand != null) {
val dfType = operand.getKotlinType().toDfType(expr)
val dfVar = KtVariableDescriptor.createFromQualified(factory, operand)
val ref = expr.operationReference.text
if (dfType is DfIntegralType) {
when (ref) {
"++", "--" -> {
if (dfVar != null) {
addInstruction(PushValueInstruction(dfType.meetRange(LongRangeSet.point(1))))
addInstruction(NumericBinaryInstruction(if (ref == "++") LongRangeBinOp.PLUS else LongRangeBinOp.MINUS, null))
addInstruction(JvmAssignmentInstruction(anchor, dfVar))
return
}
}
"+" -> {
return
}
"-" -> {
addInstruction(PushValueInstruction(dfType.meetRange(LongRangeSet.point(0))))
addInstruction(SwapInstruction())
addInstruction(NumericBinaryInstruction(LongRangeBinOp.MINUS, anchor))
return
}
}
}
if (dfType is DfBooleanType && ref == "!") {
addInstruction(NotInstruction(anchor))
return
}
if (dfVar != null && (ref == "++" || ref == "--")) {
// Custom inc/dec may update the variable
addInstruction(FlushVariableInstruction(dfVar))
}
}
addInstruction(EvalUnknownInstruction(anchor, 1, expr.getKotlinType()?.toDfType(expr) ?: DfType.TOP))
}
private fun processPostfixExpression(expr: KtPostfixExpression) {
val operand = expr.baseExpression
processExpression(operand)
val anchor = KotlinExpressionAnchor(expr)
val ref = expr.operationReference.text
if (ref == "++" || ref == "--") {
if (operand != null) {
val dfType = operand.getKotlinType().toDfType(expr)
val dfVar = KtVariableDescriptor.createFromQualified(factory, operand)
if (dfVar != null) {
if (dfType is DfIntegralType) {
addInstruction(DupInstruction())
addInstruction(PushValueInstruction(dfType.meetRange(LongRangeSet.point(1))))
addInstruction(NumericBinaryInstruction(if (ref == "++") LongRangeBinOp.PLUS else LongRangeBinOp.MINUS, null))
addInstruction(JvmAssignmentInstruction(anchor, dfVar))
addInstruction(PopInstruction())
} else {
// Custom inc/dec may update the variable
addInstruction(FlushVariableInstruction(dfVar))
}
} else {
// Unknown value updated
addInstruction(FlushFieldsInstruction())
}
}
} else if (ref == "!!") {
val transfer: DfaControlTransferValue? = trapTracker.maybeTransferValue("java.lang.NullPointerException")
val operandType = operand?.getKotlinType()
if (operandType?.canBeNull() == true) {
addInstruction(EnsureInstruction(KotlinNullCheckProblem(expr), RelationType.NE, DfTypes.NULL, transfer))
// Probably unbox
addImplicitConversion(expr, operandType, expr.getKotlinType())
}
} else {
addInstruction(EvalUnknownInstruction(anchor, 1, expr.getKotlinType()?.toDfType(expr) ?: DfType.TOP))
}
}
private fun processDoWhileExpression(expr: KtDoWhileExpression) {
inlinedBlock(expr) {
val offset = ControlFlow.FixedOffset(flow.instructionCount)
processExpression(expr.body)
addInstruction(PopInstruction())
processExpression(expr.condition)
addInstruction(ConditionalGotoInstruction(offset, DfTypes.TRUE))
flow.finishElement(expr)
}
pushUnknown()
addInstruction(FinishElementInstruction(expr))
}
private fun processWhileExpression(expr: KtWhileExpression) {
inlinedBlock(expr) {
val startOffset = ControlFlow.FixedOffset(flow.instructionCount)
val condition = expr.condition
processExpression(condition)
val endOffset = DeferredOffset()
addInstruction(ConditionalGotoInstruction(endOffset, DfTypes.FALSE, condition))
processExpression(expr.body)
addInstruction(PopInstruction())
addInstruction(GotoInstruction(startOffset))
setOffset(endOffset)
flow.finishElement(expr)
}
pushUnknown()
addInstruction(FinishElementInstruction(expr))
}
private fun processForExpression(expr: KtForExpression) {
inlinedBlock(expr) {
val parameter = expr.loopParameter
if (parameter == null) {
broken = true
return@inlinedBlock
}
val parameterVar = factory.varFactory.createVariableValue(KtVariableDescriptor(parameter))
val parameterType = parameter.type()
val pushLoopCondition = processForRange(expr, parameterVar, parameterType)
val startOffset = ControlFlow.FixedOffset(flow.instructionCount)
val endOffset = DeferredOffset()
flushParameter(parameter)
pushLoopCondition()
addInstruction(ConditionalGotoInstruction(endOffset, DfTypes.FALSE))
processExpression(expr.body)
addInstruction(PopInstruction())
addInstruction(GotoInstruction(startOffset))
setOffset(endOffset)
flow.finishElement(expr)
}
pushUnknown()
addInstruction(FinishElementInstruction(expr))
}
private fun flushParameter(parameter: KtParameter) {
val destructuringDeclaration = parameter.destructuringDeclaration
if (destructuringDeclaration != null) {
for (entry in destructuringDeclaration.entries) {
addInstruction(FlushVariableInstruction(factory.varFactory.createVariableValue(KtVariableDescriptor(entry))))
}
} else {
addInstruction(FlushVariableInstruction(factory.varFactory.createVariableValue(KtVariableDescriptor(parameter))))
}
}
private fun processForRange(expr: KtForExpression, parameterVar: DfaVariableValue, parameterType: KotlinType?): () -> Unit {
val range = expr.loopRange
if (parameterVar.dfType is DfIntegralType) {
if (range is KtBinaryExpression) {
val ref = range.operationReference.text
val (leftRelation, rightRelation) = when(ref) {
".." -> RelationType.GE to RelationType.LE
"until" -> RelationType.GE to RelationType.LT
"downTo" -> RelationType.LE to RelationType.GE
else -> null to null
}
if (leftRelation != null && rightRelation != null) {
val left = range.left
val right = range.right
val leftType = left?.getKotlinType()
val rightType = right?.getKotlinType()
if (leftType.toDfType(range) is DfIntegralType && rightType.toDfType(range) is DfIntegralType) {
processExpression(left)
val leftVar = flow.createTempVariable(parameterVar.dfType)
addImplicitConversion(left, parameterType)
addInstruction(JvmAssignmentInstruction(null, leftVar))
addInstruction(PopInstruction())
processExpression(right)
val rightVar = flow.createTempVariable(parameterVar.dfType)
addImplicitConversion(right, parameterType)
addInstruction(JvmAssignmentInstruction(null, rightVar))
addInstruction(PopInstruction())
return {
val forAnchor = KotlinForVisitedAnchor(expr)
addInstruction(JvmPushInstruction(parameterVar, null))
addInstruction(JvmPushInstruction(leftVar, null))
addInstruction(BooleanBinaryInstruction(leftRelation, false, null))
val offset = DeferredOffset()
addInstruction(ConditionalGotoInstruction(offset, DfTypes.FALSE))
addInstruction(JvmPushInstruction(parameterVar, null))
addInstruction(JvmPushInstruction(rightVar, null))
addInstruction(BooleanBinaryInstruction(rightRelation, false, forAnchor))
val finalOffset = DeferredOffset()
addInstruction(GotoInstruction(finalOffset))
setOffset(offset)
addInstruction(PushValueInstruction(DfTypes.FALSE, forAnchor))
setOffset(finalOffset)
}
}
}
}
}
processExpression(range)
if (range != null) {
val kotlinType = range.getKotlinType()
val lengthField = findSpecialField(kotlinType)
if (lengthField != null) {
val collectionVar = flow.createTempVariable(kotlinType.toDfType(range))
addInstruction(JvmAssignmentInstruction(null, collectionVar))
addInstruction(PopInstruction())
return {
addInstruction(JvmPushInstruction(lengthField.createValue(factory, collectionVar), null))
addInstruction(PushValueInstruction(DfTypes.intValue(0)))
addInstruction(BooleanBinaryInstruction(RelationType.GT, false, null))
pushUnknown()
addInstruction(BooleanAndOrInstruction(false, KotlinForVisitedAnchor(expr)))
}
}
}
addInstruction(PopInstruction())
return { pushUnknown() }
}
private fun processBlock(expr: KtBlockExpression) {
val statements = expr.statements
if (statements.isEmpty()) {
pushUnknown()
} else {
for (child in statements) {
processExpression(child)
if (child != statements.last()) {
addInstruction(PopInstruction())
}
if (broken) return
}
addInstruction(FinishElementInstruction(expr))
}
}
private fun processDeclaration(variable: KtProperty) {
val initializer = variable.initializer
if (initializer == null) {
pushUnknown()
return
}
val dfaVariable = factory.varFactory.createVariableValue(KtVariableDescriptor(variable))
if (variable.isLocal && !variable.isVar && variable.type()?.isBoolean() == true) {
// Boolean true/false constant: do not track; might be used as a feature knob or explanatory variable
if (initializer.node?.elementType == KtNodeTypes.BOOLEAN_CONSTANT) {
pushUnknown()
return
}
}
processExpression(initializer)
addImplicitConversion(initializer, variable.type())
addInstruction(JvmAssignmentInstruction(KotlinExpressionAnchor(variable), dfaVariable))
}
private fun processReturnExpression(expr: KtReturnExpression) {
val returnedExpression = expr.returnedExpression
processExpression(returnedExpression)
if (expr.labeledExpression != null) {
val targetFunction = expr.getTargetFunction(expr.safeAnalyzeNonSourceRootCode(BodyResolveMode.FULL))
if (targetFunction != null && PsiTreeUtil.isAncestor(context, targetFunction, true)) {
val transfer: InstructionTransfer
if (returnedExpression != null) {
val retVar = flow.createTempVariable(returnedExpression.getKotlinType().toDfType(expr))
addInstruction(JvmAssignmentInstruction(null, retVar))
transfer = createTransfer(targetFunction, targetFunction, retVar)
} else {
transfer = createTransfer(targetFunction, targetFunction, factory.unknown)
}
addInstruction(ControlTransferInstruction(factory.controlTransfer(transfer, trapTracker.getTrapsInsideElement(targetFunction))))
return
}
}
addInstruction(ReturnInstruction(factory, trapTracker.trapStack(), expr))
}
private fun controlTransfer(target: TransferTarget, traps: FList<Trap>) {
addInstruction(ControlTransferInstruction(factory.controlTransfer(target, traps)))
}
private fun createTransfer(exitedStatement: PsiElement, blockToFlush: PsiElement, resultValue: DfaValue,
exitBlock: Boolean = false): InstructionTransfer {
val varsToFlush = PsiTreeUtil.findChildrenOfType(
blockToFlush,
KtProperty::class.java
).map { property -> KtVariableDescriptor(property) }
return KotlinTransferTarget(resultValue, flow.getEndOffset(exitedStatement), exitBlock, varsToFlush)
}
private class KotlinTransferTarget(
val resultValue: DfaValue,
val offset: ControlFlowOffset,
val exitBlock: Boolean,
val varsToFlush: List<KtVariableDescriptor>
) : InstructionTransfer(offset, varsToFlush) {
override fun dispatch(state: DfaMemoryState, interpreter: DataFlowInterpreter): MutableList<DfaInstructionState> {
if (exitBlock) {
val value = state.pop()
check(!(value !is DfaControlTransferValue || value.target !== DfaControlTransferValue.RETURN_TRANSFER)) {
"Expected control transfer on stack; got $value"
}
}
state.push(resultValue)
return super.dispatch(state, interpreter)
}
override fun bindToFactory(factory: DfaValueFactory): TransferTarget {
return KotlinTransferTarget(resultValue.bindToFactory(factory), offset, exitBlock, varsToFlush)
}
override fun toString(): String {
return super.toString() + "; result = " + resultValue
}
}
private fun processLabeledJumpExpression(expr: KtExpressionWithLabel) {
val targetLoop = expr.targetLoop()
if (targetLoop == null || !PsiTreeUtil.isAncestor(context, targetLoop, false)) {
addInstruction(ControlTransferInstruction(trapTracker.transferValue(DfaControlTransferValue.RETURN_TRANSFER)))
} else {
val body = if (expr is KtBreakExpression) targetLoop else targetLoop.body!!
val transfer = factory.controlTransfer(createTransfer(body, body, factory.unknown), trapTracker.getTrapsInsideElement(body))
addInstruction(ControlTransferInstruction(transfer))
}
}
private fun processThrowExpression(expr: KtThrowExpression) {
val exception = expr.thrownExpression
processExpression(exception)
addInstruction(PopInstruction())
if (exception != null) {
val psiType = exception.getKotlinType()?.toPsiType(expr)
if (psiType != null) {
val kind = ExceptionTransfer(TypeConstraints.instanceOf(psiType))
addInstruction(ThrowInstruction(trapTracker.transferValue(kind), expr))
return
}
}
pushUnknown()
}
private fun processReferenceExpression(expr: KtSimpleNameExpression, qualifierOnStack: Boolean = false) {
val dfVar = KtVariableDescriptor.createFromSimpleName(factory, expr)
if (dfVar != null) {
if (qualifierOnStack) {
addInstruction(PopInstruction())
}
addInstruction(JvmPushInstruction(dfVar, KotlinExpressionAnchor(expr)))
var realExpr: KtExpression = expr
while (true) {
val parent = realExpr.parent
if (parent is KtQualifiedExpression && parent.selectorExpression == realExpr) {
realExpr = parent
} else break
}
val exprType = realExpr.getKotlinType()
val declaredType = when (val desc = dfVar.descriptor) {
is KtVariableDescriptor -> desc.variable.type()
is KtItVariableDescriptor -> desc.type
else -> null
}
addImplicitConversion(expr, declaredType, exprType)
return
}
val target = expr.mainReference.resolve()
val value: DfType? = getReferenceValue(expr, target)
if (value != null) {
if (qualifierOnStack) {
addInstruction(PopInstruction())
}
addInstruction(PushValueInstruction(value, KotlinExpressionAnchor(expr)))
} else {
addCall(expr, 0, qualifierOnStack)
}
}
private fun getReferenceValue(expr: KtExpression, target: PsiElement?): DfType? {
return when (target) {
// Companion object qualifier
is KtObjectDeclaration -> DfType.TOP
is PsiClass -> DfType.TOP
is PsiVariable -> {
val constantValue = target.computeConstantValue()
if (constantValue != null && constantValue !is Boolean) {
DfTypes.constant(constantValue, target.type)
} else {
expr.getKotlinType().toDfType(expr)
}
}
is KtEnumEntry -> {
val enumClass = target.containingClass()?.toLightClass()
val enumConstant = enumClass?.fields?.firstOrNull { f -> f is PsiEnumConstant && f.name == target.name }
if (enumConstant != null) {
DfTypes.referenceConstant(enumConstant, TypeConstraints.exactClass(enumClass).instanceOf())
} else {
DfType.TOP
}
}
else -> null
}
}
private fun processConstantExpression(expr: KtConstantExpression) {
addInstruction(PushValueInstruction(getConstant(expr), KotlinExpressionAnchor(expr)))
}
private fun pushUnknown() {
addInstruction(PushValueInstruction(DfType.TOP))
}
private fun processBinaryExpression(expr: KtBinaryExpression) {
val token = expr.operationToken
val relation = relationFromToken(token)
if (relation != null) {
processBinaryRelationExpression(expr, relation, token == KtTokens.EXCLEQ || token == KtTokens.EQEQ)
return
}
val leftKtType = expr.left?.getKotlinType()
if (token === KtTokens.PLUS && (KotlinBuiltIns.isString(leftKtType) || KotlinBuiltIns.isString(expr.right?.getKotlinType()))) {
processExpression(expr.left)
processExpression(expr.right)
addInstruction(StringConcatInstruction(KotlinExpressionAnchor(expr), stringType))
return
}
if (leftKtType?.toDfType(expr) is DfIntegralType) {
val mathOp = mathOpFromToken(expr.operationReference)
if (mathOp != null) {
processMathExpression(expr, mathOp)
return
}
}
if (token === KtTokens.ANDAND || token === KtTokens.OROR) {
processShortCircuitExpression(expr, token === KtTokens.ANDAND)
return
}
if (ASSIGNMENT_TOKENS.contains(token)) {
processAssignmentExpression(expr)
return
}
if (token === KtTokens.ELVIS) {
processNullSafeOperator(expr)
return
}
if (token === KtTokens.IN_KEYWORD) {
val left = expr.left
processExpression(left)
processInCheck(left?.getKotlinType(), expr.right, KotlinExpressionAnchor(expr), false)
return
}
if (token === KtTokens.NOT_IN) {
val left = expr.left
processExpression(left)
processInCheck(left?.getKotlinType(), expr.right, KotlinExpressionAnchor(expr), true)
return
}
processExpression(expr.left)
processExpression(expr.right)
addCall(expr, 2)
}
private fun processInCheck(kotlinType: KotlinType?, range: KtExpression?, anchor: KotlinAnchor, negated: Boolean) {
if (kotlinType != null && (kotlinType.isInt() || kotlinType.isLong())) {
if (range is KtBinaryExpression) {
val ref = range.operationReference.text
if (ref == ".." || ref == "until") {
val left = range.left
val right = range.right
val leftType = left?.getKotlinType()
val rightType = right?.getKotlinType()
if (leftType.toDfType(range) is DfIntegralType && rightType.toDfType(range) is DfIntegralType) {
processExpression(left)
addImplicitConversion(left, kotlinType)
processExpression(right)
addImplicitConversion(right, kotlinType)
addInstruction(SpliceInstruction(3, 2, 0, 2, 1))
addInstruction(BooleanBinaryInstruction(RelationType.GE, false, null))
val offset = DeferredOffset()
addInstruction(ConditionalGotoInstruction(offset, DfTypes.FALSE))
var relationType = if (ref == "until") RelationType.LT else RelationType.LE
if (negated) {
relationType = relationType.negated
}
addInstruction(BooleanBinaryInstruction(relationType, false, anchor))
val finalOffset = DeferredOffset()
addInstruction(GotoInstruction(finalOffset))
setOffset(offset)
addInstruction(SpliceInstruction(2))
addInstruction(PushValueInstruction(if (negated) DfTypes.TRUE else DfTypes.FALSE, anchor))
setOffset(finalOffset)
return
}
}
}
}
processExpression(range)
addInstruction(EvalUnknownInstruction(anchor, 2, DfTypes.BOOLEAN))
addInstruction(FlushFieldsInstruction())
}
private fun processNullSafeOperator(expr: KtBinaryExpression) {
val left = expr.left
processExpression(left)
addInstruction(DupInstruction())
val offset = DeferredOffset()
addInstruction(ConditionalGotoInstruction(offset, DfTypes.NULL))
val endOffset = DeferredOffset()
addImplicitConversion(expr, left?.getKotlinType(), expr.getKotlinType())
addInstruction(GotoInstruction(endOffset))
setOffset(offset)
addInstruction(PopInstruction())
processExpression(expr.right)
setOffset(endOffset)
addInstruction(ResultOfInstruction(KotlinExpressionAnchor(expr)))
}
private fun processAssignmentExpression(expr: KtBinaryExpression) {
val left = expr.left
val right = expr.right
val token = expr.operationToken
if (left is KtArrayAccessExpression && token == KtTokens.EQ) {
// TODO: compound-assignment for arrays
processArrayAccess(left, right)
return
}
val dfVar = KtVariableDescriptor.createFromQualified(factory, left)
val leftType = left?.getKotlinType()
val rightType = right?.getKotlinType()
if (dfVar == null) {
processExpression(left)
addInstruction(PopInstruction())
processExpression(right)
addImplicitConversion(right, leftType)
// TODO: support safe-qualified assignments
addInstruction(FlushFieldsInstruction())
return
}
val mathOp = mathOpFromAssignmentToken(token)
if (mathOp != null) {
val resultType = balanceType(leftType, rightType)
processExpression(left)
addImplicitConversion(left, resultType)
processExpression(right)
addImplicitConversion(right, resultType)
addInstruction(NumericBinaryInstruction(mathOp, KotlinExpressionAnchor(expr)))
addImplicitConversion(right, resultType, leftType)
} else {
processExpression(right)
addImplicitConversion(right, leftType)
}
// TODO: support overloaded assignment
addInstruction(JvmAssignmentInstruction(KotlinExpressionAnchor(expr), dfVar))
addInstruction(FinishElementInstruction(expr))
}
private fun processShortCircuitExpression(expr: KtBinaryExpression, and: Boolean) {
val left = expr.left
val right = expr.right
val endOffset = DeferredOffset()
processExpression(left)
val nextOffset = DeferredOffset()
addInstruction(ConditionalGotoInstruction(nextOffset, DfTypes.booleanValue(and), left))
val anchor = KotlinExpressionAnchor(expr)
addInstruction(PushValueInstruction(DfTypes.booleanValue(!and), anchor))
addInstruction(GotoInstruction(endOffset))
setOffset(nextOffset)
addInstruction(FinishElementInstruction(null))
processExpression(right)
setOffset(endOffset)
addInstruction(ResultOfInstruction(anchor))
}
private fun processMathExpression(expr: KtBinaryExpression, mathOp: LongRangeBinOp) {
val left = expr.left
val right = expr.right
val resultType = expr.getKotlinType()
processExpression(left)
addImplicitConversion(left, resultType)
processExpression(right)
if (!mathOp.isShift) {
addImplicitConversion(right, resultType)
}
if ((mathOp == LongRangeBinOp.DIV || mathOp == LongRangeBinOp.MOD) && resultType != null &&
(resultType.isLong() || resultType.isInt())) {
val transfer: DfaControlTransferValue? = trapTracker.maybeTransferValue("java.lang.ArithmeticException")
val zero = if (resultType.isLong()) DfTypes.longValue(0) else DfTypes.intValue(0)
addInstruction(EnsureInstruction(null, RelationType.NE, zero, transfer, true))
}
addInstruction(NumericBinaryInstruction(mathOp, KotlinExpressionAnchor(expr)))
}
private fun addImplicitConversion(expression: KtExpression?, expectedType: KotlinType?) {
addImplicitConversion(expression, expression?.getKotlinType(), expectedType)
}
private fun addImplicitConversion(expression: KtExpression?, actualType: KotlinType?, expectedType: KotlinType?) {
expression ?: return
actualType ?: return
expectedType ?: return
if (actualType == expectedType) return
val actualPsiType = actualType.toPsiType(expression)
val expectedPsiType = expectedType.toPsiType(expression)
if (actualPsiType !is PsiPrimitiveType && expectedPsiType is PsiPrimitiveType) {
addInstruction(UnwrapDerivedVariableInstruction(SpecialField.UNBOX))
}
else if (expectedPsiType !is PsiPrimitiveType && actualPsiType is PsiPrimitiveType) {
val boxedType = actualPsiType.getBoxedType(expression)
val dfType = if (boxedType != null) DfTypes.typedObject(boxedType, Nullability.NOT_NULL) else DfTypes.NOT_NULL_OBJECT
addInstruction(WrapDerivedVariableInstruction(expectedType.toDfType(expression).meet(dfType), SpecialField.UNBOX))
}
if (actualPsiType is PsiPrimitiveType && expectedPsiType is PsiPrimitiveType) {
addInstruction(PrimitiveConversionInstruction(expectedPsiType, null))
}
}
private fun processBinaryRelationExpression(
expr: KtBinaryExpression, relation: RelationType,
forceEqualityByContent: Boolean
) {
val left = expr.left
val right = expr.right
val leftType = left?.getKotlinType()
val rightType = right?.getKotlinType()
processExpression(left)
val leftDfType = leftType.toDfType(expr)
val rightDfType = rightType.toDfType(expr)
if ((relation == RelationType.EQ || relation == RelationType.NE) ||
(leftDfType is DfPrimitiveType && rightDfType is DfPrimitiveType)) {
val balancedType: KotlinType? = balanceType(leftType, rightType, forceEqualityByContent)
addImplicitConversion(left, balancedType)
processExpression(right)
addImplicitConversion(right, balancedType)
if (forceEqualityByContent && !mayCompareByContent(leftDfType, rightDfType)) {
val transfer = trapTracker.maybeTransferValue(CommonClassNames.JAVA_LANG_THROWABLE)
addInstruction(KotlinEqualityInstruction(expr, relation != RelationType.EQ, transfer))
} else {
addInstruction(BooleanBinaryInstruction(relation, forceEqualityByContent, KotlinExpressionAnchor(expr)))
}
} else {
val leftConstraint = TypeConstraint.fromDfType(leftDfType)
val rightConstraint = TypeConstraint.fromDfType(rightDfType)
if (leftConstraint.isEnum && rightConstraint.isEnum && leftConstraint.meet(rightConstraint) != TypeConstraints.BOTTOM) {
addInstruction(UnwrapDerivedVariableInstruction(SpecialField.ENUM_ORDINAL))
processExpression(right)
addInstruction(UnwrapDerivedVariableInstruction(SpecialField.ENUM_ORDINAL))
addInstruction(BooleanBinaryInstruction(relation, forceEqualityByContent, KotlinExpressionAnchor(expr)))
} else if (leftConstraint.isExact(CommonClassNames.JAVA_LANG_STRING) &&
rightConstraint.isExact(CommonClassNames.JAVA_LANG_STRING)) {
processExpression(right)
addInstruction(BooleanBinaryInstruction(relation, forceEqualityByContent, KotlinExpressionAnchor(expr)))
} else {
// Overloaded >/>=/</<=: do not evaluate
processExpression(right)
addCall(expr, 2)
}
}
}
private fun mayCompareByContent(leftDfType: DfType, rightDfType: DfType): Boolean {
if (leftDfType == DfTypes.NULL || rightDfType == DfTypes.NULL) return true
if (leftDfType is DfPrimitiveType || rightDfType is DfPrimitiveType) return true
val constraint = TypeConstraint.fromDfType(leftDfType)
if (constraint.isComparedByEquals || constraint.isArray || constraint.isEnum) return true
if (!constraint.isExact) return false
val cls = PsiUtil.resolveClassInClassTypeOnly(constraint.getPsiType(factory.project)) ?: return false
val equalsSignature =
MethodSignatureUtil.createMethodSignature("equals", arrayOf(TypeUtils.getObjectType(context)), arrayOf(), PsiSubstitutor.EMPTY)
val method = MethodSignatureUtil.findMethodBySignature(cls, equalsSignature, true)
return method?.containingClass?.qualifiedName == CommonClassNames.JAVA_LANG_OBJECT
}
private fun balanceType(leftType: KotlinType?, rightType: KotlinType?, forceEqualityByContent: Boolean): KotlinType? = when {
leftType == null || rightType == null -> null
leftType.isNullableNothing() -> rightType.makeNullable()
rightType.isNullableNothing() -> leftType.makeNullable()
!forceEqualityByContent -> balanceType(leftType, rightType)
leftType.isSubtypeOf(rightType) -> rightType
rightType.isSubtypeOf(leftType) -> leftType
else -> null
}
private fun balanceType(left: KotlinType?, right: KotlinType?): KotlinType? {
if (left == null || right == null) return null
if (left == right) return left
if (left.canBeNull() && !right.canBeNull()) {
return balanceType(left.makeNotNullable(), right)
}
if (!left.canBeNull() && right.canBeNull()) {
return balanceType(left, right.makeNotNullable())
}
if (left.isDouble()) return left
if (right.isDouble()) return right
if (left.isFloat()) return left
if (right.isFloat()) return right
if (left.isLong()) return left
if (right.isLong()) return right
// The 'null' means no balancing is necessary
return null
}
private fun addInstruction(inst: Instruction) {
flow.addInstruction(inst)
}
private fun setOffset(offset: DeferredOffset) {
offset.setOffset(flow.instructionCount)
}
private fun processWhenExpression(expr: KtWhenExpression) {
val subjectExpression = expr.subjectExpression
val dfVar: DfaVariableValue?
val kotlinType: KotlinType?
if (subjectExpression == null) {
dfVar = null
kotlinType = null
} else {
processExpression(subjectExpression)
val subjectVariable = expr.subjectVariable
if (subjectVariable != null) {
kotlinType = subjectVariable.type()
dfVar = factory.varFactory.createVariableValue(KtVariableDescriptor(subjectVariable))
} else {
kotlinType = subjectExpression.getKotlinType()
dfVar = flow.createTempVariable(kotlinType.toDfType(expr))
addInstruction(JvmAssignmentInstruction(null, dfVar))
}
addInstruction(PopInstruction())
}
val endOffset = DeferredOffset()
for (entry in expr.entries) {
if (entry.isElse) {
processExpression(entry.expression)
addInstruction(GotoInstruction(endOffset))
} else {
val branchStart = DeferredOffset()
for (condition in entry.conditions) {
processWhenCondition(dfVar, kotlinType, condition)
addInstruction(ConditionalGotoInstruction(branchStart, DfTypes.TRUE))
}
val skipBranch = DeferredOffset()
addInstruction(GotoInstruction(skipBranch))
setOffset(branchStart)
processExpression(entry.expression)
addInstruction(GotoInstruction(endOffset))
setOffset(skipBranch)
}
}
pushUnknown()
setOffset(endOffset)
addInstruction(FinishElementInstruction(expr))
}
private fun processWhenCondition(dfVar: DfaVariableValue?, dfVarType: KotlinType?, condition: KtWhenCondition) {
when (condition) {
is KtWhenConditionWithExpression -> {
val expr = condition.expression
processExpression(expr)
val exprType = expr?.getKotlinType()
if (dfVar != null) {
val balancedType = balanceType(exprType, dfVarType, true)
addImplicitConversion(expr, exprType, balancedType)
addInstruction(JvmPushInstruction(dfVar, null))
addImplicitConversion(null, dfVarType, balancedType)
addInstruction(BooleanBinaryInstruction(RelationType.EQ, true, KotlinWhenConditionAnchor(condition)))
} else if (exprType?.canBeNull() == true) {
addInstruction(UnwrapDerivedVariableInstruction(SpecialField.UNBOX))
}
}
is KtWhenConditionIsPattern -> {
if (dfVar != null) {
addInstruction(JvmPushInstruction(dfVar, null))
val type = getTypeCheckDfType(condition.typeReference)
if (type == DfType.TOP) {
pushUnknown()
} else {
addInstruction(PushValueInstruction(type))
if (condition.isNegated) {
addInstruction(InstanceofInstruction(null, false))
addInstruction(NotInstruction(KotlinWhenConditionAnchor(condition)))
} else {
addInstruction(InstanceofInstruction(KotlinWhenConditionAnchor(condition), false))
}
}
} else {
pushUnknown()
}
}
is KtWhenConditionInRange -> {
if (dfVar != null) {
addInstruction(JvmPushInstruction(dfVar, null))
} else {
pushUnknown()
}
processInCheck(dfVarType, condition.rangeExpression, KotlinWhenConditionAnchor(condition), condition.isNegated)
}
else -> broken = true
}
}
private fun getTypeCheckDfType(typeReference: KtTypeReference?): DfType {
if (typeReference == null) return DfType.TOP
val kotlinType = typeReference.getAbbreviatedTypeOrType(typeReference.safeAnalyzeNonSourceRootCode(BodyResolveMode.FULL))
val type = kotlinType.toDfType(typeReference)
return if (type is DfPrimitiveType) {
val boxedType = (kotlinType?.toPsiType(typeReference) as? PsiPrimitiveType)?.getBoxedType(typeReference)
if (boxedType != null) {
DfTypes.typedObject(boxedType, Nullability.NOT_NULL)
} else {
DfType.TOP
}
} else type
}
private fun processIfExpression(ifExpression: KtIfExpression) {
val condition = ifExpression.condition
processExpression(condition)
if (condition?.getKotlinType()?.canBeNull() == true) {
addInstruction(UnwrapDerivedVariableInstruction(SpecialField.UNBOX))
}
val skipThenOffset = DeferredOffset()
val thenStatement = ifExpression.then
val elseStatement = ifExpression.`else`
val exprType = ifExpression.getKotlinType()
addInstruction(ConditionalGotoInstruction(skipThenOffset, DfTypes.FALSE, condition))
addInstruction(FinishElementInstruction(null))
processExpression(thenStatement)
addImplicitConversion(thenStatement, exprType)
val skipElseOffset = DeferredOffset()
addInstruction(GotoInstruction(skipElseOffset))
setOffset(skipThenOffset)
addInstruction(FinishElementInstruction(null))
processExpression(elseStatement)
addImplicitConversion(elseStatement, exprType)
setOffset(skipElseOffset)
addInstruction(FinishElementInstruction(ifExpression))
}
companion object {
private val LOG = logger<KtControlFlowBuilder>()
private val ASSIGNMENT_TOKENS = TokenSet.create(KtTokens.EQ, KtTokens.PLUSEQ, KtTokens.MINUSEQ, KtTokens.MULTEQ, KtTokens.DIVEQ, KtTokens.PERCEQ)
private val unsupported = ConcurrentHashMap.newKeySet<String>()
}
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/dfa/KtControlFlowBuilder.kt | 2927507913 |
package com.github.kerubistan.kerub.planner.steps.storage.lvm.duplicate
import com.github.kerubistan.kerub.data.dynamic.VirtualStorageDeviceDynamicDao
import com.github.kerubistan.kerub.host.HostCommandExecutor
import com.github.kerubistan.kerub.planner.steps.storage.block.duplicate.AbstractBlockDuplicateExecutor
import com.github.kerubistan.kerub.utils.junix.storagemanager.lvm.LvmLv
class DuplicateToLvmExecutor(
override val hostCommandExecutor: HostCommandExecutor,
override val virtualStorageDynamicDao: VirtualStorageDeviceDynamicDao
) : AbstractBlockDuplicateExecutor<DuplicateToLvm>() {
override fun allocate(step: DuplicateToLvm) {
hostCommandExecutor.execute(step.targetHost) {
LvmLv.create(session = it,
vgName = step.target.vgName,
size = step.virtualStorageDevice.size,
name = step.virtualStorageDevice.id.toString()
)
}
}
} | src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/lvm/duplicate/DuplicateToLvmExecutor.kt | 878995601 |
// 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.jps.builders
import com.intellij.util.PathUtil
import org.jetbrains.jps.api.GlobalOptions
class ParallelBuildTest: JpsBuildTestCase() {
override fun setUp() {
super.setUp()
System.setProperty(GlobalOptions.COMPILE_PARALLEL_OPTION, true.toString())
}
override fun tearDown() {
System.setProperty(GlobalOptions.COMPILE_PARALLEL_OPTION, false.toString())
super.tearDown()
}
fun testBuildDependentModules() {
createFile("m1/Class0.java", "public class Class0 {}")
for (i in 1..10) {
val file = createFile("m$i/Class$i.java", "public class Class$i { Class${i-1} prev; }")
val module = addModule("m$i", PathUtil.getParentPath(file))
if (i > 1) {
module.dependenciesList.addModuleDependency(myProject.modules.first { it.name == "m${i-1}" })
}
}
rebuildAllModules()
}
} | jps/jps-builders/testSrc/org/jetbrains/jps/builders/ParallelBuildTest.kt | 2838590965 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import org.jetbrains.annotations.Nls
open class QuickFixWithDelegateFactory(
private val delegateFactory: () -> IntentionAction?
) : IntentionAction {
@Nls
private val familyName: String
@Nls
private val text: String
private val startInWriteAction: Boolean
init {
val delegate = delegateFactory()
familyName = delegate?.familyName ?: ""
text = delegate?.text ?: ""
startInWriteAction = delegate != null && delegate.startInWriteAction()
}
override fun getFamilyName() = familyName
override fun getText() = text
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile): Boolean {
val action = delegateFactory() ?: return false
return action.isAvailable(project, editor, file)
}
override fun startInWriteAction() = startInWriteAction
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
if (!FileModificationService.getInstance().prepareFileForWrite(file)) {
return
}
val action = delegateFactory() ?: return
assert(action.detectPriority() == this.detectPriority()) {
"Incorrect priority of QuickFixWithDelegateFactory wrapper for ${action::class.java.name}"
}
action.invoke(project, editor, file)
}
}
class LowPriorityQuickFixWithDelegateFactory(
delegateFactory: () -> IntentionAction?
) : QuickFixWithDelegateFactory(delegateFactory), LowPriorityAction
class HighPriorityQuickFixWithDelegateFactory(
delegateFactory: () -> IntentionAction?
) : QuickFixWithDelegateFactory(delegateFactory), HighPriorityAction
enum class IntentionActionPriority {
LOW, NORMAL, HIGH
}
fun IntentionAction.detectPriority(): IntentionActionPriority {
return when (this) {
is LowPriorityAction -> IntentionActionPriority.LOW
is HighPriorityAction -> IntentionActionPriority.HIGH
else -> IntentionActionPriority.NORMAL
}
}
fun QuickFixWithDelegateFactory(priority: IntentionActionPriority, createAction: () -> IntentionAction?): QuickFixWithDelegateFactory {
return when (priority) {
IntentionActionPriority.NORMAL -> QuickFixWithDelegateFactory(createAction)
IntentionActionPriority.HIGH -> HighPriorityQuickFixWithDelegateFactory(createAction)
IntentionActionPriority.LOW -> LowPriorityQuickFixWithDelegateFactory(createAction)
}
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/QuickFixWithDelegateFactory.kt | 411274735 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.LOCAL_CHANGES
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.SHELF
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.getToolWindowFor
import com.intellij.openapi.wm.ToolWindow
class VcsShowLocalChangesAction : VcsShowToolWindowTabAction() {
override val tabName: String get() = LOCAL_CHANGES
}
class VcsShowShelfAction : VcsShowToolWindowTabAction() {
override val tabName: String get() = SHELF
}
abstract class VcsShowToolWindowTabAction : DumbAwareAction() {
protected abstract val tabName: String
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = getToolWindow(e.project) != null
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.EDT
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val toolWindow = getToolWindow(project)!!
val contentManager = ChangesViewContentManager.getInstance(project) as ChangesViewContentManager
val isToolWindowActive = toolWindow.isActive
val isContentSelected = contentManager.isContentSelected(tabName)
val tabSelector = Runnable { contentManager.selectContent(tabName, true) }
when {
isToolWindowActive && isContentSelected -> toolWindow.hide(null)
isToolWindowActive && !isContentSelected -> tabSelector.run()
!isToolWindowActive && isContentSelected -> toolWindow.activate(null, true)
!isToolWindowActive && !isContentSelected -> toolWindow.activate(tabSelector, false)
}
}
private fun getToolWindow(project: Project?): ToolWindow? = project?.let { getToolWindowFor(it, tabName) }
} | platform/vcs-impl/src/com/intellij/vcs/VcsShowToolWindowTabAction.kt | 483880172 |
// 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 training.dsl
import com.intellij.openapi.util.text.StringUtil
import training.ui.LearningUiManager
import training.util.replaceSpacesWithNonBreakSpace
import training.util.surroundWithNonBreakSpaces
import javax.swing.Icon
/* Here can be defined common methods for any DSL level */
interface LearningDslBase {
/** Show shortcut for [actionId] inside lesson step message */
fun action(actionId: String): String {
return "<action>$actionId</action>".surroundWithNonBreakSpaces()
}
/** Highlight as code inside lesson step message */
fun code(sourceSample: String): String {
return "<code>${StringUtil.escapeXmlEntities(sourceSample).replaceSpacesWithNonBreakSpace()}</code>".surroundWithNonBreakSpaces()
}
/** Highlight some [text] */
fun strong(text: String): String {
return "<strong>${StringUtil.escapeXmlEntities(text)}</strong>"
}
/** Show an [icon] inside lesson step message */
fun icon(icon: Icon): String {
val index = LearningUiManager.getIconIndex(icon)
return "<icon_idx>$index</icon_idx>"
}
fun shortcut(key: String): String {
return "<shortcut>${key}</shortcut>".surroundWithNonBreakSpaces()
}
}
| plugins/ide-features-trainer/src/training/dsl/LearningDslBase.kt | 3802918969 |
package one.two
fun read() {
val c = KotlinObject.fieldProperty
} | plugins/kotlin/refIndex/tests/testData/compilerIndex/properties/fromObject/fieldProperty/Read.kt | 3984952196 |
package com.jetbrains.packagesearch.intellij.plugin.maven.configuration
import com.intellij.ide.ui.search.SearchableOptionContributor
import com.intellij.ide.ui.search.SearchableOptionProcessor
import com.jetbrains.packagesearch.intellij.plugin.configuration.addSearchConfigurationMap
internal class MavenSearchableOptionContributor : SearchableOptionContributor() {
override fun processOptions(processor: SearchableOptionProcessor) {
// Make settings searchable
addSearchConfigurationMap(
processor,
"maven", "scope"
)
}
}
| plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/maven/configuration/MavenSearchableOptionContributor.kt | 3185650197 |
fun test312() {
with(`my main class`()) {
val (_) = this
}
}
| plugins/kotlin/refIndex/tests/testData/compilerIndex/properties/constructorParameterFromDataClass/escapedName/FirstComponentOnly.kt | 1854088652 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.jetcaster.ui.player
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.sizeIn
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.ContentAlpha
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.LocalContentAlpha
import androidx.compose.material.LocalContentColor
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Slider
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Forward30
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.PlaylistAdd
import androidx.compose.material.icons.filled.Replay10
import androidx.compose.material.icons.filled.SkipNext
import androidx.compose.material.icons.filled.SkipPrevious
import androidx.compose.material.icons.rounded.PlayCircleFilled
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.role
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.window.layout.FoldingFeature
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.example.jetcaster.R
import com.example.jetcaster.ui.theme.JetcasterTheme
import com.example.jetcaster.ui.theme.MinContrastOfPrimaryVsSurface
import com.example.jetcaster.util.DevicePosture
import com.example.jetcaster.util.DynamicThemePrimaryColorsFromImage
import com.example.jetcaster.util.contrastAgainst
import com.example.jetcaster.util.rememberDominantColorState
import com.example.jetcaster.util.verticalGradientScrim
import java.time.Duration
import kotlinx.coroutines.flow.StateFlow
/**
* Stateful version of the Podcast player
*/
@OptIn(ExperimentalLifecycleComposeApi::class)
@Composable
fun PlayerScreen(
viewModel: PlayerViewModel,
devicePosture: StateFlow<DevicePosture>,
onBackPress: () -> Unit
) {
val uiState = viewModel.uiState
val devicePostureValue by devicePosture.collectAsStateWithLifecycle()
PlayerScreen(uiState, devicePostureValue, onBackPress)
}
/**
* Stateless version of the Player screen
*/
@Composable
private fun PlayerScreen(
uiState: PlayerUiState,
devicePosture: DevicePosture,
onBackPress: () -> Unit,
modifier: Modifier = Modifier
) {
Surface(modifier) {
if (uiState.podcastName.isNotEmpty()) {
PlayerContent(uiState, devicePosture, onBackPress)
} else {
FullScreenLoading(modifier)
}
}
}
@Composable
fun PlayerContent(
uiState: PlayerUiState,
devicePosture: DevicePosture,
onBackPress: () -> Unit
) {
PlayerDynamicTheme(uiState.podcastImageUrl) {
// As the Player UI content changes considerably when the device is in tabletop posture,
// we split the different UIs in different composables. For simpler UIs that don't change
// much, prefer one composable that makes decisions based on the mode instead.
when (devicePosture) {
is DevicePosture.TableTopPosture ->
PlayerContentTableTop(uiState, devicePosture, onBackPress)
is DevicePosture.BookPosture ->
PlayerContentBook(uiState, devicePosture, onBackPress)
is DevicePosture.SeparatingPosture ->
if (devicePosture.orientation == FoldingFeature.Orientation.HORIZONTAL) {
PlayerContentTableTop(
uiState,
DevicePosture.TableTopPosture(devicePosture.hingePosition),
onBackPress
)
} else {
PlayerContentBook(
uiState,
DevicePosture.BookPosture(devicePosture.hingePosition),
onBackPress
)
}
else ->
PlayerContentRegular(uiState, onBackPress)
}
}
}
@Composable
private fun PlayerContentRegular(
uiState: PlayerUiState,
onBackPress: () -> Unit
) {
Column(
modifier = Modifier
.fillMaxSize()
.verticalGradientScrim(
color = MaterialTheme.colors.primary.copy(alpha = 0.50f),
startYPercentage = 1f,
endYPercentage = 0f
)
.systemBarsPadding()
.padding(horizontal = 8.dp)
) {
TopAppBar(onBackPress = onBackPress)
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.padding(horizontal = 8.dp)
) {
Spacer(modifier = Modifier.weight(1f))
PlayerImage(
podcastImageUrl = uiState.podcastImageUrl,
modifier = Modifier.weight(10f)
)
Spacer(modifier = Modifier.height(32.dp))
PodcastDescription(uiState.title, uiState.podcastName)
Spacer(modifier = Modifier.height(32.dp))
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.weight(10f)
) {
PlayerSlider(uiState.duration)
PlayerButtons(Modifier.padding(vertical = 8.dp))
}
Spacer(modifier = Modifier.weight(1f))
}
}
}
@Composable
private fun PlayerContentTableTop(
uiState: PlayerUiState,
tableTopPosture: DevicePosture.TableTopPosture,
onBackPress: () -> Unit
) {
val hingePosition = with(LocalDensity.current) { tableTopPosture.hingePosition.top.toDp() }
val hingeHeight = with(LocalDensity.current) { tableTopPosture.hingePosition.height().toDp() }
Column(modifier = Modifier.fillMaxSize()) {
// Content for the top part of the screen
Column(
modifier = Modifier
.height(hingePosition)
.fillMaxWidth()
.verticalGradientScrim(
color = MaterialTheme.colors.primary.copy(alpha = 0.50f),
startYPercentage = 1f,
endYPercentage = 0f
)
.windowInsetsPadding(
WindowInsets.systemBars.only(
WindowInsetsSides.Horizontal + WindowInsetsSides.Top
)
)
.padding(32.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
PlayerImage(uiState.podcastImageUrl)
}
// Space for the hinge
Spacer(modifier = Modifier.height(hingeHeight))
// Content for the table part of the screen
Column(
modifier = Modifier
.windowInsetsPadding(
WindowInsets.systemBars.only(
WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom
)
)
.padding(horizontal = 32.dp, vertical = 8.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
TopAppBar(onBackPress = onBackPress)
PodcastDescription(
title = uiState.title,
podcastName = uiState.podcastName,
titleTextStyle = MaterialTheme.typography.h6
)
Spacer(modifier = Modifier.weight(0.5f))
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.weight(10f)
) {
PlayerButtons(playerButtonSize = 92.dp, modifier = Modifier.padding(top = 8.dp))
PlayerSlider(uiState.duration)
}
}
}
}
@Composable
private fun PlayerContentBook(
uiState: PlayerUiState,
bookPosture: DevicePosture.BookPosture,
onBackPress: () -> Unit
) {
val hingePosition = with(LocalDensity.current) { bookPosture.hingePosition.left.toDp() }
val hingeWidth = with(LocalDensity.current) { bookPosture.hingePosition.width().toDp() }
Column(
modifier = Modifier
.fillMaxSize()
.verticalGradientScrim(
color = MaterialTheme.colors.primary.copy(alpha = 0.50f),
startYPercentage = 1f,
endYPercentage = 0f
)
.systemBarsPadding()
.padding(horizontal = 8.dp)
) {
TopAppBar(onBackPress = onBackPress)
Row(modifier = Modifier.fillMaxSize()) {
// Content for the left part of the screen
PlayerContentBookLeft(hingePosition, uiState)
// Space for the hinge
Spacer(modifier = Modifier.width(hingeWidth))
// Content for the right part of the screen
PlayerContentBookRight(uiState)
}
}
}
@Composable
private fun PlayerContentBookLeft(
hingePosition: Dp,
uiState: PlayerUiState
) {
Column(
modifier = Modifier
.width(hingePosition)
.padding(8.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.padding(horizontal = 8.dp)
) {
Spacer(modifier = Modifier.weight(1f))
Spacer(modifier = Modifier.height(32.dp))
PodcastInformation(
uiState.title,
uiState.podcastName,
uiState.summary
)
}
}
}
@Composable
private fun PlayerContentBookRight(
uiState: PlayerUiState
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(8.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Spacer(modifier = Modifier.weight(1f))
PlayerImage(
podcastImageUrl = uiState.podcastImageUrl,
modifier = Modifier.weight(10f)
)
Spacer(modifier = Modifier.height(32.dp))
PodcastDescription(uiState.title, uiState.podcastName)
Spacer(modifier = Modifier.height(32.dp))
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.weight(10f)
) {
PlayerSlider(uiState.duration)
PlayerButtons(Modifier.padding(vertical = 8.dp))
}
Spacer(modifier = Modifier.weight(1f))
}
}
@Composable
private fun TopAppBar(onBackPress: () -> Unit) {
Row(Modifier.fillMaxWidth()) {
IconButton(onClick = onBackPress) {
Icon(
imageVector = Icons.Default.ArrowBack,
contentDescription = stringResource(R.string.cd_back)
)
}
Spacer(Modifier.weight(1f))
IconButton(onClick = { /* TODO */ }) {
Icon(
imageVector = Icons.Default.PlaylistAdd,
contentDescription = stringResource(R.string.cd_add)
)
}
IconButton(onClick = { /* TODO */ }) {
Icon(
imageVector = Icons.Default.MoreVert,
contentDescription = stringResource(R.string.cd_more)
)
}
}
}
@Composable
private fun PlayerImage(
podcastImageUrl: String,
modifier: Modifier = Modifier
) {
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(podcastImageUrl)
.crossfade(true)
.build(),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = modifier
.sizeIn(maxWidth = 500.dp, maxHeight = 500.dp)
.aspectRatio(1f)
.clip(MaterialTheme.shapes.medium)
)
}
@Composable
private fun PodcastDescription(
title: String,
podcastName: String,
titleTextStyle: TextStyle = MaterialTheme.typography.h5
) {
Text(
text = title,
style = titleTextStyle,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
Text(
text = podcastName,
style = MaterialTheme.typography.body2,
maxLines = 1
)
}
}
@Composable
private fun PodcastInformation(
title: String,
name: String,
summary: String,
titleTextStyle: TextStyle = MaterialTheme.typography.h5,
nameTextStyle: TextStyle = MaterialTheme.typography.h3,
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.padding(horizontal = 8.dp)
) {
Text(
text = name,
style = nameTextStyle,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
Spacer(modifier = Modifier.height(32.dp))
Text(
text = title,
style = titleTextStyle,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
Spacer(modifier = Modifier.height(32.dp))
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
Text(
text = summary,
style = MaterialTheme.typography.body2,
)
}
Spacer(modifier = Modifier.weight(1f))
}
}
@Composable
private fun PlayerSlider(episodeDuration: Duration?) {
if (episodeDuration != null) {
Column(Modifier.fillMaxWidth()) {
Slider(value = 0f, onValueChange = { })
Row(Modifier.fillMaxWidth()) {
Text(text = "0s")
Spacer(modifier = Modifier.weight(1f))
Text("${episodeDuration.seconds}s")
}
}
}
}
@Composable
private fun PlayerButtons(
modifier: Modifier = Modifier,
playerButtonSize: Dp = 72.dp,
sideButtonSize: Dp = 48.dp
) {
Row(
modifier = modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceEvenly
) {
val buttonsModifier = Modifier
.size(sideButtonSize)
.semantics { role = Role.Button }
Image(
imageVector = Icons.Filled.SkipPrevious,
contentDescription = stringResource(R.string.cd_skip_previous),
contentScale = ContentScale.Fit,
colorFilter = ColorFilter.tint(LocalContentColor.current),
modifier = buttonsModifier
)
Image(
imageVector = Icons.Filled.Replay10,
contentDescription = stringResource(R.string.cd_reply10),
contentScale = ContentScale.Fit,
colorFilter = ColorFilter.tint(LocalContentColor.current),
modifier = buttonsModifier
)
Image(
imageVector = Icons.Rounded.PlayCircleFilled,
contentDescription = stringResource(R.string.cd_play),
contentScale = ContentScale.Fit,
colorFilter = ColorFilter.tint(LocalContentColor.current),
modifier = Modifier
.size(playerButtonSize)
.semantics { role = Role.Button }
)
Image(
imageVector = Icons.Filled.Forward30,
contentDescription = stringResource(R.string.cd_forward30),
contentScale = ContentScale.Fit,
colorFilter = ColorFilter.tint(LocalContentColor.current),
modifier = buttonsModifier
)
Image(
imageVector = Icons.Filled.SkipNext,
contentDescription = stringResource(R.string.cd_skip_next),
contentScale = ContentScale.Fit,
colorFilter = ColorFilter.tint(LocalContentColor.current),
modifier = buttonsModifier
)
}
}
/**
* Theme that updates the colors dynamically depending on the podcast image URL
*/
@Composable
private fun PlayerDynamicTheme(
podcastImageUrl: String,
content: @Composable () -> Unit
) {
val surfaceColor = MaterialTheme.colors.surface
val dominantColorState = rememberDominantColorState(
defaultColor = MaterialTheme.colors.surface
) { color ->
// We want a color which has sufficient contrast against the surface color
color.contrastAgainst(surfaceColor) >= MinContrastOfPrimaryVsSurface
}
DynamicThemePrimaryColorsFromImage(dominantColorState) {
// Update the dominantColorState with colors coming from the podcast image URL
LaunchedEffect(podcastImageUrl) {
if (podcastImageUrl.isNotEmpty()) {
dominantColorState.updateColorsFromImageUrl(podcastImageUrl)
} else {
dominantColorState.reset()
}
}
content()
}
}
/**
* Full screen circular progress indicator
*/
@Composable
private fun FullScreenLoading(modifier: Modifier = Modifier) {
Box(
modifier = modifier
.fillMaxSize()
.wrapContentSize(Alignment.Center)
) {
CircularProgressIndicator()
}
}
@Preview
@Composable
fun TopAppBarPreview() {
JetcasterTheme {
TopAppBar(onBackPress = { })
}
}
@Preview
@Composable
fun PlayerButtonsPreview() {
JetcasterTheme {
PlayerButtons()
}
}
@Preview
@Composable
fun PlayerScreenPreview() {
JetcasterTheme {
PlayerScreen(
PlayerUiState(
title = "Title",
duration = Duration.ofHours(2),
podcastName = "Podcast"
),
devicePosture = DevicePosture.NormalPosture,
onBackPress = { }
)
}
}
| Jetcaster/app/src/main/java/com/example/jetcaster/ui/player/PlayerScreen.kt | 131427617 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.codeInsight.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiFile
import com.intellij.psi.codeStyle.CodeStyleManager
import com.intellij.psi.util.PsiTreeUtil
import com.jetbrains.python.PyPsiBundle
import com.jetbrains.python.psi.LanguageLevel
import com.jetbrains.python.psi.PyElementGenerator
import com.jetbrains.python.psi.PyFromImportStatement
import com.jetbrains.python.psi.PyStatement
import org.jetbrains.annotations.PropertyKey
abstract class PyConvertImportIntentionAction(@PropertyKey(resourceBundle = PyPsiBundle.BUNDLE) intentionText: String) : PyBaseIntentionAction() {
init {
text = PyPsiBundle.message(intentionText)
}
override fun getFamilyName(): String = text
fun replaceImportStatement(statement: PyFromImportStatement, file: PsiFile, path: String) {
val imported = statement.importElements.joinToString(", ") { it.text }
val generator = PyElementGenerator.getInstance(file.project)
val languageLevel = LanguageLevel.forElement(file)
val generatedStatement = generator.createFromImportStatement(languageLevel, path, imported, null)
val formattedStatement = CodeStyleManager.getInstance(file.project).reformat(generatedStatement)
statement.replace(formattedStatement)
}
fun findStatement(file: PsiFile, editor: Editor): PyFromImportStatement? {
val position = file.findElementAt(editor.caretModel.offset)
return PsiTreeUtil.getParentOfType(position, PyFromImportStatement::class.java, true, PyStatement::class.java)
}
}
| python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyConvertImportIntentionAction.kt | 1734966284 |
package zielu.gittoolbox.ui.blame
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.vfs.VirtualFile
internal data class LineInfo(
val file: VirtualFile,
val editor: Editor,
val document: Document,
val index: Int,
val generation: Int,
val modified: Boolean
) {
constructor(
file: VirtualFile,
editor: Editor,
document: Document,
index: Int,
generation: Int
) : this(file, editor, document, index, generation, document.isLineModified(index))
}
| src/main/kotlin/zielu/gittoolbox/ui/blame/LineInfo.kt | 3293147687 |
open class A(x: Int) {
}
class B(): A(5) {
fun m() {
A(<caret>3)
}
}
//Text: (<highlight>x: Int</highlight>), Disabled: false, Strikeout: false, Green: true | plugins/kotlin/idea/tests/testData/parameterInfo/functionCall/SimpleConstructor.kt | 4176853522 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.