content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package me.serce.solidity.lang.resolve.ref
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import me.serce.solidity.lang.completion.SolCompleter
import me.serce.solidity.lang.psi.*
import me.serce.solidity.lang.psi.impl.SolNewExpressionElement
import me.serce.solidity.lang.resolve.SolResolver
import me.serce.solidity.lang.resolve.canBeApplied
import me.serce.solidity.lang.resolve.function.SolFunctionResolver
import me.serce.solidity.lang.types.*
import me.serce.solidity.wrap
class SolUserDefinedTypeNameReference(element: SolUserDefinedTypeName) : SolReferenceBase<SolUserDefinedTypeName>(element), SolReference {
override fun multiResolve(): Collection<PsiElement> {
val parent = element.parent
if (parent is SolNewExpressionElement) {
return SolResolver.resolveNewExpression(parent)
}
return SolResolver.resolveTypeNameUsingImports(element)
}
override fun getVariants() = SolCompleter.completeTypeName(element)
}
class SolVarLiteralReference(element: SolVarLiteral) : SolReferenceBase<SolVarLiteral>(element), SolReference {
override fun multiResolve() = SolResolver.resolveVarLiteralReference(element)
override fun getVariants() = SolCompleter.completeLiteral(element).toList().toTypedArray()
}
class SolModifierReference(
element: SolReferenceElement,
private val modifierElement: SolModifierInvocationElement
) : SolReferenceBase<SolReferenceElement>(element), SolReference {
override fun calculateDefaultRangeInElement() = modifierElement.parentRelativeRange
override fun multiResolve(): List<SolNamedElement> {
val contract = modifierElement.findContract()!!
val superNames: List<String> = (contract.collectSupers.map { it.name } + contract.name).filterNotNull()
return SolResolver.resolveModifier(modifierElement)
.filter { it.contract.name in superNames }
}
override fun getVariants() = SolCompleter.completeModifier(modifierElement)
}
class SolMemberAccessReference(element: SolMemberAccessExpression) : SolReferenceBase<SolMemberAccessExpression>(element), SolReference {
override fun calculateDefaultRangeInElement(): TextRange {
return element.identifier?.parentRelativeRange ?: super.calculateDefaultRangeInElement()
}
override fun multiResolve() = SolResolver.resolveMemberAccess(element)
.mapNotNull { it.resolveElement() }
override fun getVariants() = SolCompleter.completeMemberAccess(element)
}
class SolNewExpressionReference(val element: SolNewExpression) : SolReferenceBase<SolNewExpression>(element), SolReference {
override fun calculateDefaultRangeInElement(): TextRange {
return element.referenceNameElement.parentRelativeRange
}
override fun multiResolve(): Collection<PsiElement> {
val types = SolResolver.resolveTypeNameUsingImports(element.referenceNameElement)
return types
.filterIsInstance(SolContractDefinition::class.java)
.flatMap {
val constructors = it.findConstructors()
if (constructors.isEmpty()) {
listOf(it)
} else {
constructors
}
}
}
}
fun SolContractDefinition.findConstructors(): List<SolElement> {
return if (this.constructorDefinitionList.isNotEmpty()) {
this.constructorDefinitionList
} else {
this.functionDefinitionList
.filter { it.name == this.name }
}
}
class SolFunctionCallReference(element: SolFunctionCallExpression) : SolReferenceBase<SolFunctionCallExpression>(element), SolReference {
override fun calculateDefaultRangeInElement(): TextRange {
return element.referenceNameElement.parentRelativeRange
}
fun resolveFunctionCall(): Collection<SolCallable> {
if (element.parent is SolRevertStatement) {
return SolResolver.resolveTypeNameUsingImports(element).filterIsInstance<SolErrorDefinition>()
}
if (element.firstChild is SolPrimaryExpression) {
val structs = SolResolver.resolveTypeNameUsingImports(element.firstChild).filterIsInstance<SolStructDefinition>()
if (structs.isNotEmpty()) {
return structs
}
}
val resolved: Collection<SolCallable> = when (val expr = element.expression) {
is SolPrimaryExpression -> {
val regular = expr.varLiteral?.let { SolResolver.resolveVarLiteral(it) }
?.filter { it !is SolStateVariableDeclaration }
?.filterIsInstance<SolCallable>()
?: emptyList()
val casts = resolveElementaryTypeCasts(expr)
regular + casts
}
is SolMemberAccessExpression -> {
resolveMemberFunctions(expr) + resolveFunctionCallUsingLibraries(expr)
}
else ->
emptyList()
}
return removeOverrides(resolved.groupBy { it.callablePriority }.entries.minByOrNull { it.key }?.value ?: emptyList())
}
private fun removeOverrides(callables: Collection<SolCallable>): Collection<SolCallable> {
val test = callables.filterIsInstance<SolFunctionDefinition>()
return callables
.filter {
when (it) {
is SolFunctionDefinition -> SolFunctionResolver.collectOverrides(it).intersect(test).isEmpty()
else -> true
}
}
}
private fun resolveElementaryTypeCasts(expr: SolPrimaryExpression): Collection<SolCallable> {
return expr.elementaryTypeName
?.let {
val type = getSolType(it)
object : SolCallable {
override fun resolveElement(): SolNamedElement? = null
override fun parseParameters(): List<Pair<String?, SolType>> = listOf(null to SolUnknown)
override fun parseType(): SolType = type
override val callablePriority: Int = 1000
override fun getName(): String? = null
}
}
.wrap()
}
private fun resolveMemberFunctions(expression: SolMemberAccessExpression): Collection<SolCallable> {
val name = expression.identifier?.text
return if (name != null) {
expression.expression.getMembers()
.filterIsInstance<SolCallable>()
.filter { it.getName() == name }
} else {
emptyList()
}
}
private fun resolveFunctionCallUsingLibraries(expression: SolMemberAccessExpression): Collection<SolCallable> {
val name = expression.identifier?.text
return if (name != null) {
val type = expression.expression.type
if (type != SolUnknown) {
val contract = expression.findContract()
val superContracts = contract
?.collectSupers
?.flatMap { SolResolver.resolveTypeNameUsingImports(it) }
?.filterIsInstance<SolContractDefinition>()
?: emptyList()
val libraries = (superContracts + contract.wrap())
.flatMap { it.usingForDeclarationList }
.filter {
val usingType = it.type
usingType == null || usingType == type
}
.mapNotNull { it.library }
return libraries
.distinct()
.flatMap { it.functionDefinitionList }
.filter { it.name == name }
.filter {
val firstParam = it.parameters.firstOrNull()
if (firstParam == null) {
false
} else {
getSolType(firstParam.typeName).isAssignableFrom(type)
}
}
.map { it.toLibraryCallable() }
} else {
emptyList()
}
} else {
emptyList()
}
}
private fun SolFunctionDefinition.toLibraryCallable(): SolCallable {
return object : SolCallable {
override fun parseParameters(): List<Pair<String?, SolType>> = [email protected]().drop(1)
override fun parseType(): SolType = [email protected]()
override fun resolveElement() = this@toLibraryCallable
override fun getName() = name
override val callablePriority = 0
}
}
override fun multiResolve(): Collection<PsiElement> {
return resolveFunctionCallAndFilter()
.mapNotNull { it.resolveElement() }
}
fun resolveFunctionCallAndFilter(): List<SolCallable> {
return resolveFunctionCall()
.filter { it.canBeApplied(element.functionCallArguments) }
}
}
| src/main/kotlin/me/serce/solidity/lang/resolve/ref/refs.kt | 3589551953 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.base.facet
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.workspaceModel.ide.WorkspaceModelTopics
import org.jetbrains.kotlin.idea.base.facet.platform.platform
import org.jetbrains.kotlin.idea.base.util.caching.SynchronizedFineGrainedEntityCache
import org.jetbrains.kotlin.idea.base.util.caching.ModuleEntityChangeListener
import org.jetbrains.kotlin.platform.jvm.isJvm
@Service(Service.Level.PROJECT)
class JvmOnlyProjectChecker(project: Project) : SynchronizedFineGrainedEntityCache<Unit, Boolean>(project, cleanOnLowMemory = false) {
override fun subscribe() {
val busConnection = project.messageBus.connect(this)
WorkspaceModelTopics.getInstance(project).subscribeImmediately(busConnection, ModelChangeListener(project))
}
override fun checkKeyValidity(key: Unit) {}
override fun calculate(key: Unit): Boolean {
return ModuleManager.getInstance(project).modules.all { module ->
ProgressManager.checkCanceled()
module.platform.isJvm()
}
}
internal class ModelChangeListener(project: Project) : ModuleEntityChangeListener(project) {
override fun entitiesChanged(outdated: List<Module>) = getInstance(project).invalidate()
}
companion object {
fun getInstance(project: Project): JvmOnlyProjectChecker = project.service()
}
} | plugins/kotlin/base/facet/src/org/jetbrains/kotlin/idea/base/facet/JvmOnlyProjectChecker.kt | 3377678121 |
// FIR_COMPARISON
package test
fun usage(): P<caret> {}
// ABSENT: PrivateTopLevelClass
// ABSENT: PublicNestedClass
// ABSENT: ProtectedNestedClass
// ABSENT: PrivateNestedClass
// ABSENT: PublicInnerClass
// ABSENT: ProtectedInnerClass
// ABSENT: PrivateInnerClass
| plugins/kotlin/completion/tests/testData/basic/multifile/NotImportedNestedClassFromPrivateClass/NotImportedNestedClassFromPrivateClass.kt | 3509982586 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage.impl.url
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.jetbrains.annotations.TestOnly
import java.io.File
import java.nio.file.Path
/**
* Represent an URL (in VFS format) of a file or directory.
*/
open class VirtualFileUrlImpl(val id: Int, internal val manager: VirtualFileUrlManagerImpl): VirtualFileUrl {
private var cachedUrl: String? = null
override fun getUrl(): String {
if (cachedUrl == null) {
cachedUrl = manager.getUrlById(id)
}
return cachedUrl!!
}
override fun getFileName(): String = url.substringAfterLast('/')
override fun getPresentableUrl(): String {
val calculatedUrl = this.url
if (calculatedUrl.startsWith("file://")) {
return calculatedUrl.substring("file://".length)
}
else if (calculatedUrl.startsWith("jar://")) {
val removedSuffix = calculatedUrl.removeSuffix("!/").removeSuffix("!")
return removedSuffix.substring("jar://".length)
}
return calculatedUrl
}
override fun getSubTreeFileUrls() = manager.getSubtreeVirtualUrlsById(this)
override fun append(relativePath: String): VirtualFileUrl = manager.append(this, relativePath.removePrefix("/"))
override fun toString(): String = this.url
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as VirtualFileUrlImpl
if (id != other.id) return false
return true
}
override fun hashCode(): Int = id
}
// TODO It's possible to write it without additional string allocations besides absolutePath
/**
* Do not use io version in production code as FSD filesystems are incompatible with java.io
*/
@TestOnly
fun File.toVirtualFileUrl(virtualFileManager: VirtualFileUrlManager): VirtualFileUrl = virtualFileManager.fromPath(absolutePath)
fun Path.toVirtualFileUrl(virtualFileManager: VirtualFileUrlManager): VirtualFileUrl = virtualFileManager.fromPath(toAbsolutePath().toString())
| platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/url/VirtualFileUrlImpl.kt | 2563762051 |
// snippet-sourcedescription:[ListTextTranslationJobs.kt demonstrates how to list all translation jobs.]
// snippet-keyword:[SDK for Kotlin]
// snippet-service:[Amazon Translate]
package com.kotlin.translate
// snippet-start:[translate.kotlin._list_jobs.import]
import aws.sdk.kotlin.services.translate.TranslateClient
import aws.sdk.kotlin.services.translate.model.ListTextTranslationJobsRequest
// snippet-end:[translate.kotlin._list_jobs.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() {
getTranslationJobs()
}
// snippet-start:[translate.kotlin._list_jobs.main]
suspend fun getTranslationJobs() {
val textTranslationJobsRequest = ListTextTranslationJobsRequest {
maxResults = 10
}
TranslateClient { region = "us-west-2" }.use { translateClient ->
val response = translateClient.listTextTranslationJobs(textTranslationJobsRequest)
response.textTranslationJobPropertiesList?.forEach { prop ->
println("The job name is ${prop.jobName}")
println("The job id is: ${prop.jobId}")
}
}
}
// snippet-end:[translate.kotlin._list_jobs.main]
| kotlin/services/translate/src/main/kotlin/com/kotlin/translate/ListTextTranslationJobs.kt | 1388080003 |
/*
* 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.jclouds.vsphere.functions
import com.google.common.base.*
import com.google.common.base.Function
import com.google.common.base.Predicates.not
import com.google.common.collect.Iterables.filter
import com.google.common.collect.Lists
import com.google.common.collect.Sets.newHashSet
import com.google.common.net.InetAddresses
import com.google.inject.Inject
import com.google.inject.Singleton
import com.vmware.vim25.VirtualMachinePowerState
import com.vmware.vim25.VirtualMachineToolsStatus
import com.vmware.vim25.mo.InventoryNavigator
import com.vmware.vim25.mo.VirtualMachine
import org.jclouds.compute.domain.NodeMetadata
import org.jclouds.compute.domain.NodeMetadata.Status
import org.jclouds.compute.domain.NodeMetadataBuilder
import org.jclouds.compute.reference.ComputeServiceConstants
import org.jclouds.domain.LocationBuilder
import org.jclouds.domain.LocationScope
import org.jclouds.logging.Logger
import org.jclouds.util.InetAddresses2
import org.jclouds.util.Predicates2
import org.jclouds.vsphere.domain.VSphereServiceInstance
import org.jclouds.vsphere.predicates.VSpherePredicate
import java.net.Inet4Address
import java.net.Inet6Address
import java.net.URI
import java.net.URISyntaxException
import java.util.concurrent.TimeUnit
import javax.annotation.Resource
import javax.inject.Named
import javax.inject.Provider
@Singleton
class VirtualMachineToNodeMetadata
@Inject
constructor(val serviceInstanceSupplier: Supplier<VSphereServiceInstance>,
var toPortableNodeStatus: Provider<Map<VirtualMachinePowerState, Status>>) : Function<VirtualMachine, NodeMetadata> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected var logger = Logger.NULL
override fun apply(vm: VirtualMachine?): NodeMetadata? {
var freshVm: VirtualMachine? = null
var virtualMachineName = ""
val nodeMetadataBuilder = NodeMetadataBuilder()
try {
serviceInstanceSupplier.get().use { instance ->
val vmMORId = vm!!.mor._value
val vms = InventoryNavigator(instance.instance.rootFolder).searchManagedEntities("VirtualMachine")
for (machine in vms) {
if (machine.mor.getVal() == vmMORId) {
freshVm = machine as VirtualMachine
break
}
}
val locationBuilder = LocationBuilder().apply {
description("")
id("")
scope(LocationScope.HOST)
}
if (freshVm == null) {
nodeMetadataBuilder.status(Status.ERROR).id("")
return nodeMetadataBuilder.build()
}
virtualMachineName = freshVm!!.name
logger.trace("<< converting vm ($virtualMachineName) to NodeMetadata")
val vmState = freshVm!!.runtime.getPowerState()
var nodeState: Status? = toPortableNodeStatus.get()[vmState]
if (nodeState == null)
nodeState = Status.UNRECOGNIZED
nodeMetadataBuilder.name(virtualMachineName).ids(virtualMachineName).location(locationBuilder.build()).hostname(virtualMachineName)
val host = freshVm!!.serverConnection.url.host
try {
nodeMetadataBuilder.uri(URI("https://" + host + ":9443/vsphere-client/vmrc/vmrc.jsp?vm=urn:vmomi:VirtualMachine:" + vmMORId + ":" + freshVm!!.summary.getConfig().getUuid()))
} catch (e: URISyntaxException) {
}
val ipv4Addresses = newHashSet<String>()
val ipv6Addresses = newHashSet<String>()
if (nodeState == Status.RUNNING && !freshVm!!.config.isTemplate &&
VSpherePredicate.IsToolsStatusEquals(VirtualMachineToolsStatus.toolsOk).apply(freshVm) &&
VSpherePredicate.isNicConnected(freshVm)) {
Predicates2.retry(Predicate<com.vmware.vim25.mo.VirtualMachine> { vm ->
try {
return@Predicate !Strings.isNullOrEmpty(vm!!.guest.getIpAddress())
} catch (e: Exception) {
return@Predicate false
}
}, 60 * 1000 * 10.toLong(), (10 * 1000).toLong(), TimeUnit.MILLISECONDS).apply(freshVm)
}
if (VSpherePredicate.IsToolsStatusIsIn(Lists.newArrayList(VirtualMachineToolsStatus.toolsNotInstalled, VirtualMachineToolsStatus.toolsNotRunning)).apply(freshVm))
logger.trace("<< No VMware tools installed or not running ( $virtualMachineName )")
else if (nodeState == Status.RUNNING && not(VSpherePredicate.isTemplatePredicate).apply(freshVm)) {
var retries = 0
while (ipv4Addresses.size < 1) {
ipv4Addresses.clear()
ipv6Addresses.clear()
val nics = freshVm!!.guest.getNet()
var nicConnected = false
if (null != nics) {
for (nic in nics) {
nicConnected = nicConnected || nic.connected
val addresses = nic.getIpAddress()
if (null != addresses) {
for (address in addresses) {
if (logger.isTraceEnabled)
logger.trace("<< find IP addresses $address for $virtualMachineName")
if (isInet4Address(address)) {
ipv4Addresses.add(address)
} else if (isInet6Address(address)) {
ipv6Addresses.add(address)
}
}
}
}
}
if (toPortableNodeStatus.get()[freshVm!!.runtime.getPowerState()] != Status.RUNNING) {
logger.trace(">> Node is not running. EXIT IP search.")
break
}
if (freshVm!!.guest.getToolsVersionStatus2() == "guestToolsUnmanaged" && nics == null) {
val ip = freshVm!!.guest.getIpAddress()
if (!Strings.isNullOrEmpty(ip)) {
if (isInet4Address(ip)) {
ipv4Addresses.add(ip)
} else if (isInet6Address(ip)) {
ipv6Addresses.add(ip)
}
}
break
}
if (!nicConnected && retries == 5) {
logger.trace("<< VM does NOT have any NIC connected.")
break
}
if (ipv4Addresses.size < 1 && null != nics) {
logger.warn("<< can't find IPv4 address for vm: " + virtualMachineName)
retries++
Thread.sleep(6000)
}
if (ipv4Addresses.size < 1 && retries == 15) {
logger.error("<< can't find IPv4 address after $retries retries for vm: $virtualMachineName")
break
}
}
nodeMetadataBuilder.publicAddresses(filter(ipv4Addresses, not<String>(isPrivateAddress)))
nodeMetadataBuilder.privateAddresses(filter(ipv4Addresses, isPrivateAddress))
}
nodeMetadataBuilder.status(nodeState)
return nodeMetadataBuilder.build()
}
} catch (t: Throwable) {
logger.error("Got an exception for virtual machine name : " + virtualMachineName)
logger.error("The exception is : " + t.toString())
Throwables.propagate(t)
return nodeMetadataBuilder.build()
}
}
companion object {
private val isPrivateAddress = { addr: String? -> InetAddresses2.IsPrivateIPAddress.INSTANCE.apply(addr) }
private val isInet4Address = { input: String? ->
try {
// Note we can do this, as InetAddress is now on the white list
InetAddresses.forString(input) is Inet4Address
} catch (e: IllegalArgumentException) {
// could be a hostname
false
}
}
private val isInet6Address = { input: String? ->
try {
// Note we can do this, as InetAddress is now on the white list
InetAddresses.forString(input) is Inet6Address
} catch (e: IllegalArgumentException) {
// could be a hostname
false
}
}
}
}
| src/main/kotlin/org/jclouds/vsphere/functions/VirtualMachineToNodeMetadata.kt | 2988587144 |
package net.nemerosa.ontrack.repository
import net.nemerosa.ontrack.model.Ack
import net.nemerosa.ontrack.model.labels.LabelForm
interface LabelRepository {
/**
* Creation of a new label
*/
fun newLabel(form: LabelForm): LabelRecord
/**
* Creates an automated label, overriding any manual one
*/
fun overrideLabel(form: LabelForm, providerId: String): LabelRecord
/**
* Gets a label by its ID
*/
fun getLabel(labelId: Int): LabelRecord
/**
* Updates a label
*/
fun updateLabel(labelId: Int, form: LabelForm): LabelRecord
/**
* Updates a automated label
*/
fun updateAndOverrideLabel(labelId: Int, form: LabelForm, providerId: String): LabelRecord
/**
* Deletes a label
*/
fun deleteLabel(labelId: Int): Ack
/**
* Gets the list of existing label for the given provider id ("computed by")
*/
fun findLabelsByProvider(providerId: String): List<LabelRecord>
/**
* Finds a single record for the given attributes.
*/
fun findLabelByCategoryAndNameAndProvider(category: String?, name: String, providerId: String): LabelRecord?
/**
* Finds a list of labels using their category and/or name.
*/
fun findLabels(category: String?, name: String?): List<LabelRecord>
/**
* Gets list of all labels, ordered by category and name
*/
val labels: List<LabelRecord>
}
| ontrack-repository/src/main/java/net/nemerosa/ontrack/repository/LabelRepository.kt | 1349658386 |
package top.zbeboy.isy.web.vo.data.politics
import javax.validation.constraints.NotNull
import javax.validation.constraints.Size
/**
* Created by zbeboy 2017-12-12 .
**/
open class PoliticsVo {
var politicalLandscapeId: Int? = null
@NotNull
@Size(max = 30)
var politicalLandscapeName: String? = null
} | src/main/java/top/zbeboy/isy/web/vo/data/politics/PoliticsVo.kt | 906055394 |
package co.smartreceipts.android.identity.apis.me
import co.smartreceipts.android.apis.gson.SmartReceiptsGsonBuilder
import co.smartreceipts.android.date.Iso8601DateFormat
import co.smartreceipts.android.model.ColumnDefinitions
import co.smartreceipts.android.model.Receipt
import co.smartreceipts.core.identity.apis.me.MeResponse
import com.google.gson.Gson
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.MockitoAnnotations
import org.robolectric.RobolectricTestRunner
import java.util.*
@RunWith(RobolectricTestRunner::class)
class MeResponseTest {
companion object {
private const val JSON_EMPTY = "" +
"{\n" +
"}"
private const val OLD_ME_RESPONSE_JSON = "{\n" +
" \"user\":{\n" +
" \"id\":\"1234\",\n" +
" \"email\":\"[email protected]\",\n" +
" \"created_at\":1410400000,\n" +
" \"name\":\"Name\",\n" +
" \"display_name\":\"Display Name\",\n" +
" \"provider\":\"Provider\",\n" +
" \"registration_ids\":[\n" +
" \"REGISTRATION_ID\"\n" +
" ],\n" +
" \"confirmed_at\":\"2014-09-22T11:06:33.556Z\",\n" +
" \"confirmation_sent_at\":null,\n" +
" \"cognito_token\":\"COGNITO_TOKEN\",\n" +
" \"cognito_token_expires_at\":1538076327,\n" +
" \"identity_id\":\"IDENTITY_ID\",\n" +
" \"recognitions_available\":359\n" +
" }\n" +
"}"
private const val NEW_ME_RESPONSE_JSON = "{\n" +
" \"user\":{\n" +
" \"id\":\"1234\",\n" +
" \"email\":\"[email protected]\",\n" +
" \"created_at_iso8601\":\"2014-09-11T03:00:12.368Z\",\n" +
" \"name\":\"Name\",\n" +
" \"display_name\":\"Display Name\",\n" +
" \"provider\":\"Provider\",\n" +
" \"registration_ids\":[\n" +
" \"REGISTRATION_ID\"\n" +
" ],\n" +
" \"confirmed_at_iso8601\":\"2014-09-22T11:06:33.556Z\",\n" +
" \"confirmation_sent_at_iso8601\":null,\n" +
" \"cognito_token\":\"COGNITO_TOKEN\",\n" +
" \"cognito_token_expires_at_iso8601\":\"2015-09-22T11:06:33.556Z\",\n" +
" \"identity_id\":\"IDENTITY_ID\",\n" +
" \"recognitions_available\":359\n" +
" }\n" +
"}"
}
@Mock
lateinit var columnDefinitions: ColumnDefinitions<Receipt>
lateinit var gson: Gson
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
gson = SmartReceiptsGsonBuilder(columnDefinitions).create()
}
@Test
fun deserializeEmptyResponse() {
val response = gson.fromJson<MeResponse>(MeResponseTest.JSON_EMPTY, MeResponse::class.java)
assertNotNull(response)
assertNull(response.user)
}
@Test
fun deserializeOldResponseFormat() {
val response = gson.fromJson<MeResponse>(MeResponseTest.OLD_ME_RESPONSE_JSON, MeResponse::class.java)
assertNotNull(response)
assertNotNull(response.user)
val user = response.user!!
assertEquals("1234", user.id)
assertEquals("[email protected]", user.email)
assertEquals("Name", user.name)
assertEquals("Display Name", user.displayName)
assertEquals("REGISTRATION_ID", user.registrationIds?.get(0))
assertEquals("COGNITO_TOKEN", user.cognitoToken)
assertEquals(Date(1538076327L), user.cognitoTokenExpiresAt)
assertEquals("IDENTITY_ID", user.identityId)
assertEquals(359, user.recognitionsAvailable)
}
@Test
fun deserializeNewResponseFormat() {
val response = gson.fromJson<MeResponse>(MeResponseTest.NEW_ME_RESPONSE_JSON, MeResponse::class.java)
assertNotNull(response)
assertNotNull(response.user)
val user = response.user!!
assertEquals("1234", user.id)
assertEquals("[email protected]", user.email)
assertEquals("Name", user.name)
assertEquals("Display Name", user.displayName)
assertEquals("REGISTRATION_ID", user.registrationIds?.get(0))
assertEquals("COGNITO_TOKEN", user.cognitoToken)
assertEquals(Iso8601DateFormat().parse("2015-09-22T11:06:33.556Z"), user.cognitoTokenExpiresAt)
assertEquals("IDENTITY_ID", user.identityId)
assertEquals(359, user.recognitionsAvailable)
}
} | app/src/test/java/co/smartreceipts/android/identity/apis/me/MeResponseTest.kt | 3543419982 |
package eu.mc80.java.fizzbuzz
import java.util.stream.IntStream
import java.util.stream.Stream
interface FizzBuzzMapper {
fun map(range: IntStream?): Stream<String>
}
| src/main/kotlin/eu/mc80/java/fizzbuzz/FizzBuzzMapper.kt | 551456350 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.nbt.tags
import java.io.DataOutputStream
class TagShort(override val value: Short) : NbtValueTag<Short>(Short::class.java) {
override val payloadSize = 2
override val typeId = NbtTypeId.SHORT
override fun write(stream: DataOutputStream) {
stream.writeShort(value.toInt())
}
override fun toString() = toString(StringBuilder(), 0, WriterState.COMPOUND).toString()
override fun toString(sb: StringBuilder, indentLevel: Int, writerState: WriterState) =
sb.append(value).append('S')!!
}
| src/main/kotlin/com/demonwav/mcdev/nbt/tags/TagShort.kt | 4043956467 |
package com.almasb.fxdocs
import java.util.*
typealias D = String
/**
*
*
* @author Almas Baimagambetov ([email protected])
*/
fun main(args: Array<String>) {
val D0 = "ab abc cd abd ef e ge bc"
decompose(D0).forEach(::println)
}
private fun decompose(D0: D): List<D> {
println("Decomposing...")
val tokens = D0.split(" +".toRegex()).toMutableList()
println(tokens)
val elements = ArrayDeque<Char>()
val result = arrayListOf<D>()
while (tokens.isNotEmpty()) {
var D1 = ""
elements.add(tokens[0][0])
var usedElements = "" + elements.first
while (elements.isNotEmpty()) {
val e = elements.pop()
val iter = tokens.iterator()
while (iter.hasNext()) {
val token = iter.next()
if (token.contains(e)) {
D1 += token + " "
token.filter { !usedElements.contains(it) }.forEach {
elements.add(it)
usedElements += it
}
iter.remove()
}
}
}
result.add(D1.trim())
}
return result
} | src/main/java/com/almasb/fxdocs/Testk.kt | 4254904639 |
// Copyright 2017-07-21 PlanBase Inc. & Glen Peterson
//
// 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.
import com.planbase.pdf.lm2.PdfLayoutMgr
import com.planbase.pdf.lm2.PdfLayoutMgr.Companion.DEFAULT_MARGIN
import com.planbase.pdf.lm2.attributes.Orientation.*
import com.planbase.pdf.lm2.attributes.*
import com.planbase.pdf.lm2.attributes.Align.*
import com.planbase.pdf.lm2.contents.Cell
import com.planbase.pdf.lm2.contents.ScaledImage
import com.planbase.pdf.lm2.contents.Table
import com.planbase.pdf.lm2.contents.Text
import com.planbase.pdf.lm2.pages.SinglePage
import com.planbase.pdf.lm2.utils.BULLET_CHAR
import com.planbase.pdf.lm2.utils.CMYK_BLACK
import com.planbase.pdf.lm2.utils.Coord
import com.planbase.pdf.lm2.utils.Dim
import org.apache.pdfbox.pdmodel.common.PDRectangle
import org.apache.pdfbox.pdmodel.font.PDType1Font
import org.apache.pdfbox.pdmodel.graphics.color.PDColor
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceCMYK
import java.io.File
import java.io.FileOutputStream
import javax.imageio.ImageIO
import kotlin.test.Test
import kotlin.test.assertEquals
/**
* Another how-to-use example file
*/
class TestManual2 {
@Test
fun testBody() {
// Nothing happens without a PdfLayoutMgr.
val pageMgr = PdfLayoutMgr(PDDeviceCMYK.INSTANCE, Dim(PDRectangle.A6))
val bodyWidth = PDRectangle.A6.width - 80.0
val f = File("target/test-classes/graph2.png")
// println(f.absolutePath)
val graphPic = ImageIO.read(f)
val lp = pageMgr.startPageGrouping(
PORTRAIT,
a6PortraitBody,
{ pageNum:Int, pb: SinglePage ->
val isLeft = pageNum % 2 == 1
val leftMargin:Double = if (isLeft) 37.0 else 45.0
// System.out.println("pageNum " + pageNum);
pb.drawLine(Coord(leftMargin, 30.0), Coord(leftMargin + bodyWidth, 30.0),
LineStyle(CMYK_THISTLE))
pb.drawStyledText(Coord(leftMargin, 20.0), TextStyle(PDType1Font.HELVETICA, 9.0, CMYK_BLACK),
"Page # " + pageNum, true)
leftMargin })
val bulletTextCellStyle = CellStyle(
Align.TOP_LEFT, BoxStyle(
Padding.NO_PADDING, CMYK_PALE_PEACH,
BorderStyle(
LineStyle.NO_LINE, LineStyle(CMYK_QUEEN_PINK),
LineStyle.NO_LINE, LineStyle.NO_LINE
)))
// Don't make bullets like this. See WrappedListTest for the right way to do it.
val bulletTable: Table = Table().addCellWidths(30.0, bodyWidth - 30.0)
.startRow()
.cell(BULLET_CELL_STYLE, listOf(Text(BULLET_TEXT_STYLE, BULLET_CHAR)))
.cell(bulletTextCellStyle, listOf(Text(BULLET_TEXT_STYLE, "This is some text that has a bullet")))
.endRow()
.startRow()
.cell(BULLET_CELL_STYLE, listOf(Text(BULLET_TEXT_STYLE, "2.")))
.cell(bulletTextCellStyle, listOf(Text(BULLET_TEXT_STYLE, "Text that has a number")))
.endRow()
val bodyCellStyle = CellStyle(TOP_LEFT_JUSTIFY, BoxStyle(Padding(2.0), CMYK_PALE_PEACH, BorderStyle(CMYK_QUEEN_PINK)))
val bodyCellContinuation = CellStyle(TOP_LEFT_JUSTIFY, BoxStyle(Padding(2.0, 2.0, 8.0, 2.0), CMYK_PALE_PEACH,
BorderStyle(
LineStyle.NO_LINE,
LineStyle(CMYK_QUEEN_PINK),
LineStyle.NO_LINE,
LineStyle(CMYK_QUEEN_PINK))))
val imageCell = CellStyle(TOP_CENTER, BoxStyle(Padding(0.0, 0.0, 8.0, 0.0), CMYK_PALE_PEACH,
BorderStyle(
LineStyle.NO_LINE,
LineStyle(CMYK_QUEEN_PINK),
LineStyle.NO_LINE,
LineStyle(CMYK_QUEEN_PINK))))
val heading = Cell(CellStyle(BOTTOM_LEFT,
BoxStyle(Padding(10.0, 2.0, 0.0, 2.0), CMYK_PALE_PEACH,
BorderStyle(LineStyle(CMYK_VIOLET, 1.0)))),
bodyWidth,
listOf(Text(HEADING_TEXT_STYLE, "Some Heading")))
var coord = Coord(0.0, pageMgr.pageDim.height - 40.0)
var dap: DimAndPageNums =
lp.add(coord,
Cell(bodyCellStyle,
bodyWidth,
listOf(Text(BULLET_TEXT_STYLE,
"The long "),
Text(TextStyle(PDType1Font.HELVETICA_BOLD, 18.0, CMYK_BLACK),
"families"),
Text(BULLET_TEXT_STYLE,
" needed the national words and women said new."))).wrap())
assertEquals(IntRange(1, 1), dap.pageNums)
coord = coord.minusY(dap.dim.height)
dap = lp.add(coord, heading.wrap())
assertEquals(IntRange(1, 1), dap.pageNums)
coord = coord.minusY(dap.dim.height + 0.5)
dap = lp.add(coord, Cell(bodyCellContinuation, bodyWidth,
listOf(Text(BULLET_TEXT_STYLE,
"The new companies told the possible hands that the books" +
" were low."))).wrap())
assertEquals(IntRange(1, 1), dap.pageNums)
coord = coord.minusY(dap.dim.height)
dap = lp.add(coord, bulletTable.wrap())
assertEquals(IntRange(1, 1), dap.pageNums)
coord = coord.minusY(dap.dim.height)
dap = lp.add(coord, Cell(bodyCellContinuation, bodyWidth,
listOf(Text(BULLET_TEXT_STYLE,
"The new companies told the possible hands and books was low. " +
"The other questions got the recent children and lots felt" +
" important."))).wrap())
assertEquals(IntRange(1, 1), dap.pageNums)
coord = coord.minusY(dap.dim.height)
dap = lp.add(coord, Cell(imageCell, bodyWidth, listOf(ScaledImage(graphPic))).wrap())
assertEquals(IntRange(1, 1), dap.pageNums)
coord = coord.minusY(dap.dim.height)
dap = lp.add(coord, Cell(bodyCellContinuation, bodyWidth,
listOf(Text(BULLET_TEXT_STYLE,
"The hard eyes seemed the clear mothers and systems came economic. " +
"The high months showed the possible money and eyes heard certain." +
"People played the different facts and areas showed large. "))).wrap())
assertEquals(IntRange(1, 2), dap.pageNums)
coord = coord.minusY(dap.dim.height)
dap = lp.add(coord, heading.wrap())
assertEquals(IntRange(2, 2), dap.pageNums)
coord = coord.minusY(dap.dim.height + 0.5)
dap = lp.add(coord, Cell(bodyCellContinuation, bodyWidth,
listOf(Text(BULLET_TEXT_STYLE,
"The good ways lived the different countries and stories found good." +
" The certain places found the political months and facts told easy." +
" The long homes ran the good governments and cases lived social."),
ScaledImage(graphPic),
Text(BULLET_TEXT_STYLE,
("The social people ran the local cases and men left local. The " +
"easy areas saw the whole times and systems. The major rights " +
"was the important children and mothers turned unimaginatively.")),
ScaledImage(graphPic),
Text(BULLET_TEXT_STYLE,
("The best points got the economic waters " +
"and problems gave great. The whole " +
"countries went the best children and " +
"eyes became able to see clearly.")))).wrap())
assertEquals(IntRange(2, 3), dap.pageNums)
coord = coord.minusY(dap.dim.height)
lp.drawLine(coord, coord.plusX(bodyWidth), LineStyle(CMYK_QUEEN_PINK))
pageMgr.commit()
// We're just going to write to a file.
val os = FileOutputStream("test2.pdf")
// Commit it to the output stream!
pageMgr.save(os)
}
companion object {
val CMYK_COOL_GRAY = PDColor(floatArrayOf(0.13f, 0.2f, 0f, 0.57f), PDDeviceCMYK.INSTANCE)
val CMYK_LIGHT_GREEN = PDColor(floatArrayOf(0.05f, 0f, 0.1f, 0.01f), PDDeviceCMYK.INSTANCE)
val CMYK_QUEEN_PINK = PDColor(floatArrayOf(0.0f, 0.11f, 0f, 0.09f), PDDeviceCMYK.INSTANCE)
val CMYK_PALE_PEACH = PDColor(floatArrayOf(0.0f, 0.055f, 0.06f, 0f), PDDeviceCMYK.INSTANCE)
val CMYK_THISTLE = PDColor(floatArrayOf(0.05f, 0.19f, 0f, 0.09f), PDDeviceCMYK.INSTANCE)
val CMYK_VIOLET = PDColor(floatArrayOf(0.46f, 0.48f, 0f, 0f), PDDeviceCMYK.INSTANCE)
val a6PortraitBody = PageArea(Coord(DEFAULT_MARGIN, PDRectangle.A6.height - DEFAULT_MARGIN),
Dim(PDRectangle.A6).minus(Dim(DEFAULT_MARGIN * 2, DEFAULT_MARGIN * 2)))
internal val BULLET_CELL_STYLE = CellStyle(TOP_RIGHT,
BoxStyle(Padding(0.0, 4.0, 15.0, 0.0), CMYK_PALE_PEACH,
BorderStyle(
LineStyle.NO_LINE, LineStyle.NO_LINE,
LineStyle.NO_LINE, LineStyle(CMYK_QUEEN_PINK))))
internal val BULLET_TEXT_STYLE = TextStyle(PDType1Font.HELVETICA, 12.0, CMYK_BLACK, "BULLET_TEXT_STYLE")
internal val HEADING_TEXT_STYLE = TextStyle(PDType1Font.TIMES_BOLD, 16.0, CMYK_COOL_GRAY, "HEADING_TEXT_STYLE")
}
} | src/test/java/TestManual2.kt | 1435453777 |
// 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.customize.transferSettings.ui
import com.intellij.ide.customize.transferSettings.models.BaseIdeVersion
import com.intellij.ui.JBColor
import com.intellij.ui.components.JBScrollPane
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import javax.swing.JList
import javax.swing.ListModel
import javax.swing.ListSelectionModel
import javax.swing.ScrollPaneConstants
import javax.swing.event.ListSelectionEvent
class TransferSettingsLeftPanel(listModel: ListModel<BaseIdeVersion>) : JBScrollPane(JList(listModel)) {
val list get() = (viewport.view as JList<BaseIdeVersion>)
private var previousSelectedIndex = -1
init {
list.apply {
selectionMode = ListSelectionModel.SINGLE_SELECTION
cellRenderer = TransferSettingsLeftPanelItemRenderer()
}
border = JBUI.Borders.customLine(JBColor.border(), 1, 0, 0, 1)
background = UIUtil.getListBackground()
horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
}
fun addListSelectionListener(action: JList<BaseIdeVersion>.(ListSelectionEvent) -> Unit) {
list.addListSelectionListener s2@{
if (list.selectedIndex == previousSelectedIndex) return@s2
previousSelectedIndex = list.selectedIndex
action(list, it)
}
}
} | platform/platform-impl/src/com/intellij/ide/customize/transferSettings/ui/TransferSettingsLeftPanel.kt | 2248747293 |
// 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 training.ui
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.ui.AbstractPainter
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.wm.IdeGlassPane
import com.intellij.ui.ColorUtil
import com.intellij.ui.JBColor
import com.intellij.ui.paint.RectanglePainter
import com.intellij.util.ui.TimerUtil
import java.awt.*
import java.util.*
import javax.swing.*
import javax.swing.tree.TreePath
import kotlin.math.absoluteValue
private const val pulsationSize = 20
object LearningUiHighlightingManager {
data class HighlightingOptions(
val highlightBorder: Boolean = true,
val highlightInside: Boolean = true,
val usePulsation: Boolean = false,
val clearPreviousHighlights: Boolean = true,
)
private val highlights: MutableList<RepaintHighlighting<*>> = ArrayList()
val highlightingComponents: List<Component> get() = highlights.map { it.original }
val highlightingComponentsWithInfo: List<Pair<Component, () -> Any?>> get() = highlights.map { it.original to it.partInfo }
fun highlightComponent(original: Component, options: HighlightingOptions = HighlightingOptions()) {
highlightPartOfComponent(original, options) { Rectangle(Point(0, 0), it.size) }
}
fun highlightJListItem(list: JList<*>,
options: HighlightingOptions = HighlightingOptions(),
index: () -> Int?) {
highlightPartOfComponent(list, options, { index() }) l@{
index()?.let {
if (it in 0 until list.model.size) list.getCellBounds(it, it) else null
}
}
}
fun highlightJTreeItem(tree: JTree,
options: HighlightingOptions = HighlightingOptions(),
path: () -> TreePath?) {
highlightPartOfComponent(tree, options) {
path()?.let { tree.getPathBounds(it) }
}
}
fun <T : Component> highlightPartOfComponent(component: T,
options: HighlightingOptions = HighlightingOptions(),
partInfo: () -> Any? = { null },
rectangle: (T) -> Rectangle?) {
highlightComponent(component, options.clearPreviousHighlights) {
RepaintHighlighting(component, options, partInfo) l@{
val rect = rectangle(component) ?: return@l null
if (component !is JComponent) return@l rect
component.visibleRect.intersection(rect).takeIf { !it.isEmpty }
}
}
}
fun clearHighlights() {
runInEdt {
for (core in highlights) {
removeIt(core)
}
highlights.clear()
}
}
private fun highlightComponent(original: Component,
clearPreviousHighlights: Boolean,
init: () -> RepaintHighlighting<*>) {
runInEdt {
if (clearPreviousHighlights) clearHighlights()
if (!original.isShowing) return@runInEdt // this check is required in rare cases when highlighting called after restore
val repaintByTimer = init()
repaintByTimer.reinitHighlightComponent()
repaintByTimer.initTimer()
highlights.add(repaintByTimer)
}
}
internal fun removeIt(core: RepaintHighlighting<*>) {
core.removed = true
core.cleanup()
}
fun getRectangle(original: Component): Rectangle? =
highlights.find { it.original == original }?.rectangle?.invoke()
}
internal class RepaintHighlighting<T : Component>(val original: T,
val options: LearningUiHighlightingManager.HighlightingOptions,
val partInfo: () -> Any?,
val rectangle: () -> Rectangle?
) {
var removed = false
private val startDate = Date()
private var listLocationOnScreen: Point? = null
private var cellBoundsInList: Rectangle? = null
private var highlightPainter: LearningHighlightPainter? = null
private val pulsationOffset = if (options.usePulsation) pulsationSize else 0
private var disposable: Disposable? = null
fun initTimer() {
val timer = TimerUtil.createNamedTimer("IFT item", 50)
timer.addActionListener {
if (!original.isShowing || original.bounds.isEmpty) {
LearningUiHighlightingManager.removeIt(this)
}
if (this.removed) {
timer.stop()
return@addActionListener
}
if (shouldReinit()) {
cleanup()
reinitHighlightComponent()
}
highlightPainter?.setNeedsRepaint(true)
}
timer.start()
}
fun cleanup() {
disposable?.let {
Disposer.dispose(it)
disposable = null
}
highlightPainter = null
}
private fun shouldReinit(): Boolean {
return highlightPainter == null || original.locationOnScreen != listLocationOnScreen || rectangle() != cellBoundsInList
}
fun reinitHighlightComponent() {
val cellBounds = rectangle() ?: return
cleanup()
val pt = SwingUtilities.convertPoint(original, cellBounds.location, SwingUtilities.getRootPane(original).glassPane)
val bounds = Rectangle(pt.x - pulsationOffset, pt.y - pulsationOffset, cellBounds.width + 2 * pulsationOffset,
cellBounds.height + 2 * pulsationOffset)
val newPainter = LearningHighlightPainter(startDate, options, bounds)
Disposer.newDisposable("RepaintHighlightingDisposable").let {
disposable = it
findIdeGlassPane(original).addPainter(null, newPainter, it)
}
listLocationOnScreen = original.locationOnScreen
cellBoundsInList = cellBounds
highlightPainter = newPainter
}
}
internal class LearningHighlightPainter(
private val startDate: Date,
private val options: LearningUiHighlightingManager.HighlightingOptions,
val bounds: Rectangle
) : AbstractPainter() {
private val pulsationOffset = if (options.usePulsation) pulsationSize else 0
private var previous: Long = 0
override fun executePaint(component: Component?, g: Graphics2D?) {
val g2d = g as Graphics2D
val r: Rectangle = bounds
val oldColor = g2d.color
val time = Date().time
val delta = time - startDate.time
previous = time
val shift = if (pulsationOffset != 0 && (delta / 1000) % 4 == 2.toLong()) {
(((delta / 25 + 20) % 40 - 20).absoluteValue).toInt()
}
else 0
fun cyclicNumber(amplitude: Int, change: Long) = (change % (2 * amplitude) - amplitude).absoluteValue.toInt()
val alphaCycle = cyclicNumber(1000, delta).toDouble() / 1000
val magenta = ColorUtil.withAlpha(Color.magenta, 0.8)
val orange = ColorUtil.withAlpha(Color.orange, 0.8)
val background = ColorUtil.withAlpha(JBColor(Color(0, 0, shift * 10), Color(255 - shift * 10, 255 - shift * 10, 255)),
(0.3 + 0.7 * shift / 20.0) * alphaCycle)
val gradientShift = (delta / 20).toFloat()
val gp = GradientPaint(gradientShift + 0F, gradientShift + 0F, magenta,
gradientShift + r.height.toFloat(), gradientShift + r.height.toFloat(), orange, true)
val x = r.x + pulsationOffset - shift
val y = r.y + pulsationOffset - shift
val width = r.width - (pulsationOffset - shift) * 2
val height = r.height - (pulsationOffset - shift) * 2
RectanglePainter.paint(g2d, x, y, width, height, 2,
if (options.highlightInside) background else null,
if (options.highlightBorder) gp else null)
g2d.color = oldColor
}
override fun needsRepaint(): Boolean = true
}
private fun findIdeGlassPane(component: Component): IdeGlassPane {
val root = when (component) {
is JComponent -> component.rootPane
is RootPaneContainer -> component.rootPane
else -> null
} ?: throw IllegalArgumentException("Component must be visible in order to find glass pane for it")
val gp = root.glassPane
require(gp is IdeGlassPane) { "Glass pane should be " + IdeGlassPane::class.java.name }
return gp
}
| plugins/ide-features-trainer/src/training/ui/LearningUiHighlightingManager.kt | 2425301388 |
// 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.inspections
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInspection.*
import com.intellij.openapi.project.Project
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.intentions.branchedTransformations.isStableSimpleExpression
import org.jetbrains.kotlin.lexer.KtToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
class NullChecksToSafeCallInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession) =
binaryExpressionVisitor { expression ->
if (isNullChecksToSafeCallFixAvailable(expression)) {
holder.registerProblem(
expression,
KotlinBundle.message("null.checks.replaceable.with.safe.calls"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
NullChecksToSafeCallCheckFix()
)
}
}
private class NullChecksToSafeCallCheckFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("null.checks.to.safe.call.check.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
applyFix(descriptor.psiElement as? KtBinaryExpression ?: return)
}
private fun applyFix(expression: KtBinaryExpression) {
if (!FileModificationService.getInstance().preparePsiElementForWrite(expression)) return
val (lte, rte, isAnd) = collectNullCheckExpressions(expression) ?: return
val parent = expression.parent
expression.replaced(KtPsiFactory(lte.project).buildExpression {
appendExpression(lte)
appendFixedText("?.")
appendExpression(rte.selectorExpression)
appendFixedText(if (isAnd) "!= null" else "== null")
})
if (isNullChecksToSafeCallFixAvailable(parent as? KtBinaryExpression ?: return)) {
applyFix(parent)
}
}
}
companion object {
private fun isNullChecksToSafeCallFixAvailable(expression: KtBinaryExpression): Boolean {
fun String.afterIgnoreCalls() = replace("?.", ".")
val (lte, rte) = collectNullCheckExpressions(expression) ?: return false
val context = expression.analyze()
if (!lte.isChainStable(context)) return false
val resolvedCall = rte.getResolvedCall(context) ?: return false
val extensionReceiver = resolvedCall.extensionReceiver
if (extensionReceiver != null && TypeUtils.isNullableType(extensionReceiver.type)) return false
return rte.receiverExpression.text.afterIgnoreCalls() == lte.text.afterIgnoreCalls()
}
private fun collectNullCheckExpressions(expression: KtBinaryExpression): Triple<KtExpression, KtQualifiedExpression, Boolean>? {
val isAnd = when (expression.operationToken) {
KtTokens.ANDAND -> true
KtTokens.OROR -> false
else -> return null
}
val lhs = expression.left as? KtBinaryExpression ?: return null
val rhs = expression.right as? KtBinaryExpression ?: return null
val expectedOperation = if (isAnd) KtTokens.EXCLEQ else KtTokens.EQEQ
val lte = lhs.getNullTestableExpression(expectedOperation) ?: return null
val rte = rhs.getNullTestableExpression(expectedOperation) as? KtQualifiedExpression ?: return null
return Triple(lte, rte, isAnd)
}
private fun KtBinaryExpression.getNullTestableExpression(expectedOperation: KtToken): KtExpression? {
if (operationToken != expectedOperation) return null
val lhs = left ?: return null
val rhs = right ?: return null
if (KtPsiUtil.isNullConstant(lhs)) return rhs
if (KtPsiUtil.isNullConstant(rhs)) return lhs
return null
}
private fun KtExpression.isChainStable(context: BindingContext): Boolean = when (this) {
is KtReferenceExpression -> isStableSimpleExpression(context)
is KtQualifiedExpression -> selectorExpression?.isStableSimpleExpression(context) == true && receiverExpression.isChainStable(
context
)
else -> false
}
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/NullChecksToSafeCallInspection.kt | 624391849 |
package com.github.vhromada.catalog.utils
import com.github.vhromada.catalog.domain.io.MediaStatistics
import com.github.vhromada.catalog.entity.Medium
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.SoftAssertions.assertSoftly
import javax.persistence.EntityManager
/**
* A class represents utility class for media.
*
* @author Vladimir Hromada
*/
object MediumUtils {
/**
* Count of media
*/
const val MEDIA_COUNT = 4
/**
* Returns medium for index.
*
* @param index index
* @return medium for index
*/
fun getDomainMedium(index: Int): com.github.vhromada.catalog.domain.Medium {
val lengthMultiplier = 100
return com.github.vhromada.catalog.domain.Medium(
id = index,
number = if (index < 4) 1 else 2,
length = index * lengthMultiplier
).fillAudit(AuditUtils.getAudit())
}
/**
* Returns medium for index.
*
* @param index medium index
* @return medium for index
*/
fun getMedium(index: Int): Medium {
val lengthMultiplier = 100
return Medium(
number = if (index < 4) 1 else 2,
length = index * lengthMultiplier
)
}
/**
* Returns statistics for media.
*
* @return statistics for media
*/
fun getStatistics(): MediaStatistics {
return MediaStatistics(count = MEDIA_COUNT.toLong(), length = 1000L)
}
/**
* Returns count of media.
*
* @param entityManager entity manager
* @return count of media
*/
fun getMediaCount(entityManager: EntityManager): Int {
return entityManager.createQuery("SELECT COUNT(m.id) FROM Medium m", java.lang.Long::class.java).singleResult.toInt()
}
/**
* Returns medium.
*
* @param id ID
* @return medium
*/
fun newDomainMedium(id: Int?): com.github.vhromada.catalog.domain.Medium {
return com.github.vhromada.catalog.domain.Medium(
id = id,
number = 1,
length = 10
)
}
/**
* Returns medium.
*
* @return medium
*/
fun newMedium(): Medium {
return Medium(
number = 1,
length = 10
)
}
/**
* Asserts list of medium deep equals.
*
* @param expected expected list of medium
* @param actual actual list of medium
*/
fun assertDomainMediumDeepEquals(expected: List<com.github.vhromada.catalog.domain.Medium>, actual: List<com.github.vhromada.catalog.domain.Medium>) {
assertThat(expected.size).isEqualTo(actual.size)
if (expected.isNotEmpty()) {
for (i in expected.indices) {
assertMediumDeepEquals(expected = expected[i], actual = actual[i])
}
}
}
/**
* Asserts medium deep equals.
*
* @param expected expected medium
* @param actual actual medium
*/
private fun assertMediumDeepEquals(expected: com.github.vhromada.catalog.domain.Medium?, actual: com.github.vhromada.catalog.domain.Medium?) {
if (expected == null) {
assertThat(actual).isNull()
} else {
assertThat(actual).isNotNull
assertSoftly {
it.assertThat(actual!!.id).isEqualTo(expected.id)
it.assertThat(actual.number).isEqualTo(expected.number)
it.assertThat(actual.length).isEqualTo(expected.length)
}
AuditUtils.assertAuditDeepEquals(expected = expected, actual = actual!!)
}
}
/**
* Asserts list of medium deep equals.
*
* @param expected expected list of medium
* @param actual actual list of medium
*/
fun assertMediumDeepEquals(expected: List<com.github.vhromada.catalog.domain.Medium>, actual: List<Medium>) {
assertThat(expected.size).isEqualTo(actual.size)
if (expected.isNotEmpty()) {
for (i in expected.indices) {
assertMediumDeepEquals(expected = expected[i], actual = actual[i])
}
}
}
/**
* Asserts medium deep equals.
*
* @param expected expected medium
* @param actual actual medium
*/
private fun assertMediumDeepEquals(expected: com.github.vhromada.catalog.domain.Medium, actual: Medium) {
assertSoftly {
it.assertThat(actual.number).isEqualTo(expected.number)
it.assertThat(actual.length).isEqualTo(expected.length)
}
}
/**
* Asserts list of medium deep equals.
*
* @param expected expected list of medium
* @param actual actual list of medium
*/
fun assertMediumListDeepEquals(expected: List<Medium>, actual: List<Medium>) {
assertThat(expected.size).isEqualTo(actual.size)
if (expected.isNotEmpty()) {
for (i in expected.indices) {
assertMediumDeepEquals(expected = expected[i], actual = actual[i])
}
}
}
/**
* Asserts medium deep equals.
*
* @param expected expected medium
* @param actual actual medium
*/
private fun assertMediumDeepEquals(expected: Medium, actual: Medium) {
assertSoftly {
it.assertThat(actual.number).isEqualTo(expected.number)
it.assertThat(actual.length).isEqualTo(expected.length)
}
}
/**
* Asserts statistics for media deep equals.
*
* @param expected expected statistics for media
* @param actual actual statistics for media
*/
fun assertStatisticsDeepEquals(expected: MediaStatistics, actual: MediaStatistics) {
assertSoftly {
it.assertThat(actual.count).isEqualTo(expected.count)
it.assertThat(actual.length).isEqualTo(expected.length)
}
}
}
| core/src/test/kotlin/com/github/vhromada/catalog/utils/MediumUtils.kt | 653806343 |
package org.jetbrains.generator
/**
* Created by atsky on 11/7/14.
*/
class TextGenerator {
val data : StringBuilder = StringBuilder()
var indent : Int = 0
fun line() {
data.append("\n")
}
fun line(text : String) {
for (k in 1..indent) {
data.append(" ")
}
data.append(text).append("\n")
}
fun indent(body : TextGenerator.() -> Unit) {
indent++
this.body()
indent--
}
override fun toString() : String{
return data.toString()
}
} | generator/src/org/jetbrains/generator/TextGenerator.kt | 1134759227 |
package workshop.kotlin._01_convert_from_java
| src/main/kotlin/workshop/kotlin/_01_convert_from_java/ConverterProblem.kt | 2466456358 |
// 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.wm.impl.customFrameDecorations
import com.intellij.icons.AllIcons
import com.intellij.ide.ui.UISettings
import com.intellij.openapi.wm.impl.customFrameDecorations.style.ComponentStyle
import com.intellij.openapi.wm.impl.customFrameDecorations.style.ComponentStyleState
import com.intellij.openapi.wm.impl.customFrameDecorations.style.StyleManager
import com.intellij.ui.scale.ScaleType
import com.intellij.util.IconUtil
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.JBUI.Borders
import com.intellij.util.ui.JBUI.CurrentTheme
import net.miginfocom.swing.MigLayout
import java.awt.*
import javax.accessibility.AccessibleContext
import javax.swing.*
import javax.swing.border.Border
import javax.swing.plaf.ButtonUI
import javax.swing.plaf.basic.BasicButtonUI
internal open class CustomFrameTitleButtons constructor(myCloseAction: Action) {
companion object {
private val closeIcon = freezeIconUserSize(AllIcons.Windows.CloseActive)
private val closeHoverIcon = freezeIconUserSize(AllIcons.Windows.CloseHover)
private val closeInactive = freezeIconUserSize(AllIcons.Windows.CloseInactive)
fun create(myCloseAction: Action): CustomFrameTitleButtons {
val darculaTitleButtons = CustomFrameTitleButtons(myCloseAction)
darculaTitleButtons.createChildren()
return darculaTitleButtons
}
fun freezeIconUserSize(icon: Icon): Icon {
return IconUtil.overrideScale(IconUtil.deepCopy(icon, null), ScaleType.USR_SCALE.of(UISettings.defFontScale.toDouble()))
}
}
private val baseStyle = ComponentStyle.ComponentStyleBuilder<JComponent> {
isOpaque = false
border = Borders.empty()
}.apply {
fun paintHover(g: Graphics, width: Int, height: Int, color: Color) {
g.color = color
g.fillRect(0, 0, width, height)
}
class MyBorder(val color: ()-> Color) : Border {
override fun getBorderInsets(c: Component?): Insets = JBUI.emptyInsets()
override fun isBorderOpaque(): Boolean = false
override fun paintBorder(c: Component, g: Graphics, x: Int, y: Int, width: Int, height: Int) {
paintHover(g, width, height, color())
}
}
val hoverBorder = MyBorder {CurrentTheme.CustomFrameDecorations.titlePaneButtonHoverBackground()}
val pressBorder = MyBorder {CurrentTheme.CustomFrameDecorations.titlePaneButtonPressBackground()}
style(ComponentStyleState.HOVERED) {
this.border = hoverBorder
}
style(ComponentStyleState.PRESSED) {
this.border = pressBorder
}
}
val closeStyleBuilder = ComponentStyle.ComponentStyleBuilder<JButton> {
isOpaque = false
border = Borders.empty()
icon = closeIcon
}.apply {
style(ComponentStyleState.HOVERED) {
isOpaque = true
background = Color(0xe81123)
icon = closeHoverIcon
}
style(ComponentStyleState.PRESSED) {
isOpaque = true
background = Color(0xf1707a)
icon = closeHoverIcon
}
}
private val activeCloseStyle = closeStyleBuilder.build()
private val inactiveCloseStyle = closeStyleBuilder
.updateDefault() {
icon = closeInactive
}.build()
protected val panel = JPanel(MigLayout("top, ins 0 2 0 0, gap 0, hidemode 3, novisualpadding")).apply {
isOpaque = false
}
private val myCloseButton: JButton = createButton("Close", myCloseAction)
var isSelected = false
set(value) {
if(field != value) {
field = value
updateStyles()
}
}
protected open fun updateStyles() {
StyleManager.applyStyle(myCloseButton, if(isSelected) activeCloseStyle else inactiveCloseStyle)
}
protected fun createChildren() {
fillButtonPane()
addCloseButton()
updateVisibility()
updateStyles()
}
fun getView(): JComponent = panel
protected open fun fillButtonPane() {
}
open fun updateVisibility() {
}
private fun addCloseButton() {
addComponent(myCloseButton)
}
protected fun addComponent(component: JComponent) {
component.preferredSize = Dimension((47 * UISettings.defFontScale).toInt(), (28 * UISettings.defFontScale).toInt())
panel.add(component, "top")
}
protected fun getStyle(icon: Icon, hoverIcon : Icon): ComponentStyle<JComponent> {
val clone = baseStyle.clone()
clone.updateDefault {
this.icon = icon
}
clone.updateState(ComponentStyleState.HOVERED) {
this.icon = hoverIcon
}
clone.updateState(ComponentStyleState.PRESSED) {
this.icon = hoverIcon
}
return clone.build()
}
protected fun createButton(accessibleName: String, action: Action): JButton {
val button = object : JButton(){
init {
super.setUI(BasicButtonUI())
}
override fun setUI(ui: ButtonUI?) {
}
}
button.action = action
button.isFocusable = false
button.putClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY, accessibleName)
button.text = null
return button
}
} | platform/platform-impl/src/com/intellij/openapi/wm/impl/customFrameDecorations/CustomFrameTitleButtons.kt | 1755550984 |
package com.masahirosaito.spigot.homes.listeners
import com.masahirosaito.spigot.homes.Homes
import org.bukkit.event.Listener
interface HomesListener : Listener {
val plugin: Homes
fun register() {
plugin.server.pluginManager.registerEvents(this, plugin)
}
} | src/main/kotlin/com/masahirosaito/spigot/homes/listeners/HomesListener.kt | 3308019185 |
package br.com.thalesmachado.sample
import br.com.thalesmachado.kuestioner.Kuestioner
import br.com.thalesmachado.sample.models.Film
import br.com.thalesmachado.sample.service.StarWarsService
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
fun main(args: Array<String>) {
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
val client = OkHttpClient.Builder().addInterceptor(interceptor).build()
val retrofit = Retrofit.Builder().baseUrl("http://graphql-swapi.parseapp.com/")
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
val service = retrofit.create(StarWarsService::class.java)
service
.query(Kuestioner.queryOn(Film::class.java, mapOf("id" to "\"ZmlsbXM6MQ==\"")))
.subscribe(
{
println("SUCCESS")
},
{
println("ERROR + $it")
})
} | sample/src/main/java/br/com/thalesmachado/sample/KuestionerSample.kt | 2758481963 |
package net.serverpeon.discord.internal.adapters
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
import net.serverpeon.discord.model.DiscordId
object DiscordIdAdapter : TypeAdapter<DiscordId<*>>() {
override fun write(writer: JsonWriter, value: DiscordId<*>) {
writer.value(value.repr)
}
override fun read(reader: JsonReader): DiscordId<*> {
return DiscordId<Dummy>(reader.nextString())
}
private interface Dummy : DiscordId.Identifiable<Dummy>
} | implementation/src/main/kotlin/net/serverpeon/discord/internal/adapters/DiscordIdAdapter.kt | 2523906865 |
/*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.internal
import kotlin.coroutines.*
/**
* Tries to recover stacktrace for given [exception] and [continuation].
* Stacktrace recovery tries to restore [continuation] stack frames using its debug metadata with [CoroutineStackFrame] API
* and then reflectively instantiate exception of given type with original exception as a cause and
* sets new stacktrace for wrapping exception.
* Some frames may be missing due to tail-call elimination.
*
* Works only on JVM with enabled debug-mode.
*/
internal expect fun <E: Throwable> recoverStackTrace(exception: E, continuation: Continuation<*>): E
/**
* initCause on JVM, nop on other platforms
*/
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
internal expect fun Throwable.initCause(cause: Throwable)
/**
* Tries to recover stacktrace for given [exception]. Used in non-suspendable points of awaiting.
* Stacktrace recovery tries to instantiate exception of given type with original exception as a cause.
* Wrapping exception will have proper stacktrace as it's instantiated in the right context.
*
* Works only on JVM with enabled debug-mode.
*/
internal expect fun <E: Throwable> recoverStackTrace(exception: E): E
// Name conflict with recoverStackTrace
@Suppress("NOTHING_TO_INLINE")
internal expect suspend inline fun recoverAndThrow(exception: Throwable): Nothing
/**
* The opposite of [recoverStackTrace].
* It is guaranteed that `unwrap(recoverStackTrace(e)) === e`
*/
@PublishedApi // published for the multiplatform implementation of kotlinx-coroutines-test
internal expect fun <E: Throwable> unwrap(exception: E): E
internal expect class StackTraceElement
internal expect interface CoroutineStackFrame {
public val callerFrame: CoroutineStackFrame?
public fun getStackTraceElement(): StackTraceElement?
}
| kotlinx-coroutines-core/common/src/internal/StackTraceRecovery.common.kt | 4055409251 |
package com.ncorti.myonnaise
import android.app.Activity
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanFilter
import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.content.Context
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.FlowableEmitter
import io.reactivex.Single
import java.util.concurrent.TimeUnit
/**
* Entry point to the Myonnaise library.
* Use this class to do a Bluetooth scan and search for a new [Myo].
*
* Please note that in order to perform a Bluetooth Scan, the user needs to provide the
* [android.permission.ACCESS_COARSE_LOCATION] permission. You must request this permission to
* the user otherwise your scan will be empty.
*/
class Myonnaise(val context: Context) {
private val blManager = context.getSystemService(Activity.BLUETOOTH_SERVICE) as BluetoothManager
private val blAdapter = blManager.adapter
private val blLowEnergyScanner = blAdapter?.bluetoothLeScanner
private var scanCallback: MyonnaiseScanCallback? = null
/**
* Use this method to perform a scan. This method will return a [Flowable] that will publish
* all the found [BluetoothDevice].
* The scan will be stopped when you cancel the Flowable.
* To set a timeout use the overloaded method
*
* Usage:
* ```
* Myonnaise(context).startScan()
* .subscribeOn(Schedulers.io())
* .observeOn(AndroidSchedulers.mainThread())
* .subscribe({
* // Do something with the found device
* println(it.address)
* })
* ```
* @return A flowable that will publish the found [BluetoothDevice]
*/
fun startScan(): Flowable<BluetoothDevice> {
val scanFlowable: Flowable<BluetoothDevice> = Flowable.create(
{
scanCallback = MyonnaiseScanCallback(it)
blLowEnergyScanner?.startScan(scanCallback)
},
BackpressureStrategy.BUFFER
)
return scanFlowable.doOnCancel {
blLowEnergyScanner?.stopScan(scanCallback)
}
}
/**
* Use this method to perform a scan. This method will return a [Flowable] that will publish
* all the found [BluetoothDevice] and will stop after the timeout.
*
* Usage:
* ```
* Myonnaise(context).startScan(5, TimeUnit.MINUTES)
* .subscribeOn(Schedulers.io())
* .observeOn(AndroidSchedulers.mainThread())
* .subscribe({
* // Do something with the found device.
* println(it.address)
* })
* ```
* @param
* @param interval the timeout value.
* @param timeUnit time units to use for [interval].
*/
fun startScan(interval: Long, timeUnit: TimeUnit): Flowable<BluetoothDevice> =
startScan().takeUntil(Flowable.timer(interval, timeUnit))
/**
* Returns a [Myo] from a [BluetoothDevice]. Use this method after you discovered a device with
* the [startScan] method.
*/
fun getMyo(bluetoothDevice: BluetoothDevice): Myo {
return Myo(bluetoothDevice)
}
/**
* Returns a [Myo] from a Bluetooth address. Please note that this method will perform another
* scan to search for the desired device and return a [Single].
*/
fun getMyo(myoAddress: String): Single<Myo> {
return Single.create {
val filter =
ScanFilter.Builder()
.setDeviceAddress(myoAddress)
.build()
val settings =
ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)
.build()
blLowEnergyScanner?.startScan(
listOf(filter), settings,
object : ScanCallback() {
override fun onScanResult(callbackType: Int, result: ScanResult?) {
super.onScanResult(callbackType, result)
result?.device?.apply {
it.onSuccess(Myo(this))
}
}
override fun onScanFailed(errorCode: Int) {
super.onScanFailed(errorCode)
it.onError(RuntimeException())
}
}
)
}
}
inner class MyonnaiseScanCallback(private val emitter: FlowableEmitter<BluetoothDevice>) : ScanCallback() {
override fun onScanResult(callbackType: Int, result: ScanResult?) {
super.onScanResult(callbackType, result)
result?.device?.apply { emitter.onNext(this) }
}
override fun onScanFailed(errorCode: Int) {
super.onScanFailed(errorCode)
emitter.onError(RuntimeException())
}
}
}
| myonnaise/src/main/java/com/ncorti/myonnaise/Myonnaise.kt | 366515960 |
package slatekit.core.queues
import slatekit.common.EnumLike
import slatekit.common.EnumSupport
enum class QueueEntryStatus(override val value: Int) : EnumLike {
InActive(0),
Processing(1),
Completed(2),
Discarded(3);
companion object : EnumSupport() {
override fun all(): Array<EnumLike> {
return arrayOf(InActive, Processing, Completed)
}
}
}
| src/lib/kotlin/slatekit-core/src/main/kotlin/slatekit/core/queues/QueueEntryStatus.kt | 1396973977 |
/*
* Copyright (c) 2015-2022 Hallin Information Technology AB
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package io.codekvast.intake.bootstrap
import io.codekvast.common.logging.LoggerDelegate
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.context.properties.ConstructorBinding
import org.springframework.validation.annotation.Validated
import java.io.File
import javax.annotation.PostConstruct
/**
* Wrapper for environment properties codekvast.*
*
* @author [email protected]
*/
@ConfigurationProperties(prefix = "codekvast.intake")
@Validated
@ConstructorBinding
data class CodekvastIntakeSettings(
/** The path to the agent publication queue */
val fileImportQueuePath: File,
/** How often to scan fileImportQueuePath for new files. */
val fileImportIntervalSeconds: Int = 0,
/** Should imported files be deleted after successful import? */
val deleteImportedFiles: Boolean = true
) {
val logger by LoggerDelegate()
@PostConstruct
fun logStartup() {
System.out.printf("%n%s starts%n%n", this)
logger.info("{} starts", this)
}
} | product/server/intake/src/main/kotlin/io/codekvast/intake/bootstrap/CodekvastIntakeSettings.kt | 175532124 |
package slatekit.cache
import slatekit.common.DateTime
import slatekit.common.Identity
import slatekit.common.ext.toStringUtc
import slatekit.common.utils.Random
/**
* @param id : Id of this event
* @param origin : Name of the cache this event originated from.
* @param action : Cache action e.g. CRUD action
* @param key : Affected key in the cache. Empty if action = DeleteAll
* @param time : Time at which this event occurred
*/
data class CacheEvent(val uuid:String, val identity:Identity, val action: CacheAction, val key: String, val time: DateTime) {
val id:String = "$uuid.${identity.name}.${action.name}.$key"
val name:String = "${identity.name}.${action.name}.$key"
fun structured():List<Pair<String, Any>>{
return listOf(
CacheEvent::id.name to id,
CacheEvent::uuid.name to uuid,
CacheEvent::action.name to action.name,
CacheEvent::key.name to key,
CacheEvent::time.name to time.toStringUtc()
)
}
companion object {
fun of(id:Identity, action:CacheAction, key:String):CacheEvent {
val finalKey = if(key.trim().isNullOrEmpty()) "*" else key.trim()
return CacheEvent(Random.uuid(), id, action, finalKey, DateTime.now())
}
}
}
| src/lib/kotlin/slatekit-cache/src/main/kotlin/slatekit/cache/CacheEvent.kt | 1860823740 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.ui.branch.dashboard
import com.intellij.dvcs.branch.GroupingKey
import com.intellij.icons.AllIcons
import com.intellij.ide.CommonActionsManager
import com.intellij.ide.DataManager
import com.intellij.ide.DefaultTreeExpander
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.progress.util.ProgressWindow
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.changes.ui.ChangesBrowserBase
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.ui.IdeBorderFactory.createBorder
import com.intellij.ui.JBColor
import com.intellij.ui.OnePixelSplitter
import com.intellij.ui.ScrollPaneFactory
import com.intellij.ui.SideBorder
import com.intellij.ui.components.panels.NonOpaquePanel
import com.intellij.ui.speedSearch.SpeedSearch
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.JBUI.Panels.simplePanel
import com.intellij.util.ui.StatusText.getDefaultEmptyText
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.components.BorderLayoutPanel
import com.intellij.util.ui.table.ComponentsListFocusTraversalPolicy
import com.intellij.vcs.log.VcsLogBranchLikeFilter
import com.intellij.vcs.log.VcsLogFilterCollection
import com.intellij.vcs.log.data.VcsLogData
import com.intellij.vcs.log.impl.*
import com.intellij.vcs.log.impl.VcsLogManager.BaseVcsLogUiFactory
import com.intellij.vcs.log.impl.VcsLogProjectTabsProperties.MAIN_LOG_ID
import com.intellij.vcs.log.ui.VcsLogColorManager
import com.intellij.vcs.log.ui.VcsLogInternalDataKeys
import com.intellij.vcs.log.ui.VcsLogUiImpl
import com.intellij.vcs.log.ui.filter.VcsLogFilterUiEx
import com.intellij.vcs.log.ui.frame.*
import com.intellij.vcs.log.util.VcsLogUiUtil.isDiffPreviewInEditor
import com.intellij.vcs.log.util.VcsLogUtil
import com.intellij.vcs.log.visible.VisiblePackRefresher
import com.intellij.vcs.log.visible.VisiblePackRefresherImpl
import com.intellij.vcs.log.visible.filters.VcsLogFilterObject
import com.intellij.vcs.log.visible.filters.with
import com.intellij.vcs.log.visible.filters.without
import git4idea.i18n.GitBundle.message
import git4idea.i18n.GitBundleExtensions.messagePointer
import git4idea.repo.GitRepository
import git4idea.ui.branch.dashboard.BranchesDashboardActions.DeleteBranchAction
import git4idea.ui.branch.dashboard.BranchesDashboardActions.FetchAction
import git4idea.ui.branch.dashboard.BranchesDashboardActions.NewBranchAction
import git4idea.ui.branch.dashboard.BranchesDashboardActions.ShowBranchDiffAction
import git4idea.ui.branch.dashboard.BranchesDashboardActions.ShowMyBranchesAction
import git4idea.ui.branch.dashboard.BranchesDashboardActions.ToggleFavoriteAction
import git4idea.ui.branch.dashboard.BranchesDashboardActions.UpdateSelectedBranchAction
import java.awt.Component
import java.awt.datatransfer.DataFlavor
import java.awt.event.ActionEvent
import javax.swing.AbstractAction
import javax.swing.Action
import javax.swing.JComponent
import javax.swing.TransferHandler
import javax.swing.event.TreeSelectionListener
internal class BranchesDashboardUi(project: Project, private val logUi: BranchesVcsLogUi) : Disposable {
private val uiController = BranchesDashboardController(project, this)
private val tree = FilteringBranchesTree(project, BranchesTreeComponent(project), uiController)
private val branchViewSplitter = BranchViewSplitter()
private val branchesTreePanel = BranchesTreePanel().withBorder(createBorder(JBColor.border(), SideBorder.LEFT))
private val branchesScrollPane = ScrollPaneFactory.createScrollPane(tree.component, true)
private val branchesProgressStripe = ProgressStripe(branchesScrollPane, this, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS)
private val branchesTreeWithLogPanel = simplePanel()
private val mainPanel = simplePanel().apply { DataManager.registerDataProvider(this, uiController) }
private val branchesSearchFieldPanel = simplePanel()
private val branchesSearchField =
NonOpaquePanel(tree.installSearchField().apply { textEditor.border = JBUI.Borders.emptyLeft(5) }).apply(UIUtil::setNotOpaqueRecursively)
private lateinit var branchesPanelExpandableController: ExpandablePanelController
private val treeSelectionListener = TreeSelectionListener {
if (!branchesPanelExpandableController.isExpanded()) return@TreeSelectionListener
val ui = logUi
val properties = ui.properties
if (properties[CHANGE_LOG_FILTER_ON_BRANCH_SELECTION_PROPERTY]) {
updateLogBranchFilter()
}
else if (properties[NAVIGATE_LOG_TO_BRANCH_ON_BRANCH_SELECTION_PROPERTY]) {
navigateToSelectedBranch(false)
}
}
internal fun updateLogBranchFilter() {
val ui = logUi
val selectedFilters = tree.getSelectedBranchFilters()
val oldFilters = ui.filterUi.filters
val newFilters = if (selectedFilters.isNotEmpty()) {
oldFilters.without(VcsLogBranchLikeFilter::class.java).with(VcsLogFilterObject.fromBranches(selectedFilters))
} else {
oldFilters.without(VcsLogBranchLikeFilter::class.java)
}
ui.filterUi.filters = newFilters
}
internal fun navigateToSelectedBranch(focus: Boolean) {
val selectedReference = tree.getSelectedBranchFilters().singleOrNull() ?: return
logUi.vcsLog.jumpToReference(selectedReference, focus)
}
internal fun toggleGrouping(key: GroupingKey, state: Boolean) {
tree.toggleGrouping(key, state)
}
internal fun isGroupingEnabled(key: GroupingKey) = tree.isGroupingEnabled(key)
internal fun getSelectedRepositories(branchInfo: BranchInfo): List<GitRepository> {
return tree.getSelectedRepositories(branchInfo)
}
internal fun getSelectedRemotes(): Set<RemoteInfo> {
return tree.getSelectedRemotes()
}
internal fun getRootsToFilter(): Set<VirtualFile> {
val roots = logUi.logData.roots.toSet()
if (roots.size == 1) return roots
return VcsLogUtil.getAllVisibleRoots(roots, logUi.filterUi.filters)
}
private val BRANCHES_UI_FOCUS_TRAVERSAL_POLICY = object : ComponentsListFocusTraversalPolicy() {
override fun getOrderedComponents(): List<Component> = listOf(tree.component, logUi.table,
logUi.changesBrowser.preferredFocusedComponent,
logUi.filterUi.textFilterComponent.textEditor)
}
private val showBranches get() = logUi.properties.get(SHOW_GIT_BRANCHES_LOG_PROPERTY)
init {
initMainUi()
installLogUi()
toggleBranchesPanelVisibility()
}
@RequiresEdt
private fun installLogUi() {
uiController.registerDataPackListener(logUi.logData)
uiController.registerLogUiPropertiesListener(logUi.properties)
uiController.registerLogUiFilterListener(logUi.filterUi)
branchesSearchField.setVerticalSizeReferent(logUi.toolbar)
branchViewSplitter.secondComponent = logUi.mainLogComponent
val isDiffPreviewInEditor = isDiffPreviewInEditor()
val diffPreview = logUi.createDiffPreview(isDiffPreviewInEditor)
if (isDiffPreviewInEditor) {
mainPanel.add(branchesTreeWithLogPanel)
}
else {
mainPanel.add(DiffPreviewSplitter(diffPreview, logUi.properties, branchesTreeWithLogPanel).mainComponent)
}
tree.component.addTreeSelectionListener(treeSelectionListener)
}
@RequiresEdt
private fun disposeBranchesUi() {
branchViewSplitter.secondComponent.removeAll()
uiController.removeDataPackListener(logUi.logData)
uiController.removeLogUiPropertiesListener(logUi.properties)
tree.component.removeTreeSelectionListener(treeSelectionListener)
}
private fun initMainUi() {
val diffAction = ShowBranchDiffAction()
diffAction.registerCustomShortcutSet(KeymapUtil.getActiveKeymapShortcuts("Diff.ShowDiff"), branchesTreeWithLogPanel)
val deleteAction = DeleteBranchAction()
val shortcuts = KeymapUtil.getActiveKeymapShortcuts("SafeDelete").shortcuts + KeymapUtil.getActiveKeymapShortcuts(
"EditorDeleteToLineStart").shortcuts
deleteAction.registerCustomShortcutSet(CustomShortcutSet(*shortcuts), branchesTreeWithLogPanel)
createFocusFilterFieldAction(branchesSearchField)
installPasteAction(tree)
val toggleFavoriteAction = ToggleFavoriteAction()
val fetchAction = FetchAction(this)
val showMyBranchesAction = ShowMyBranchesAction(uiController)
val newBranchAction = NewBranchAction()
val updateSelectedAction = UpdateSelectedBranchAction()
val defaultTreeExpander = DefaultTreeExpander(tree.component)
val commonActionsManager = CommonActionsManager.getInstance()
val expandAllAction = commonActionsManager.createExpandAllHeaderAction(defaultTreeExpander, branchesTreePanel)
val collapseAllAction = commonActionsManager.createCollapseAllHeaderAction(defaultTreeExpander, branchesTreePanel)
val actionManager = ActionManager.getInstance()
val hideBranchesAction = actionManager.getAction("Git.Log.Hide.Branches")
val settings = actionManager.getAction("Git.Log.Branches.Settings")
val group = DefaultActionGroup()
group.add(hideBranchesAction)
group.add(Separator())
group.add(newBranchAction)
group.add(updateSelectedAction)
group.add(deleteAction)
group.add(diffAction)
group.add(showMyBranchesAction)
group.add(fetchAction)
group.add(toggleFavoriteAction)
group.add(actionManager.getAction("Git.Log.Branches.Navigate.Log.To.Selected.Branch"))
group.add(Separator())
group.add(settings)
group.add(actionManager.getAction("Git.Log.Branches.Grouping.Settings"))
group.add(expandAllAction)
group.add(collapseAllAction)
val toolbar = actionManager.createActionToolbar("Git.Log.Branches", group, false)
toolbar.setTargetComponent(branchesTreePanel)
val branchesButton = ExpandStripeButton(messagePointer("action.Git.Log.Show.Branches.text"), AllIcons.Actions.ArrowExpand)
.apply {
border = createBorder(JBColor.border(), SideBorder.RIGHT)
addActionListener {
if (logUi.properties.exists(SHOW_GIT_BRANCHES_LOG_PROPERTY)) {
logUi.properties.set(SHOW_GIT_BRANCHES_LOG_PROPERTY, true)
}
}
}
branchesSearchFieldPanel.withBackground(UIUtil.getListBackground()).withBorder(createBorder(JBColor.border(), SideBorder.BOTTOM))
branchesSearchFieldPanel.addToCenter(branchesSearchField)
branchesTreePanel.addToTop(branchesSearchFieldPanel).addToCenter(branchesProgressStripe)
branchesPanelExpandableController = ExpandablePanelController(toolbar.component, branchesButton, branchesTreePanel)
branchViewSplitter.firstComponent = branchesTreePanel
branchesTreeWithLogPanel.addToLeft(branchesPanelExpandableController.expandControlPanel).addToCenter(branchViewSplitter)
mainPanel.isFocusCycleRoot = true
mainPanel.focusTraversalPolicy = BRANCHES_UI_FOCUS_TRAVERSAL_POLICY
}
fun toggleBranchesPanelVisibility() {
branchesPanelExpandableController.toggleExpand(showBranches)
updateBranchesTree(true)
}
private fun createFocusFilterFieldAction(searchField: Component) {
DumbAwareAction.create { e ->
val project = e.getRequiredData(CommonDataKeys.PROJECT)
if (IdeFocusManager.getInstance(project).getFocusedDescendantFor(tree.component) != null) {
IdeFocusManager.getInstance(project).requestFocus(searchField, true)
}
else {
IdeFocusManager.getInstance(project).requestFocus(tree.component, true)
}
}.registerCustomShortcutSet(KeymapUtil.getActiveKeymapShortcuts("Find"), branchesTreePanel)
}
private fun installPasteAction(tree: FilteringBranchesTree) {
tree.component.actionMap.put(TransferHandler.getPasteAction().getValue(Action.NAME), object: AbstractAction () {
override fun actionPerformed(e: ActionEvent?) {
val speedSearch = tree.searchModel.speedSearch as? SpeedSearch ?: return
val pasteContent =
CopyPasteManager.getInstance().getContents<String>(DataFlavor.stringFlavor)
// the same filtering logic as in javax.swing.text.PlainDocument.insertString (e.g. DnD to search field)
?.let { StringUtil.convertLineSeparators(it, " ") }
speedSearch.type(pasteContent)
speedSearch.update()
}
})
}
inner class BranchesTreePanel : BorderLayoutPanel(), DataProvider {
override fun getData(dataId: String): Any? {
return when {
GIT_BRANCHES.`is`(dataId) -> tree.getSelectedBranches()
GIT_BRANCH_FILTERS.`is`(dataId) -> tree.getSelectedBranchFilters()
BRANCHES_UI_CONTROLLER.`is`(dataId) -> uiController
VcsLogInternalDataKeys.LOG_UI_PROPERTIES.`is`(dataId) -> logUi.properties
else -> null
}
}
}
fun getMainComponent(): JComponent {
return mainPanel
}
fun updateBranchesTree(initial: Boolean) {
if (showBranches) {
tree.update(initial)
}
}
fun refreshTree() {
tree.refreshTree()
}
fun refreshTreeModel() {
tree.refreshNodeDescriptorsModel()
}
fun startLoadingBranches() {
tree.component.emptyText.text = message("action.Git.Loading.Branches.progress")
branchesTreePanel.isEnabled = false
branchesProgressStripe.startLoading()
}
fun stopLoadingBranches() {
tree.component.emptyText.text = getDefaultEmptyText()
branchesTreePanel.isEnabled = true
branchesProgressStripe.stopLoading()
}
override fun dispose() {
disposeBranchesUi()
}
}
internal class BranchesVcsLogUiFactory(logManager: VcsLogManager, logId: String, filters: VcsLogFilterCollection? = null)
: BaseVcsLogUiFactory<BranchesVcsLogUi>(logId, filters, logManager.uiProperties, logManager.colorManager) {
override fun createVcsLogUiImpl(logId: String,
logData: VcsLogData,
properties: MainVcsLogUiProperties,
colorManager: VcsLogColorManager,
refresher: VisiblePackRefresherImpl,
filters: VcsLogFilterCollection?) =
BranchesVcsLogUi(logId, logData, colorManager, properties, refresher, filters)
}
internal class BranchesVcsLogUi(id: String, logData: VcsLogData, colorManager: VcsLogColorManager,
uiProperties: MainVcsLogUiProperties, refresher: VisiblePackRefresher,
initialFilters: VcsLogFilterCollection?) :
VcsLogUiImpl(id, logData, colorManager, uiProperties, refresher, initialFilters) {
private val branchesUi =
BranchesDashboardUi(logData.project, this)
.also { branchesUi -> Disposer.register(this, branchesUi) }
internal val mainLogComponent: JComponent
get() = mainFrame
internal val changesBrowser: ChangesBrowserBase
get() = mainFrame.changesBrowser
override fun createMainFrame(logData: VcsLogData, uiProperties: MainVcsLogUiProperties, filterUi: VcsLogFilterUiEx) =
MainFrame(logData, this, uiProperties, filterUi, false, this)
.apply {
isFocusCycleRoot = false
focusTraversalPolicy = null //new focus traversal policy will be configured include branches tree
if (isDiffPreviewInEditor()) {
VcsLogEditorDiffPreview(myProject, uiProperties, this)
}
}
override fun getMainComponent() = branchesUi.getMainComponent()
fun createDiffPreview(isInEditor: Boolean): VcsLogChangeProcessor {
return mainFrame.createDiffPreview(isInEditor, mainFrame.changesBrowser)
}
}
internal val SHOW_GIT_BRANCHES_LOG_PROPERTY =
object : VcsLogProjectTabsProperties.CustomBooleanTabProperty("Show.Git.Branches") {
override fun defaultValue(logId: String) = logId == MAIN_LOG_ID
}
internal val CHANGE_LOG_FILTER_ON_BRANCH_SELECTION_PROPERTY =
object : VcsLogApplicationSettings.CustomBooleanProperty("Change.Log.Filter.on.Branch.Selection") {
override fun defaultValue() = false
}
internal val NAVIGATE_LOG_TO_BRANCH_ON_BRANCH_SELECTION_PROPERTY =
object : VcsLogApplicationSettings.CustomBooleanProperty("Navigate.Log.To.Branch.on.Branch.Selection") {
override fun defaultValue() = false
}
private class BranchViewSplitter(first: JComponent? = null, second: JComponent? = null)
: OnePixelSplitter(false, "vcs.branch.view.splitter.proportion", 0.3f) {
init {
firstComponent = first
secondComponent = second
}
}
private class DiffPreviewSplitter(diffPreview: VcsLogChangeProcessor, uiProperties: VcsLogUiProperties, mainComponent: JComponent)
: FrameDiffPreview<VcsLogChangeProcessor>(diffPreview, uiProperties, mainComponent,
"vcs.branch.view.diff.splitter.proportion",
uiProperties[MainVcsLogUiProperties.DIFF_PREVIEW_VERTICAL_SPLIT], 0.3f) {
override fun updatePreview(state: Boolean) {
previewDiff.updatePreview(state)
}
}
| plugins/git4idea/src/git4idea/ui/branch/dashboard/BranchesDashboardUi.kt | 1455266691 |
// 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.vcs.log.history
import com.google.common.util.concurrent.SettableFuture
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.vcs.log.*
import com.intellij.vcs.log.data.VcsLogData
import com.intellij.vcs.log.data.VcsLogStorage
import com.intellij.vcs.log.impl.*
import com.intellij.vcs.log.statistics.VcsLogUsageTriggerCollector
import com.intellij.vcs.log.ui.MainVcsLogUi
import com.intellij.vcs.log.ui.VcsLogUiEx
import com.intellij.vcs.log.ui.table.GraphTableModel
import com.intellij.vcs.log.util.VcsLogUtil
import com.intellij.vcs.log.visible.filters.VcsLogFilterObject
import com.intellij.vcs.log.visible.filters.matches
import com.intellij.vcsUtil.VcsUtil
private const val TAB_NAME = "History"
class VcsLogFileHistoryProviderImpl : VcsLogFileHistoryProvider {
override fun canShowFileHistory(project: Project, paths: Collection<FilePath>, revisionNumber: String?): Boolean {
if (!Registry.`is`("vcs.new.history")) return false
val dataManager = VcsProjectLog.getInstance(project).dataManager ?: return false
if (paths.size == 1) {
return canShowSingleFileHistory(project, dataManager, paths.single(), revisionNumber != null)
}
return revisionNumber == null && createPathsFilter(project, dataManager, paths) != null
}
private fun canShowSingleFileHistory(project: Project, dataManager: VcsLogData, path: FilePath, isRevisionHistory: Boolean): Boolean {
val root = VcsLogUtil.getActualRoot(project, path) ?: return false
return dataManager.index.isIndexingEnabled(root) ||
canShowHistoryInLog(dataManager, getCorrectedPath(project, path, root, isRevisionHistory), root)
}
override fun showFileHistory(project: Project, paths: Collection<FilePath>, revisionNumber: String?) {
val hash = revisionNumber?.let { HashImpl.build(it) }
val root = VcsLogUtil.getActualRoot(project, paths.first())!!
triggerFileHistoryUsage(paths, hash)
val logManager = VcsProjectLog.getInstance(project).logManager!!
val historyUiConsumer = { ui: VcsLogUiEx, firstTime: Boolean ->
if (hash != null) {
ui.jumpToNearestCommit(logManager.dataManager.storage, hash, root, true)
}
else if (firstTime) {
ui.jumpToRow(0, true)
}
}
if (paths.size == 1) {
val correctedPath = getCorrectedPath(project, paths.single(), root, revisionNumber != null)
if (!canShowHistoryInLog(logManager.dataManager, correctedPath, root)) {
findOrOpenHistory(project, logManager, root, correctedPath, hash, historyUiConsumer)
return
}
}
findOrOpenFolderHistory(project, createHashFilter(hash, root), createPathsFilter(project, logManager.dataManager, paths)!!,
historyUiConsumer)
}
private fun canShowHistoryInLog(dataManager: VcsLogData,
correctedPath: FilePath,
root: VirtualFile): Boolean {
if (!correctedPath.isDirectory) {
return false
}
val logProvider = dataManager.logProviders[root] ?: return false
return VcsLogProperties.SUPPORTS_LOG_DIRECTORY_HISTORY.getOrDefault(logProvider)
}
private fun triggerFileHistoryUsage(paths: Collection<FilePath>, hash: Hash?) {
VcsLogUsageTriggerCollector.triggerUsage(VcsLogUsageTriggerCollector.VcsLogEvent.HISTORY_SHOWN) { data ->
val kind = if (paths.size > 1) "multiple" else if (paths.first().isDirectory) "folder" else "file"
data.addData("kind", kind).addData("has_revision", hash != null)
}
}
private fun findOrOpenHistory(project: Project, logManager: VcsLogManager,
root: VirtualFile, path: FilePath, hash: Hash?,
consumer: (VcsLogUiEx, Boolean) -> Unit) {
var fileHistoryUi = VcsLogContentUtil.findAndSelect(project, FileHistoryUi::class.java) { ui -> ui.matches(path, hash) }
val firstTime = fileHistoryUi == null
if (firstTime) {
val suffix = if (hash != null) " (" + hash.toShortString() + ")" else ""
fileHistoryUi = VcsLogContentUtil.openLogTab(project, logManager, TAB_NAME, path.name + suffix,
FileHistoryUiFactory(path, root, hash), true)
}
consumer(fileHistoryUi!!, firstTime)
}
private fun findOrOpenFolderHistory(project: Project, hashFilter: VcsLogFilter, pathsFilter: VcsLogFilter,
consumer: (VcsLogUiEx, Boolean) -> Unit) {
var ui = VcsLogContentUtil.findAndSelect(project, MainVcsLogUi::class.java) { logUi ->
matches(logUi.filterUi.filters, pathsFilter, hashFilter)
}
val firstTime = ui == null
if (firstTime) {
val filters = VcsLogFilterObject.collection(pathsFilter, hashFilter)
ui = VcsProjectLog.getInstance(project).openLogTab(filters) ?: return
ui.properties.set(MainVcsLogUiProperties.SHOW_ONLY_AFFECTED_CHANGES, true)
}
consumer(ui!!, firstTime)
}
private fun createPathsFilter(project: Project, dataManager: VcsLogData, paths: Collection<FilePath>): VcsLogFilter? {
val forRootFilter = mutableSetOf<VirtualFile>()
val forPathsFilter = mutableListOf<FilePath>()
for (path in paths) {
val root = VcsLogUtil.getActualRoot(project, path)
if (root == null) return null
if (!VcsLogProperties.SUPPORTS_LOG_DIRECTORY_HISTORY.getOrDefault(dataManager.getLogProvider(root))) return null
val correctedPath = getCorrectedPath(project, path, root, false)
if (!correctedPath.isDirectory) return null
if (path.virtualFile == root) {
forRootFilter.add(root)
}
else {
forPathsFilter.add(correctedPath)
}
if (forPathsFilter.isNotEmpty() && forRootFilter.isNotEmpty()) return null
}
if (forPathsFilter.isNotEmpty()) return VcsLogFilterObject.fromPaths(forPathsFilter)
return VcsLogFilterObject.fromRoots(forRootFilter)
}
private fun createHashFilter(hash: Hash?, root: VirtualFile): VcsLogFilter {
if (hash == null) {
return VcsLogFilterObject.fromBranch(VcsLogUtil.HEAD)
}
return VcsLogFilterObject.fromCommit(CommitId(hash, root))
}
private fun matches(filters: VcsLogFilterCollection, pathsFilter: VcsLogFilter, hashFilter: VcsLogFilter): Boolean {
if (!filters.matches(hashFilter.key, pathsFilter.key)) {
return false
}
return filters.get(pathsFilter.key) == pathsFilter && filters.get(hashFilter.key) == hashFilter
}
private fun getCorrectedPath(project: Project, path: FilePath, root: VirtualFile,
isRevisionHistory: Boolean): FilePath {
var correctedPath = path
if (root != VcsUtil.getVcsRootFor(project, correctedPath) && correctedPath.isDirectory) {
correctedPath = VcsUtil.getFilePath(correctedPath.path, false)
}
if (!isRevisionHistory) {
return VcsUtil.getLastCommitPath(project, correctedPath)
}
return correctedPath
}
}
private fun VcsLogUiEx.jumpToNearestCommit(storage: VcsLogStorage, hash: Hash, root: VirtualFile, silently: Boolean) {
jumpTo(hash, { model: GraphTableModel, h: Hash? ->
if (!storage.containsCommit(CommitId(h!!, root))) return@jumpTo GraphTableModel.COMMIT_NOT_FOUND
val commitIndex: Int = storage.getCommitIndex(h, root)
val visiblePack = model.visiblePack
var rowIndex = visiblePack.visibleGraph.getVisibleRowIndex(commitIndex)
if (rowIndex == null) {
rowIndex = findVisibleAncestorRow(commitIndex, visiblePack)
}
rowIndex ?: GraphTableModel.COMMIT_DOES_NOT_MATCH
}, SettableFuture.create<Boolean>(), silently)
}
| platform/vcs-log/impl/src/com/intellij/vcs/log/history/VcsLogFileHistoryProviderImpl.kt | 538102242 |
// TARGET_BACKEND: JVM
// FILE: A.java
// ANDROID_ANNOTATIONS
import kotlin.annotations.jvm.internal.*;
public class A {
public Integer a(@DefaultValue("42") Integer arg) {
return arg;
}
public Float b(@DefaultValue("42.5") Float arg) {
return arg;
}
public Boolean c(@DefaultValue("true") Boolean arg) {
return arg;
}
public Byte d(@DefaultValue("42") Byte arg) {
return arg;
}
public Character e(@DefaultValue("o") Character arg) {
return arg;
}
public Double f(@DefaultValue("1e12") Double arg) {
return arg;
}
public Long g(@DefaultValue("42424242424242") Long arg) {
return arg;
}
public Short h(@DefaultValue("123") Short arg) {
return arg;
}
}
// FILE: test.kt
fun box(): String {
val a = A()
if (a.a() != 42) {
return "FAIL Int: ${a.a()}"
}
if (a.b() != 42.5f) {
return "FAIL Float: ${a.b()}"
}
if (!a.c()) {
return "FAIL Boolean: ${a.c()}"
}
if (a.d() != 42.toByte()) {
return "FAIL Byte: ${a.d()}"
}
if (a.e() != 'o') {
return "FAIL Char: ${a.e()}"
}
if (a.f() != 1e12) {
return "FAIl Double: ${a.f()}"
}
if (a.g() != 42424242424242) {
return "FAIL Long: ${a.g()}"
}
if (a.h() != 123.toShort()) {
return "FAIL Short: ${a.h()}"
}
return "OK"
} | backend.native/tests/external/codegen/box/signatureAnnotations/defaultBoxTypes.kt | 807083825 |
operator fun Int.compareTo(c: Char) = 0
fun foo(x: Int, y: Char): String {
if (x < y) {
throw Error()
}
return "${y}K"
}
fun box(): String {
return foo(42, 'O')
} | backend.native/tests/external/codegen/box/binaryOp/kt11163.kt | 2125151928 |
package nl.mpcjanssen.simpletask
import android.app.Activity
import android.appwidget.AppWidgetManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import com.google.android.material.tabs.TabLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.viewpager.widget.ViewPager
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.Toolbar
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.EditText
import nl.mpcjanssen.simpletask.remote.FileDialog
import nl.mpcjanssen.simpletask.remote.FileStore
import nl.mpcjanssen.simpletask.task.Priority
import nl.mpcjanssen.simpletask.task.TodoList
import nl.mpcjanssen.simpletask.util.*
import java.io.File
import java.io.IOException
import java.util.*
class FilterActivity : ThemedNoActionBarActivity() {
internal var asWidgetConfigure = false
internal var asWidgetReConfigure = false
internal lateinit var mFilter: Query
internal lateinit var m_app: TodoApplication
val prefs = TodoApplication.config.prefs
private var pager: ViewPager? = null
private var m_menu: Menu? = null
private var pagerAdapter: ScreenSlidePagerAdapter? = null
private var scriptFragment: FilterScriptFragment? = null
private var m_page = 0
override fun onBackPressed() {
if (!asWidgetConfigure && !asWidgetReConfigure) {
applyFilter()
}
super.onBackPressed()
}
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.i(TAG, "Called with intent: " + intent.toString())
m_app = application as TodoApplication
setContentView(R.layout.filter)
val toolbar = findViewById<Toolbar>(R.id.toolbar_edit_filter)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_close_white_24dp)
val intent = intent
val environment: String = intent.action?.let {
asWidgetConfigure = it == AppWidgetManager.ACTION_APPWIDGET_CONFIGURE
val id = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, 0)
"widget" + id.toString()
} ?: "mainui"
val context = applicationContext
if (!asWidgetConfigure) {
mFilter = Query(intent, luaModule = environment)
} else if (intent.getBooleanExtra(Constants.EXTRA_WIDGET_RECONFIGURE, false)) {
asWidgetReConfigure = true
asWidgetConfigure = false
setTitle(R.string.config_widget)
val prefsName = intent.getIntExtra(Constants.EXTRA_WIDGET_ID, -1).toString()
val preferences = context.getSharedPreferences(prefsName , Context.MODE_PRIVATE)
mFilter = Query(preferences, luaModule = environment)
} else {
setTitle(R.string.create_widget)
mFilter = Query(prefs, luaModule = environment)
}
pagerAdapter = ScreenSlidePagerAdapter(supportFragmentManager)
val contextTab = FilterListFragment()
contextTab.arguments = Bundle().apply {
val contexts = alfaSort(TodoApplication.todoList.contexts, TodoApplication.config.sortCaseSensitive, "-")
putStringArrayList(FILTER_ITEMS, contexts)
putStringArrayList(INITIAL_SELECTED_ITEMS, mFilter.contexts)
putBoolean(INITIAL_NOT, mFilter.contextsNot)
putString(TAB_TYPE, CONTEXT_TAB)
}
pagerAdapter!!.add(contextTab)
val projectTab = FilterListFragment()
projectTab.arguments = Bundle().apply {
val projects = alfaSort(TodoApplication.todoList.projects, TodoApplication.config.sortCaseSensitive, "-")
putStringArrayList(FILTER_ITEMS, projects)
putStringArrayList(INITIAL_SELECTED_ITEMS, mFilter.projects)
putBoolean(INITIAL_NOT, mFilter.projectsNot)
putString(TAB_TYPE, PROJECT_TAB)
}
pagerAdapter!!.add(projectTab)
val prioTab = FilterListFragment()
prioTab.arguments = Bundle().apply {
putStringArrayList(FILTER_ITEMS, Priority.inCode(TodoApplication.todoList.priorities))
putStringArrayList(INITIAL_SELECTED_ITEMS, Priority.inCode(mFilter.priorities))
putBoolean(INITIAL_NOT, mFilter.prioritiesNot)
putString(TAB_TYPE, PRIO_TAB)
}
pagerAdapter!!.add(prioTab)
val otherTab = FilterOtherFragment()
otherTab.arguments = Bundle().apply {
putBoolean(Query.INTENT_HIDE_COMPLETED_FILTER, mFilter.hideCompleted)
putBoolean(Query.INTENT_HIDE_FUTURE_FILTER, mFilter.hideFuture)
putBoolean(Query.INTENT_HIDE_LISTS_FILTER, mFilter.hideLists)
putBoolean(Query.INTENT_HIDE_TAGS_FILTER, mFilter.hideTags)
putBoolean(Query.INTENT_HIDE_CREATE_DATE_FILTER, mFilter.hideCreateDate)
putBoolean(Query.INTENT_HIDE_HIDDEN_FILTER, mFilter.hideHidden)
putBoolean(Query.INTENT_CREATE_AS_THRESHOLD, mFilter.createIsThreshold)
putString(TAB_TYPE, OTHER_TAB)
}
pagerAdapter!!.add(otherTab)
// Fill arguments for fragment
val sortTab = FilterSortFragment()
sortTab.arguments = Bundle().apply {
putStringArrayList(FILTER_ITEMS, mFilter.getSort(TodoApplication.config.defaultSorts))
putString(TAB_TYPE, SORT_TAB)
}
pagerAdapter!!.add(sortTab)
val scriptTab = FilterScriptFragment()
scriptFragment = scriptTab
scriptTab.arguments = Bundle().apply {
putString(Query.INTENT_LUA_MODULE, environment)
putBoolean(Query.INTENT_USE_SCRIPT_FILTER, mFilter.useScript)
putString(Query.INTENT_SCRIPT_FILTER, mFilter.script)
putString(Query.INTENT_SCRIPT_TEST_TASK_FILTER, mFilter.scriptTestTask)
putString(TAB_TYPE, SCRIPT_TAB)
}
pagerAdapter!!.add(scriptTab)
pager = findViewById<ViewPager>(R.id.pager)
pager!!.adapter = pagerAdapter
// Give the TabLayout the ViewPager
val tabLayout = findViewById<TabLayout>(R.id.sliding_tabs)
tabLayout.setupWithViewPager(pager as ViewPager)
tabLayout.tabMode = TabLayout.MODE_SCROLLABLE
pager?.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrollStateChanged(state: Int) {
return
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
return
}
override fun onPageSelected(position: Int) {
Log.i(TAG, "Page $position selected")
m_page = position
}
})
val activePage = prefs.getInt(getString(R.string.last_open_filter_tab), 0)
if (activePage < pagerAdapter?.count ?: 0) {
pager?.setCurrentItem(activePage, false)
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
val inflater = menuInflater
inflater.inflate(R.menu.filter, menu)
m_menu = menu
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
finish()
return true
}
R.id.menu_filter_action -> {
when {
asWidgetConfigure -> askWidgetName()
asWidgetReConfigure -> {
updateWidget()
finish()
}
else -> applyFilter()
}
}
R.id.menu_filter_load_script -> openScript { contents ->
runOnMainThread(
Runnable { setScript(contents) })
}
}
return true
}
private fun openScript(file_read: (String) -> Unit) {
val dialog = FileDialog()
dialog.addFileListener(object : FileDialog.FileSelectedListener {
override fun fileSelected(file: File) {
Thread(Runnable {
try {
FileStore.readFile(file, file_read)
} catch (e: IOException) {
showToastShort(this@FilterActivity, "Failed to load script.")
e.printStackTrace()
}
}).start()
}
})
dialog.createFileDialog(this@FilterActivity, FileStore, TodoApplication.config.todoFile.parentFile, txtOnly = false)
}
private fun createFilterIntent(): Intent {
val target = Intent(this, Simpletask::class.java)
target.action = Constants.INTENT_START_FILTER
updateFilterFromFragments()
mFilter.saveInIntent(target)
target.putExtra("name", mFilter.proposedName)
return target
}
private fun updateFilterFromFragments() {
for (f in pagerAdapter!!.fragments) {
when (f.arguments?.getString(TAB_TYPE, "")?: "") {
"" -> {
}
OTHER_TAB -> {
val of = f as FilterOtherFragment
mFilter.hideCompleted = of.hideCompleted
mFilter.hideFuture = of.hideFuture
mFilter.hideLists = of.hideLists
mFilter.hideTags = of.hideTags
mFilter.hideCreateDate = of.hideCreateDate
mFilter.hideHidden = of.hideHidden
mFilter.createIsThreshold = of.createAsThreshold
}
CONTEXT_TAB -> {
val lf = f as FilterListFragment
mFilter.contexts = lf.getSelectedItems()
mFilter.contextsNot = lf.getNot()
}
PROJECT_TAB -> {
val pf = f as FilterListFragment
mFilter.projects = pf.getSelectedItems()
mFilter.projectsNot = pf.getNot()
}
PRIO_TAB -> {
val prf = f as FilterListFragment
mFilter.priorities = Priority.toPriority(prf.getSelectedItems())
mFilter.prioritiesNot = prf.getNot()
}
SORT_TAB -> {
val sf = f as FilterSortFragment
mFilter.setSort(sf.selectedItem)
}
SCRIPT_TAB -> {
val scrf = f as FilterScriptFragment
mFilter.useScript = scrf.useScript
mFilter.script = scrf.script
mFilter.scriptTestTask = scrf.testTask
}
}
}
}
private fun setScript(script: String?) {
if (scriptFragment == null) {
// fragment was never intialized
showToastShort(this, "Script tab not visible??")
} else {
script?.let { scriptFragment!!.script = script }
}
}
private fun updateWidget() {
updateFilterFromFragments()
val widgetId = intent.getIntExtra(Constants.EXTRA_WIDGET_ID, 0)
Log.i(TAG, "Saving settings for widget $widgetId")
val preferences = applicationContext.getSharedPreferences("" + widgetId, Context.MODE_PRIVATE)
mFilter.saveInPrefs(preferences)
broadcastRefreshWidgets(m_app.localBroadCastManager)
}
private fun createWidget(name: String) {
val mAppWidgetId: Int
val intent = intent
val extras = intent.extras
updateFilterFromFragments()
if (extras != null) {
mAppWidgetId = extras.getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID)
val context = applicationContext
// Store widget applyFilter
val preferences = context.getSharedPreferences("" + mAppWidgetId, Context.MODE_PRIVATE)
val namedFilter = NamedQuery(name, mFilter)
namedFilter.saveInPrefs(preferences)
val appWidgetManager = AppWidgetManager.getInstance(context)
MyAppWidgetProvider.updateAppWidget(context, appWidgetManager,
mAppWidgetId, name)
val resultValue = Intent(applicationContext, AppWidgetService::class.java)
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId)
setResult(Activity.RESULT_OK, resultValue)
finish()
}
}
private fun applyFilter() {
val data = createFilterIntent()
startActivity(data)
finish()
}
private fun askWidgetName() {
val name: String
val alert = AlertDialog.Builder(this)
alert.setTitle("Create widget")
alert.setMessage("Widget title")
updateFilterFromFragments()
name = mFilter.proposedName
// Set an EditText view to get user input
val input = EditText(this)
alert.setView(input)
input.setText(name)
alert.setPositiveButton("Ok") { _, _ ->
val value = input.text.toString()
if (value == "") {
showToastShort(applicationContext, R.string.widget_name_empty)
} else {
createWidget(value)
}
}
alert.setNegativeButton("Cancel") { _, _ -> }
alert.show()
}
override fun onDestroy() {
super.onDestroy()
prefs.edit().putInt(getString(R.string.last_open_filter_tab), m_page).apply()
pager?.clearOnPageChangeListeners()
}
/**
* A simple pager adapter that represents 5 ScreenSlidePageFragment objects, in
* sequence.
*/
private inner class ScreenSlidePagerAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm) {
val fragments: ArrayList<Fragment>
init {
fragments = ArrayList<Fragment>()
}
fun add(frag: Fragment) {
fragments.add(frag)
}
override fun getPageTitle(position: Int): CharSequence {
val f = fragments[position]
val type = f.arguments?.getString(TAB_TYPE, "unknown") ?:"unknown"
when (type) {
PROJECT_TAB -> return TodoApplication.config.tagTerm
CONTEXT_TAB -> return TodoApplication.config.listTerm
else -> return type
}
}
override fun getItem(position: Int): Fragment {
return fragments[position]
}
override fun getCount(): Int {
return fragments.size
}
}
companion object {
val TAG = "FilterActivity"
val TAB_TYPE = "type"
val CONTEXT_TAB = "context"
val PROJECT_TAB = "project"
val PRIO_TAB = getString(R.string.filter_tab_header_prio)
val OTHER_TAB = getString(R.string.filter_tab_header_other)
val SORT_TAB = getString(R.string.filter_tab_header_sort)
val SCRIPT_TAB = getString(R.string.filter_tab_header_script)
// Constants for saving state
val FILTER_ITEMS = "items"
val INITIAL_SELECTED_ITEMS = "initialSelectedItems"
val INITIAL_NOT = "initialNot"
}
}
| app/src/main/java/nl/mpcjanssen/simpletask/FilterActivity.kt | 1305431421 |
// WITH_RUNTIME
package test.regressions.kt1149
public interface SomeTrait {
fun foo()
}
fun box(): String {
val list = ArrayList<SomeTrait>()
var res = ArrayList<String>()
list.add(object : SomeTrait {
override fun foo() {
res.add("anonymous.foo()")
}
})
list.forEach{ it.foo() }
return if ("anonymous.foo()" == res[0]) "OK" else "fail"
}
| backend.native/tests/external/codegen/box/regressions/Kt1149.kt | 464063100 |
/*
* Copyright (C) 2016 Anthony C. Restaino
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.anthonycr.bonsai
/**
* The interface definition for the threading scheme used by Bonsai. Classes implementing this
* interface are expected to correctly execute a runnable on a thread of their choosing.
*/
interface Scheduler {
/**
* Run the runnable on the thread defined by the class implementing this class.
*
* @param runnable the task to execute.
*/
fun execute(runnable: () -> Unit)
}
| library/src/main/java/com/anthonycr/bonsai/Scheduler.kt | 3529692593 |
package com.aerodeko.pfm.extensions
import java.util.*
/**
* Created by rm on 28/12/2016.
*/
fun Calendar.setTimeToStartOfDate(date: Date) {
this.time = date
this.set(Calendar.HOUR_OF_DAY, 0)
this.set(Calendar.MINUTE, 0)
this.set(Calendar.SECOND, 0)
this.set(Calendar.MILLISECOND, 0)
}
| app/src/main/java/com/aerodeko/pfm/extensions/Calendar.kt | 3703350292 |
package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.vimeo.networking2.common.Connection
/**
* The default implementation of a connection that does not add any other properties.
*/
@JsonClass(generateAdapter = true)
data class DefaultConnection(
@Json(name = "options")
override val options: List<String>? = null,
@Json(name = "uri")
override val uri: String? = null
) : Connection
| models/src/main/java/com/vimeo/networking2/DefaultConnection.kt | 1743477902 |
package org.example.domain.finder
import io.ebean.Finder
import org.example.domain.Contact
open class ContactFinder : Finder<Long, Contact>(Contact::class.java)
| src/main/kotlin/org/example/domain/finder/ContactFinder.kt | 789830618 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic.collectors.fus
import com.intellij.internal.statistic.eventLog.validator.ValidationResultType
import com.intellij.internal.statistic.eventLog.validator.rules.EventContext
import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule
import com.intellij.internal.statistic.utils.PluginType
import com.intellij.internal.statistic.utils.getPluginInfo
internal class MethodNameRuleValidator : CustomValidationRule() {
override fun acceptRuleId(ruleId: String?): Boolean = "method_name" == ruleId
override fun doValidate(data: String, context: EventContext): ValidationResultType {
if (isThirdPartyValue(data)) {
return ValidationResultType.ACCEPTED
}
val lastDotIndex = data.lastIndexOf(".")
if (lastDotIndex == -1) {
return ValidationResultType.REJECTED
}
val className = data.substring(0, lastDotIndex)
val info = getPluginInfo(className)
if (info.type === PluginType.UNKNOWN) {
// if we can't detect a plugin then probably it's not a class name
return ValidationResultType.REJECTED
}
return if (info.isSafeToReport()) ValidationResultType.ACCEPTED else ValidationResultType.THIRD_PARTY
}
} | platform/statistics/src/com/intellij/internal/statistic/collectors/fus/MethodNameRuleValidator.kt | 1816053644 |
internal class Test | plugins/kotlin/j2k/old/tests/testData/fileOrElement/class/internalClass.kt | 8407166 |
// PROBLEM: none
open class Base {
open operator fun get(s: String) = ""
}
class C : Base() {
override fun get(s: String): String {
return super.<caret>get(s)
}
}
| plugins/kotlin/idea/tests/testData/inspectionsLocal/conventionNameCalls/replaceGetOrSet/super.kt | 1978593225 |
/*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package org.jetbrains.idea.devkit.actions
import com.intellij.icons.AllIcons
import com.intellij.navigation.ItemPresentation
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.impl.ModuleRenamingHistoryState
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Factory
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiPlainText
import com.intellij.psi.search.*
import com.intellij.usageView.UsageInfo
import com.intellij.usages.*
import com.intellij.util.Processor
import com.intellij.util.loadElement
import com.intellij.util.xmlb.XmlSerializationException
import com.intellij.util.xmlb.XmlSerializer
import org.jetbrains.idea.devkit.util.PsiUtil
import java.io.File
import kotlin.experimental.or
private val LOG = Logger.getInstance(MigrateModuleNamesInSourcesAction::class.java)
/**
* This is a temporary action to be used for migrating occurrences of module names in IntelliJ IDEA sources after massive module renaming.
*/
class MigrateModuleNamesInSourcesAction : AnAction("Find/Update Module Names in Sources...", "Find and migrate to the new scheme occurrences of module names in IntelliJ IDEA project sources", null) {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val viewPresentation = UsageViewPresentation().apply {
tabText = "Occurrences of Module Names"
toolwindowTitle = "Occurrences of Module Names"
usagesString = "occurrences of module names"
usagesWord = "occurrence"
codeUsagesString = "Found Occurrences"
isOpenInNewTab = true
isCodeUsages = false
isUsageTypeFilteringAvailable = true
}
val processPresentation = FindUsagesProcessPresentation(viewPresentation).apply {
isShowNotFoundMessage = true
isShowPanelIfOnlyOneUsage = true
}
val renamingScheme = try {
LocalFileSystem.getInstance().refreshAndFindFileByIoFile(
File(VfsUtil.virtualToIoFile(project.baseDir), "module-renaming-scheme.xml"))?.let {
XmlSerializer.deserialize(loadElement(it.inputStream), ModuleRenamingHistoryState::class.java).oldToNewName
}
}
catch (e: XmlSerializationException) {
LOG.error(e)
return
}
val moduleNames = renamingScheme?.keys?.toList() ?: ModuleManager.getInstance(project).modules.map { it.name }
val targets = moduleNames.map(::ModuleNameUsageTarget).toTypedArray()
val searcherFactory = Factory<UsageSearcher> {
val processed = HashSet<Pair<VirtualFile, Int>>()
UsageSearcher { consumer ->
val usageInfoConsumer = Processor<UsageInfo> {
if (processed.add(Pair(it.virtualFile!!, it.navigationRange!!.startOffset))) {
consumer.process(UsageInfo2UsageAdapter(it))
}
else true
}
processOccurrences(project, moduleNames, usageInfoConsumer)
}
}
val listener = object : UsageViewManager.UsageViewStateListener {
override fun usageViewCreated(usageView: UsageView) {
if (renamingScheme == null) return
val migrateOccurrences = Runnable {
@Suppress("UNCHECKED_CAST")
val usages = (usageView.usages - usageView.excludedUsages) as Set<UsageInfo2UsageAdapter>
val usagesByFile = usages.groupBy { it.file }
val progressIndicator = ProgressManager.getInstance().progressIndicator
var i = 0
usagesByFile.forEach { (file, usages) ->
progressIndicator?.fraction = (i++).toDouble() / usagesByFile.size
try {
usages.sortedByDescending { it.usageInfo.navigationRange!!.startOffset }.forEach {
var range = it.usageInfo.navigationRange!!
if (it.document.charsSequence[range.startOffset] in listOf('"', '\'')) range = TextRange(range.startOffset + 1, range.endOffset - 1)
val oldName = it.document.charsSequence.subSequence(range.startOffset, range.endOffset).toString()
if (oldName !in renamingScheme) throw RuntimeException("Unknown module $oldName")
val newName = renamingScheme[oldName]!!
runWriteAction {
it.document.replaceString(range.startOffset, range.endOffset, newName)
}
}
}
catch (e: Exception) {
throw RuntimeException("Cannot replace usage in ${file.presentableUrl}: ${e.message}", e)
}
}
}
usageView.addPerformOperationAction(migrateOccurrences, "Migrate Module Name Occurrences", "Cannot migrate occurrences", "Migrate Module Name Occurrences")
}
override fun findingUsagesFinished(usageView: UsageView?) {
}
}
UsageViewManager.getInstance(project).searchAndShowUsages(targets, searcherFactory, processPresentation, viewPresentation, listener)
}
private fun processOccurrences(project: Project,
moduleNames: List<String>,
consumer: Processor<UsageInfo>) {
val progress = ProgressManager.getInstance().progressIndicator ?: EmptyProgressIndicator()
progress.text = "Searching for module names..."
val scope = GlobalSearchScope.projectScope(project)
val searchHelper = PsiSearchHelper.SERVICE.getInstance(project)
fun Char.isModuleNamePart() = this.isJavaIdentifierPart() || this == '-'
fun GlobalSearchScope.filter(filter: (VirtualFile) -> Boolean) = object: DelegatingGlobalSearchScope(this) {
override fun contains(file: VirtualFile): Boolean {
return filter(file) && super.contains(file)
}
}
fun mayMentionModuleNames(text: String) = (text.contains("JpsProject") || text.contains("package com.intellij.testGuiFramework")
|| text.contains("getJarPathForClass")) && !text.contains("StandardLicenseUrls")
fun VirtualFile.isBuildScript() = when (extension) {
"gant" -> true
"groovy" -> VfsUtil.loadText(this).contains("package org.jetbrains.intellij.build")
"java" -> mayMentionModuleNames(VfsUtil.loadText(this))
"kt" -> mayMentionModuleNames(VfsUtil.loadText(this))
else -> false
}
fun processCodeUsages(moduleName: String, quotedString: String, groovyOnly: Boolean) {
val ignoredMethods = listOf("getPluginHomePath(", "getPluginHome(", "getPluginHomePathRelative(")
val quotedOccurrencesProcessor = TextOccurenceProcessor { element, offset ->
if (element.text != quotedString) return@TextOccurenceProcessor true
if (ignoredMethods.any {
element.textRange.startOffset > it.length && element.containingFile.text.startsWith(it, element.textRange.startOffset - it.length)
}) {
return@TextOccurenceProcessor true
}
consumer.process(UsageInfo(element, offset, offset + quotedString.length))
}
val literalsScope = if (moduleName in regularWordsUsedAsModuleNames + moduleNamesUsedAsIDs) scope.filter { it.isBuildScript() &&
!groovyOnly || it.extension in listOf("groovy", "gant") }
else scope
searchHelper.processElementsWithWord(quotedOccurrencesProcessor, literalsScope, quotedString,
UsageSearchContext.IN_CODE or UsageSearchContext.IN_STRINGS, true)
}
fun processUsagesInStrings(moduleName: String, substring: String) {
val quotedOccurrencesProcessor = TextOccurenceProcessor { element, offset ->
val text = element.text
if (text[0] == '"' && text.lastOrNull() == '"' || text[0] == '\'' && text.lastOrNull() == '\'') {
consumer.process(UsageInfo(element, offset + substring.indexOf(moduleName), offset + substring.length))
}
else {
true
}
}
searchHelper.processElementsWithWord(quotedOccurrencesProcessor, scope, substring, UsageSearchContext.IN_STRINGS, true)
}
for ((i, moduleName) in moduleNames.withIndex()) {
progress.fraction = i.toDouble() / moduleNames.size
progress.text2 = "Searching for \"$moduleName\""
processCodeUsages(moduleName, "\"$moduleName\"", groovyOnly = false)
processCodeUsages(moduleName, "'$moduleName'", groovyOnly = true)
processUsagesInStrings(moduleName, "production/$moduleName")
processUsagesInStrings(moduleName, "test/$moduleName")
val plainOccurrencesProcessor = TextOccurenceProcessor { element, offset ->
val endOffset = offset + moduleName.length
if ((offset == 0 || element.text[offset - 1].isWhitespace()) && (endOffset == element.textLength || element.text[endOffset].isWhitespace())
&& element is PsiPlainText) {
consumer.process(UsageInfo(element, offset, endOffset))
}
else true
}
val plainTextScope = if (moduleName in regularWordsUsedAsModuleNames + moduleNamesUsedAsIDs) scope.filter {it.name == "plugin-list.txt"} else scope
searchHelper.processElementsWithWord(plainOccurrencesProcessor, plainTextScope, moduleName, UsageSearchContext.IN_PLAIN_TEXT, true)
if (moduleName !in regularWordsUsedAsModuleNames) {
val commentsOccurrencesProcessor = TextOccurenceProcessor { element, offset ->
val endOffset = offset + moduleName.length
if ((offset == 0 || !element.text[offset - 1].isModuleNamePart() && element.text[offset-1] != '.')
&& (endOffset == element.textLength || !element.text[endOffset].isModuleNamePart() && element.text[endOffset] != '/'
&& !(endOffset < element.textLength - 2 && element.text[endOffset] == '.' && element.text[endOffset+1].isLetter()))
&& element is PsiComment) {
consumer.process(UsageInfo(element, offset, endOffset))
}
else true
}
searchHelper.processElementsWithWord(commentsOccurrencesProcessor, scope, moduleName, UsageSearchContext.IN_COMMENTS, true)
}
}
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = PsiUtil.isIdeaProject(e.project)
}
}
private class ModuleNameUsageTarget(val moduleName: String) : UsageTarget, ItemPresentation {
override fun getFiles() = null
override fun getPresentation() = this
override fun canNavigate() = false
override fun getName() = "\"$moduleName\""
override fun findUsages() {
throw UnsupportedOperationException()
}
override fun canNavigateToSource() = false
override fun isReadOnly() = true
override fun navigate(requestFocus: Boolean) {
throw UnsupportedOperationException()
}
override fun findUsagesInEditor(editor: FileEditor) {
}
override fun highlightUsages(file: PsiFile, editor: Editor, clearHighlights: Boolean) {
}
override fun isValid() = true
override fun update() {
}
override fun getPresentableText() = "Occurrences of \"$moduleName\""
override fun getLocationString() = null
override fun getIcon(unused: Boolean) = AllIcons.Nodes.Module!!
}
private val regularWordsUsedAsModuleNames = setOf(
"CloudBees", "AngularJS", "CloudFoundry", "CSS", "CFML", "Docker", "Dart", "EJS", "Guice", "Heroku", "Jade", "Kubernetes", "LiveEdit",
"OpenShift", "Meteor", "NodeJS", "Perforce", "TFS", "WSL", "analyzer", "android", "ant", "annotations", "appcode", "artwork", "asp", "aspectj", "behat", "boot", "bootstrap", "build", "blade",
"commandLineTool", "chronon", "codeception", "common", "commander", "copyright", "coverage", "dependencies", "designer", "ddmlib", "doxygen", "draw9patch", "drupal", "duplicates", "drools", "eclipse", "el", "emma", "editorconfig",
"extensions", "flex", "gherkin", "flags", "freemarker", "github", "gradle", "haml", "graph", "icons", "idea", "images", "ipnb", "jira", "joomla", "jbpm",
"json", "junit", "layoutlib", "less", "localization", "manifest", "main", "markdown", "maven", "ognl", "openapi", "ninepatch", "perflib", "observable", "phing", "php", "phpspec",
"pixelprobe", "play", "profilers", "properties", "puppet", "postcss", "python", "quirksmode", "repository", "resources", "rs", "relaxng", "restClient", "rest", "ruby", "sass", "sdklib", "seam", "ssh",
"spellchecker", "stylus", "swift", "terminal", "tomcat", "textmate", "testData", "testFramework", "testng", "testRunner", "twig", "util", "updater", "vaadin", "vagrant", "vuejs", "velocity", "weblogic",
"websocket", "wizard", "ws", "wordPress", "xml", "xpath", "yaml", "usageView", "error-prone", "spy-js", "WebStorm", "javac2", "dsm", "clion",
"phpstorm", "WebComponents"
)
private val moduleNamesUsedAsIDs = setOf("spring-integration", "spring-aop", "spring-mvc", "spring-security", "spring-webflow", "git4idea", "dvlib", "hg4idea",
"JsTestDriver", "ByteCodeViewer", "appcode-designer", "dsm", "flex",
"google-app-engine", "phpstorm-workshop", "ruby-core", "ruby-slim", "spring-ws", "svn4idea", "Yeoman",
"spring-batch", "spring-data", "sdk-common", "ui-designer") | plugins/devkit/src/actions/MigrateModuleNamesInSourcesAction.kt | 3605940149 |
// FLOW: OUT
fun test() {
val f = { <caret>1 }
val x = f()
} | plugins/kotlin/idea/tests/testData/slicer/outflow/lambdaResultWithDirectCallViaAssignment.kt | 1445673774 |
// IS_APPLICABLE: false
fun test(a: Int, b: Int, c: Int<caret>) {} | plugins/kotlin/idea/tests/testData/intentions/joinParameterList/noLineBreak.kt | 1444614505 |
// 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.vcs
import com.intellij.diff.util.Side
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileTypes.PlainTextFileType
import com.intellij.openapi.vcs.LineStatusTrackerTestUtil.parseInput
import com.intellij.openapi.vcs.ex.*
import com.intellij.openapi.vcs.ex.LocalLineStatusTracker.Mode
import com.intellij.testFramework.LightVirtualFile
import java.util.*
abstract class BaseLineStatusTrackerTestCase : BaseLineStatusTrackerManagerTest() {
protected fun test(text: String, task: SimpleTest.() -> Unit) {
test(text, text, false, task)
}
protected fun test(text: String, vcsText: String, smart: Boolean = false, task: SimpleTest.() -> Unit) {
resetTestState()
VcsApplicationSettings.getInstance().SHOW_WHITESPACES_IN_LST = smart
arePartialChangelistsSupported = false
doTest(text, vcsText, { tracker -> SimpleTest(tracker as SimpleLocalLineStatusTracker) }, task)
}
protected fun testPartial(text: String, task: PartialTest.() -> Unit) {
testPartial(text, text, task)
}
protected fun testPartial(text: String, vcsText: String, task: PartialTest.() -> Unit) {
resetTestState()
doTest(text, vcsText, { tracker -> PartialTest(tracker as ChangelistsLocalLineStatusTracker) }, task)
}
private fun <TestHelper : TrackerModificationsTest> doTest(text: String, vcsText: String,
createTestHelper: (LineStatusTracker<*>) -> TestHelper,
task: TestHelper.() -> Unit) {
val fileName = "file.txt"
val file = addLocalFile(fileName, parseInput(text))
setBaseVersion(fileName, parseInput(vcsText))
refreshCLM()
file.withOpenedEditor {
lstm.waitUntilBaseContentsLoaded()
val testHelper = createTestHelper(file.tracker!!)
testHelper.verify()
task(testHelper)
testHelper.verify()
}
}
protected fun lightTest(text: String, vcsText: String, smart: Boolean = false, task: SimpleTest.() -> Unit) {
val file = LightVirtualFile("LSTTestFile", PlainTextFileType.INSTANCE, parseInput(text))
val document = FileDocumentManager.getInstance().getDocument(file)!!
val tracker = runWriteAction {
val tracker = SimpleLocalLineStatusTracker.createTracker(getProject(), document, file)
tracker.mode = Mode(true, true, smart)
tracker.setBaseRevision(parseInput(vcsText))
tracker
}
try {
val testHelper = SimpleTest(tracker)
testHelper.verify()
task(testHelper)
testHelper.verify()
}
finally {
tracker.release()
}
}
protected inner class SimpleTest(val simpleTracker: SimpleLocalLineStatusTracker) : TrackerModificationsTest(simpleTracker)
protected inner class PartialTest(val partialTracker: ChangelistsLocalLineStatusTracker) : TrackerModificationsTest(partialTracker) {
fun assertAffectedChangeLists(vararg expected: String) {
partialTracker.assertAffectedChangeLists(*expected)
}
fun createChangeList_SetDefault(list: String) {
clm.addChangeList(list, null)
clm.setDefaultChangeList(list)
}
fun handlePartialCommit(side: Side, list: String, honorExcludedFromCommit: Boolean = true): PartialCommitHelper {
return partialTracker.handlePartialCommit(side, listOf(list.asListNameToId()), honorExcludedFromCommit)
}
fun Range.moveTo(list: String) {
val changeList = clm.addChangeList(list, null)
partialTracker.moveToChangelist(this, changeList)
}
fun moveChangesTo(lines: BitSet, list: String) {
val changeList = clm.addChangeList(list, null)
partialTracker.moveToChangelist(lines, changeList)
}
fun undo() {
undo(document)
}
fun redo() {
redo(document)
}
}
}
| platform/vcs-tests/testSrc/com/intellij/openapi/vcs/BaseLineStatusTrackerTestCase.kt | 2124701109 |
// 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.
@file:JvmMultifileClass
@file:JvmName("Promises")
package org.jetbrains.concurrency
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.ActionCallback
import com.intellij.util.Function
import com.intellij.util.ThreeState
import com.intellij.util.concurrency.AppExecutorUtil
import java.util.*
import java.util.concurrent.CancellationException
import java.util.concurrent.Future
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
import java.util.function.Consumer
private val obsoleteError: RuntimeException by lazy { MessageError("Obsolete", false) }
val Promise<*>.isRejected: Boolean
get() = state == Promise.State.REJECTED
val Promise<*>.isPending: Boolean
get() = state == Promise.State.PENDING
private val REJECTED: Promise<*> by lazy {
DonePromise<Any?>(PromiseValue.createRejected(createError("rejected")))
}
@Suppress("RemoveExplicitTypeArguments")
private val fulfilledPromise: CancellablePromise<Any?> by lazy {
DonePromise<Any?>(PromiseValue.createFulfilled(null))
}
@Suppress("UNCHECKED_CAST")
fun <T> resolvedPromise(): Promise<T> = fulfilledPromise as Promise<T>
fun nullPromise(): Promise<*> = fulfilledPromise
/**
* Creates a promise that is resolved with the given value.
*/
fun <T> resolvedPromise(result: T): Promise<T> = resolvedCancellablePromise(result)
/**
* Create a promise that is resolved with the given value.
*/
fun <T> resolvedCancellablePromise(result: T): CancellablePromise<T> {
@Suppress("UNCHECKED_CAST")
return when (result) {
null -> fulfilledPromise as CancellablePromise<T>
else -> DonePromise(PromiseValue.createFulfilled(result))
}
}
@Suppress("UNCHECKED_CAST")
/**
* Consider passing error.
*/
fun <T> rejectedPromise(): Promise<T> = REJECTED as Promise<T>
fun <T> rejectedPromise(error: String): Promise<T> = rejectedCancellablePromise(error)
fun <T> rejectedPromise(error: Throwable?): Promise<T> {
@Suppress("UNCHECKED_CAST")
return when (error) {
null -> REJECTED as Promise<T>
else -> DonePromise(PromiseValue.createRejected(error))
}
}
fun <T> rejectedCancellablePromise(error: String): CancellablePromise<T> =
DonePromise(PromiseValue.createRejected(createError(error, true)))
@Suppress("RemoveExplicitTypeArguments")
private val CANCELLED_PROMISE: Promise<Any?> by lazy {
DonePromise(PromiseValue.createRejected<Any?>(obsoleteError))
}
@Suppress("UNCHECKED_CAST")
fun <T> cancelledPromise(): Promise<T> = CANCELLED_PROMISE as Promise<T>
// only internal usage
interface ObsolescentFunction<Param, Result> : Function<Param, Result>, Obsolescent
abstract class ValueNodeAsyncFunction<PARAM, RESULT>(private val node: Obsolescent) : Function<PARAM, Promise<RESULT>>, Obsolescent {
override fun isObsolete(): Boolean = node.isObsolete
}
abstract class ObsolescentConsumer<T>(private val obsolescent: Obsolescent) : Obsolescent, Consumer<T> {
override fun isObsolete(): Boolean = obsolescent.isObsolete
}
inline fun <T, SUB_RESULT> Promise<T>.then(obsolescent: Obsolescent, crossinline handler: (T) -> SUB_RESULT): Promise<SUB_RESULT> = then(object : ObsolescentFunction<T, SUB_RESULT> {
override fun `fun`(param: T) = handler(param)
override fun isObsolete() = obsolescent.isObsolete
})
inline fun <T> Promise<T>.onSuccess(node: Obsolescent, crossinline handler: (T) -> Unit): Promise<T> = onSuccess(object : ObsolescentConsumer<T>(node) {
override fun accept(param: T) = handler(param)
})
inline fun Promise<*>.processed(node: Obsolescent, crossinline handler: () -> Unit): Promise<Any?>? {
@Suppress("UNCHECKED_CAST")
return (this as Promise<Any?>)
.onProcessed(object : ObsolescentConsumer<Any?>(node) {
override fun accept(param: Any?) = handler()
})
}
@Suppress("UNCHECKED_CAST")
inline fun <T> Promise<*>.thenRun(crossinline handler: () -> T): Promise<T> = (this as Promise<Any?>).then { handler() }
@Suppress("UNCHECKED_CAST")
inline fun Promise<*>.processedRun(crossinline handler: () -> Unit): Promise<*> {
return (this as Promise<Any?>).onProcessed { handler() }
}
inline fun <T, SUB_RESULT> Promise<T>.thenAsync(node: Obsolescent, crossinline handler: (T) -> Promise<SUB_RESULT>): Promise<SUB_RESULT> = thenAsync(object : ValueNodeAsyncFunction<T, SUB_RESULT>(node) {
override fun `fun`(param: T) = handler(param)
})
@Suppress("UNCHECKED_CAST")
inline fun <T> Promise<T>.thenAsyncAccept(node: Obsolescent, crossinline handler: (T) -> Promise<*>): Promise<Any?> {
return thenAsync(object : ValueNodeAsyncFunction<T, Any?>(node) {
override fun `fun`(param: T) = handler(param) as Promise<Any?>
})
}
inline fun <T> Promise<T>.thenAsyncAccept(crossinline handler: (T) -> Promise<*>): Promise<Any?> = thenAsync(Function { param ->
@Suppress("UNCHECKED_CAST")
(return@Function handler(param) as Promise<Any?>)
})
inline fun Promise<*>.onError(node: Obsolescent, crossinline handler: (Throwable) -> Unit): Promise<out Any> = onError(object : ObsolescentConsumer<Throwable>(node) {
override fun accept(param: Throwable) = handler(param)
})
/**
* Merge results into one list. Results are ordered as in the promises list.
*
* `T` here is a not nullable type, if you use this method from Java, take care that all promises are not resolved to `null`.
*
* If `ignoreErrors = false`, list of the same size is returned.
* If `ignoreErrors = true`, list of different size is returned if some promise failed with error.
*/
@JvmOverloads
fun <T : Any> Collection<Promise<T>>.collectResults(ignoreErrors: Boolean = false): Promise<List<T>> {
if (isEmpty()) {
return resolvedPromise(emptyList())
}
val result = AsyncPromise<List<T>>()
val latch = AtomicInteger(size)
val list = Collections.synchronizedList(Collections.nCopies<T?>(size, null).toMutableList())
fun arrive() {
if (latch.decrementAndGet() == 0) {
if (ignoreErrors) {
list.removeIf { it == null }
}
@Suppress("UNCHECKED_CAST")
result.setResult(list as List<T>)
}
}
for ((i, promise) in this.withIndex()) {
promise.onSuccess {
list.set(i, it)
arrive()
}
promise.onError {
if (ignoreErrors) {
arrive()
}
else {
result.setError(it)
}
}
}
return result
}
@JvmOverloads
fun createError(error: String, log: Boolean = false): RuntimeException = MessageError(error, log)
inline fun <T> AsyncPromise<T>.compute(runnable: () -> T) {
val result = try {
runnable()
}
catch (e: Throwable) {
setError(e)
return
}
setResult(result)
}
inline fun <T> runAsync(crossinline runnable: () -> T): Promise<T> {
val promise = AsyncPromise<T>()
AppExecutorUtil.getAppExecutorService().execute {
val result = try {
runnable()
}
catch (e: Throwable) {
promise.setError(e)
return@execute
}
promise.setResult(result)
}
return promise
}
/**
* Log error if not a message error
*/
fun Logger.errorIfNotMessage(e: Throwable): Boolean {
if (e is MessageError) {
val log = e.log
if (log == ThreeState.YES || (log == ThreeState.UNSURE && ApplicationManager.getApplication()?.isUnitTestMode == true)) {
error(e)
return true
}
}
else if (e !is ControlFlowException && e !is CancellationException) {
error(e)
return true
}
return false
}
fun ActionCallback.toPromise(): Promise<Any?> {
val promise = AsyncPromise<Any?>()
doWhenDone { promise.setResult(null) }
.doWhenRejected { error -> promise.setError(createError(error ?: "Internal error")) }
return promise
}
fun Promise<*>.toActionCallback(): ActionCallback {
val result = ActionCallback()
onSuccess { result.setDone() }
onError { result.setRejected() }
return result
}
fun Collection<Promise<*>>.all(): Promise<*> = if (size == 1) first() else all(null)
/**
* @see collectResults
*/
@JvmOverloads
fun <T: Any?> Collection<Promise<*>>.all(totalResult: T, ignoreErrors: Boolean = false): Promise<T> {
if (isEmpty()) {
return resolvedPromise()
}
val totalPromise = AsyncPromise<T>()
val done = CountDownConsumer(size, totalPromise, totalResult)
val rejected = if (ignoreErrors) {
Consumer { done.accept(null) }
}
else {
Consumer<Throwable> { totalPromise.setError(it) }
}
for (promise in this) {
promise.onSuccess(done)
promise.onError(rejected)
}
return totalPromise
}
private class CountDownConsumer<T : Any?>(countDown: Int, private val promise: AsyncPromise<T>, private val totalResult: T) : Consumer<Any?> {
private val countDown = AtomicInteger(countDown)
override fun accept(t: Any?) {
if (countDown.decrementAndGet() == 0) {
promise.setResult(totalResult)
}
}
}
fun <T> any(promises: Collection<Promise<T>>, totalError: String): Promise<T> {
if (promises.isEmpty()) {
return resolvedPromise()
}
else if (promises.size == 1) {
return promises.first()
}
val totalPromise = AsyncPromise<T>()
val done = Consumer<T> { result -> totalPromise.setResult(result) }
val rejected = object : Consumer<Throwable> {
private val toConsume = AtomicInteger(promises.size)
override fun accept(throwable: Throwable) {
if (toConsume.decrementAndGet() <= 0) {
totalPromise.setError(totalError)
}
}
}
for (promise in promises) {
promise.onSuccess(done)
promise.onError(rejected)
}
return totalPromise
}
private class DonePromise<T>(private val value: PromiseValue<T>) : Promise<T>, Future<T>, CancellablePromise<T> {
/**
* The same as @{link Future[Future.isDone]}.
* Completion may be due to normal termination, an exception, or cancellation -- in all of these cases, this method will return true.
*/
override fun isDone() = true
override fun getState() = value.state
override fun isCancelled() = this.value.isCancelled
override fun get() = blockingGet(-1)
override fun get(timeout: Long, unit: TimeUnit) = blockingGet(timeout.toInt(), unit)
override fun cancel(mayInterruptIfRunning: Boolean): Boolean {
if (state == Promise.State.PENDING) {
cancel()
return true
}
else {
return false
}
}
override fun onSuccess(handler: Consumer<in T?>): CancellablePromise<T> {
if (value.error != null) {
return this
}
if (!isHandlerObsolete(handler)) {
handler.accept(value.result)
}
return this
}
@Suppress("UNCHECKED_CAST")
override fun processed(child: Promise<in T?>): Promise<T> {
if (child is CompletablePromise<*>) {
(child as CompletablePromise<T>).setResult(value.result)
}
return this
}
override fun onProcessed(handler: Consumer<in T?>): CancellablePromise<T> {
if (value.error == null) {
onSuccess(handler)
}
else if (!isHandlerObsolete(handler)) {
handler.accept(null)
}
return this
}
override fun onError(handler: Consumer<in Throwable?>): CancellablePromise<T> {
if (value.error != null && !isHandlerObsolete(handler)) {
handler.accept(value.error)
}
return this
}
override fun <SUB_RESULT : Any?> then(done: Function<in T, out SUB_RESULT>): Promise<SUB_RESULT> {
@Suppress("UNCHECKED_CAST")
return when {
value.error != null -> this as Promise<SUB_RESULT>
isHandlerObsolete(done) -> cancelledPromise()
else -> DonePromise(PromiseValue.createFulfilled(done.`fun`(value.result)))
}
}
override fun <SUB_RESULT : Any?> thenAsync(done: Function<in T, out Promise<SUB_RESULT>>): Promise<SUB_RESULT> {
if (value.error == null) {
return done.`fun`(value.result)
}
else {
@Suppress("UNCHECKED_CAST")
return this as Promise<SUB_RESULT>
}
}
override fun blockingGet(timeout: Int, timeUnit: TimeUnit) = value.getResultOrThrowError()
override fun cancel() {}
} | platform/util/concurrency/org/jetbrains/concurrency/promise.kt | 3619839471 |
/*
The MIT License (MIT)
FTL-Lang Copyright (c) 2016 thoma
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.thomas.needham.ftl.frontend.symbols
import java.util.*
/**
* This class represents a defined interface within the compiler
* @author Thomas Needham
*/
class InterfaceSymbol<Type> : Symbol<Type> {
/**
* Unique identifier to represent this symbol
*/
override var id: UUID
/**
* The name of this symbol
*/
override val name: String
/**
* the value of this symbol
*/
override var value: Type?
/**
* The scope in which this symbol is defined
*/
override val scope: Scope
/**
* Whether this symbol is read only
*/
override val readOnly : Boolean
/**
* Whether this symbol is initialised
*/
override var initialised: Boolean
/**
* MutableList of functions defined within this interface
*/
val functions : MutableList<FunctionSymbol<*>>
/**
* Constructor for variable symbol
* @param id the unique identifier of the symbol
* @param name the name of this symbol
* @param value the value of this symbol
* @param readOnly whether this symbol is read only
* @param scope the scope tthat this symbol is defined in
* @param initialised whether this symbol has been initialised defaults to false
* @param functions MutableList of functions defined in this interface
*/
constructor(id: UUID, name: String, value: Type?, readOnly: Boolean, scope: Scope, initialised: Boolean = false,
functions: MutableList<FunctionSymbol<*>> = mutableListOf()){
this.id = id
this.name = name
this.value = value
this.readOnly = readOnly
this.scope = scope
this.initialised = initialised
this.functions = functions
}
/**
* Function to generate unique symbol id
* @param table the symbol table that this symbol is in
* @return A unique ID to represent a symbol
*/
override fun generateID(table: SymbolTable): UUID {
val symbols : MutableList<Symbol<*>> = table.symbols.filter { e -> e is InterfaceSymbol<*> }.toMutableList()
var found : Boolean = false
var id : UUID = UUID.fromString("0".repeat(128))
while (!found){
id = UUID.randomUUID()
for(sym: Symbol<*> in symbols){
if(sym.id == id)
found = true
}
}
return id
}
/**
* Function to compare if two symbols are equal
* @param other the symbol to compare this symbol with
* @return Whether both symbols are equal
*/
override fun equals(other: Any?): Boolean {
if(other !is InterfaceSymbol<*>?)
return false
if (other === null)
return true
return this.id == other.id && this.name == other.name &&
this.value == other.value && this.scope == other.scope &&
this.readOnly == other.readOnly && this.initialised == other.initialised &&
this.functions.containsAll(other.functions)
}
/**
* Generates a hashCode for this symbol
* @return the generated hash code
*/
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + id.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + (value?.hashCode() ?: 0)
result = 31 * result + scope.hashCode()
result = 31 * result + readOnly.hashCode()
result = 31 * result + initialised.hashCode()
result = 31 * result + functions.hashCode()
return result
}
} | src/main/kotlin/com/thomas/needham/ftl/frontend/symbols/InterfaceSymbol.kt | 1624190296 |
/*
* Copyright 1999-2017 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.p3c.idea.vcs
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.changes.CommitContext
import com.intellij.openapi.vcs.checkin.CheckinHandler
import com.intellij.openapi.vcs.checkin.CheckinHandlerFactory
/**
*
*
* @author caikang
* @date 2017/05/04
*/
class AliCodeAnalysisCheckinHandlerFactory : CheckinHandlerFactory() {
override fun createHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler {
return AliCodeAnalysisCheckinHandler(panel.project, panel)
}
} | idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/vcs/AliCodeAnalysisCheckinHandlerFactory.kt | 3609410146 |
package activitystarter.compiler
import activitystarter.compiler.generation.getPutArgumentToIntentMethodName
import activitystarter.compiler.model.param.ParamType
import org.junit.Assert
import org.junit.Assert.assertEquals
import org.junit.Test
class BindeingHelpersTest {
@Test
fun `For simple types Intent put is putExtra`() {
val exampleSimpleTypes = listOf(ParamType.Boolean, ParamType.BooleanArray, ParamType.Byte, ParamType.ByteArray, ParamType.Double, ParamType.Short)
for(simpleType in exampleSimpleTypes) {
assertEquals("putExtra", getPutArgumentToIntentMethodName(simpleType))
}
}
@Test
fun `For ArrayList type Intent put is specific`() {
val arrayTypeToPutFunctionMap = mapOf(
ParamType.IntegerArrayList to "putIntegerArrayListExtra",
ParamType.CharSequenceArrayList to "putCharSequenceArrayListExtra",
ParamType.ParcelableArrayListSubtype to "putParcelableArrayListExtra",
ParamType.StringArrayList to "putStringArrayListExtra"
)
for((type, functionName) in arrayTypeToPutFunctionMap) {
assertEquals(functionName, getPutArgumentToIntentMethodName(type))
}
}
} | activitystarter-compiler/src/test/java/activitystarter/compiler/BindeingHelpersTest.kt | 428639441 |
package uy.kohesive.iac.model.aws.cloudformation.resources.builders
import com.amazonaws.AmazonWebServiceRequest
import com.amazonaws.services.identitymanagement.model.*
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import uy.kohesive.iac.model.aws.cloudformation.ResourcePropertiesBuilder
import uy.kohesive.iac.model.aws.cloudformation.resources.IAM
import uy.kohesive.iac.model.aws.utils.CasePreservingJacksonNamingStrategy
class IAMManagedPolicyResourcePropertiesBuilder : ResourcePropertiesBuilder<CreatePolicyRequest> {
override val requestClazz = CreatePolicyRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreatePolicyRequest).let {
IAM.ManagedPolicy(
Description = it.description,
PolicyDocument = it.policyDocument.let { IAMGroupResourcePropertiesBuilder.JSON.readValue<Map<String, Any>>(it) },
Path = it.path
)
}
}
class IAMAccessKeyResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateAccessKeyRequest> {
override val requestClazz = CreateAccessKeyRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateAccessKeyRequest).let {
IAM.AccessKey(
UserName = request.userName,
Status = relatedObjects.filterIsInstance<UpdateAccessKeyRequest>().lastOrNull()?.status ?: "Active"
)
}
}
class IAMGroupResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateGroupRequest> {
companion object {
val JSON = jacksonObjectMapper()
.setPropertyNamingStrategy(CasePreservingJacksonNamingStrategy())
.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
}
override val requestClazz = CreateGroupRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateGroupRequest).let {
IAM.Group(
GroupName = request.groupName,
Path = request.path,
ManagedPolicyArns = relatedObjects.filterIsInstance<AttachGroupPolicyRequest>().map { it.policyArn },
Policies = relatedObjects.filterIsInstance<PutGroupPolicyRequest>().map {
IAM.Role.PolicyProperty(
PolicyName = it.policyName,
PolicyDocument = it.policyDocument.let { JSON.readValue<Map<String, Any>>(it) }
)
}
)
}
}
class IAMUserResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateUserRequest> {
override val requestClazz = CreateUserRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateUserRequest).let {
IAM.User(
Path = request.path,
UserName = request.userName,
Groups = relatedObjects.filterIsInstance<AddUserToGroupRequest>().map {
it.groupName
},
LoginProfile = relatedObjects.filterIsInstance<CreateLoginProfileRequest>().lastOrNull()?.let {
IAM.User.LoginProfileProperty(
Password = it.password,
PasswordResetRequired = it.passwordResetRequired?.toString()
)
},
ManagedPolicyArns = relatedObjects.filterIsInstance<AttachUserPolicyRequest>().map { it.policyArn },
Policies = relatedObjects.filterIsInstance<PutUserPolicyRequest>().map {
IAM.Role.PolicyProperty(
PolicyName = it.policyName,
PolicyDocument = it.policyDocument.let { IAMGroupResourcePropertiesBuilder.JSON.readValue<Map<String, Any>>(it) }
)
}
)
}
}
class IamInstanceProfilePropertiesBuilder : ResourcePropertiesBuilder<CreateInstanceProfileRequest> {
override val requestClazz = CreateInstanceProfileRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateInstanceProfileRequest).let {
IAM.InstanceProfile(
Path = request.path ?: "/",
Roles = relatedObjects.filterIsInstance(AddRoleToInstanceProfileRequest::class.java).map {
it.roleName
}
)
}
}
class IamPolicyResourcePropertiesBuilder : ResourcePropertiesBuilder<CreatePolicyRequest> {
override val requestClazz = CreatePolicyRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreatePolicyRequest).let {
IAM.Policy(
PolicyName = request.policyName,
PolicyDocument = jacksonObjectMapper().readTree(request.policyDocument),
Roles = relatedObjects.filterIsInstance(AttachRolePolicyRequest::class.java).map {
it.roleName
}
)
}
}
class IamRoleResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateRoleRequest> {
override val requestClazz = CreateRoleRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateRoleRequest).let {
IAM.Role(
AssumeRolePolicyDocument = jacksonObjectMapper().readTree(request.assumeRolePolicyDocument),
Path = request.path,
ManagedPolicyArns = relatedObjects.filterIsInstance<AttachRolePolicyRequest>().map { it.policyArn },
Policies = relatedObjects.filterIsInstance<PutRolePolicyRequest>().map {
IAM.Role.PolicyProperty(
PolicyName = it.policyName,
PolicyDocument = it.policyDocument.let { IAMGroupResourcePropertiesBuilder.JSON.readValue<Map<String, Any>>(it) }
)
},
RoleName = it.roleName
)
}
} | model-aws/src/main/kotlin/uy/kohesive/iac/model/aws/cloudformation/resources/builders/IAM.kt | 3549065991 |
/*
* Copyright 2016 Fabio Collini.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.cosenonjaviste.daggermock.realworldappkotlin.main
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.rule.ActivityTestRule
import it.cosenonjaviste.daggermock.realworldappkotlin.espressoDaggerMockRule
import it.cosenonjaviste.daggermock.realworldappkotlin.services.SnackBarManager
import it.cosenonjaviste.daggeroverride.R
import org.junit.Rule
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito.doAnswer
import org.mockito.Mockito.verify
class MainActivityMockPresenterTest {
@get:Rule val rule = espressoDaggerMockRule()
@get:Rule val activityRule = ActivityTestRule(MainActivity::class.java, false, false)
@Mock lateinit var presenter: MainPresenter
@Mock lateinit var snackBarManager: SnackBarManager
@Test
fun testOnCreate() {
val activity = activityRule.launchActivity(null)
doAnswer {
activity.showText("Hello world")
null
}.`when`<MainPresenter>(presenter).loadData()
onView(withId(R.id.reload)).perform(click())
onView(withId(R.id.text)).check(matches(withText("Hello world")))
}
@Test
fun testErrorOnCreate() {
doAnswer {
snackBarManager.showMessage("Error!")
null
}.`when`<MainPresenter>(presenter).loadData()
activityRule.launchActivity(null)
onView(withId(R.id.reload)).perform(click())
onView(withId(R.id.text)).check(matches(withText("")))
verify(snackBarManager).showMessage("Error!")
}
} | RealWorldAppKotlinAllOpen/src/androidTest/java/it/cosenonjaviste/daggermock/realworldappkotlin/main/MainActivityMockPresenterTest.kt | 2737518410 |
// 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.bridgeEntities.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.PersistentEntityId
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.SoftLinkable
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.containers.MutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.extractOneToOneChild
import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex
import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import java.io.Serializable
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class LibraryEntityImpl : LibraryEntity, WorkspaceEntityBase() {
companion object {
internal val SDK_CONNECTION_ID: ConnectionId = ConnectionId.create(LibraryEntity::class.java, SdkEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ONE, false)
internal val LIBRARYPROPERTIES_CONNECTION_ID: ConnectionId = ConnectionId.create(LibraryEntity::class.java,
LibraryPropertiesEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ONE, false)
internal val LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID: ConnectionId = ConnectionId.create(LibraryEntity::class.java,
LibraryFilesPackagingElementEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ONE,
false)
val connections = listOf<ConnectionId>(
SDK_CONNECTION_ID,
LIBRARYPROPERTIES_CONNECTION_ID,
LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID,
)
}
@JvmField
var _name: String? = null
override val name: String
get() = _name!!
@JvmField
var _tableId: LibraryTableId? = null
override val tableId: LibraryTableId
get() = _tableId!!
@JvmField
var _roots: List<LibraryRoot>? = null
override val roots: List<LibraryRoot>
get() = _roots!!
@JvmField
var _excludedRoots: List<VirtualFileUrl>? = null
override val excludedRoots: List<VirtualFileUrl>
get() = _excludedRoots!!
override val sdk: SdkEntity?
get() = snapshot.extractOneToOneChild(SDK_CONNECTION_ID, this)
override val libraryProperties: LibraryPropertiesEntity?
get() = snapshot.extractOneToOneChild(LIBRARYPROPERTIES_CONNECTION_ID, this)
override val libraryFilesPackagingElement: LibraryFilesPackagingElementEntity?
get() = snapshot.extractOneToOneChild(LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID, this)
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: LibraryEntityData?) : ModifiableWorkspaceEntityBase<LibraryEntity>(), LibraryEntity.Builder {
constructor() : this(LibraryEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity LibraryEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
index(this, "excludedRoots", this.excludedRoots.toHashSet())
indexLibraryRoots(roots)
// 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().isNameInitialized()) {
error("Field LibraryEntity#name should be initialized")
}
if (!getEntityData().isTableIdInitialized()) {
error("Field LibraryEntity#tableId should be initialized")
}
if (!getEntityData().isRootsInitialized()) {
error("Field LibraryEntity#roots should be initialized")
}
if (!getEntityData().isExcludedRootsInitialized()) {
error("Field LibraryEntity#excludedRoots 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 LibraryEntity
this.entitySource = dataSource.entitySource
this.name = dataSource.name
this.tableId = dataSource.tableId
this.roots = dataSource.roots.toMutableList()
this.excludedRoots = dataSource.excludedRoots.toMutableList()
if (parents != null) {
}
}
private fun indexLibraryRoots(libraryRoots: List<LibraryRoot>) {
val jarDirectories = mutableSetOf<VirtualFileUrl>()
val libraryRootList = libraryRoots.map {
if (it.inclusionOptions != LibraryRoot.InclusionOptions.ROOT_ITSELF) {
jarDirectories.add(it.url)
}
it.url
}.toHashSet()
index(this, "roots", libraryRootList)
indexJarDirectories(this, jarDirectories)
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var name: String
get() = getEntityData().name
set(value) {
checkModificationAllowed()
getEntityData().name = value
changedProperty.add("name")
}
override var tableId: LibraryTableId
get() = getEntityData().tableId
set(value) {
checkModificationAllowed()
getEntityData().tableId = value
changedProperty.add("tableId")
}
private val rootsUpdater: (value: List<LibraryRoot>) -> Unit = { value ->
val _diff = diff
if (_diff != null) {
indexLibraryRoots(value)
}
changedProperty.add("roots")
}
override var roots: MutableList<LibraryRoot>
get() {
val collection_roots = getEntityData().roots
if (collection_roots !is MutableWorkspaceList) return collection_roots
collection_roots.setModificationUpdateAction(rootsUpdater)
return collection_roots
}
set(value) {
checkModificationAllowed()
getEntityData().roots = value
rootsUpdater.invoke(value)
}
private val excludedRootsUpdater: (value: List<VirtualFileUrl>) -> Unit = { value ->
val _diff = diff
if (_diff != null) index(this, "excludedRoots", value.toHashSet())
changedProperty.add("excludedRoots")
}
override var excludedRoots: MutableList<VirtualFileUrl>
get() {
val collection_excludedRoots = getEntityData().excludedRoots
if (collection_excludedRoots !is MutableWorkspaceList) return collection_excludedRoots
collection_excludedRoots.setModificationUpdateAction(excludedRootsUpdater)
return collection_excludedRoots
}
set(value) {
checkModificationAllowed()
getEntityData().excludedRoots = value
excludedRootsUpdater.invoke(value)
}
override var sdk: SdkEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneChild(SDK_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, SDK_CONNECTION_ID)] as? SdkEntity
}
else {
this.entityLinks[EntityLink(true, SDK_CONNECTION_ID)] as? SdkEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, SDK_CONNECTION_ID)] = this
}
// 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.updateOneToOneChildOfParent(SDK_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, SDK_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, SDK_CONNECTION_ID)] = value
}
changedProperty.add("sdk")
}
override var libraryProperties: LibraryPropertiesEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneChild(LIBRARYPROPERTIES_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true,
LIBRARYPROPERTIES_CONNECTION_ID)] as? LibraryPropertiesEntity
}
else {
this.entityLinks[EntityLink(true, LIBRARYPROPERTIES_CONNECTION_ID)] as? LibraryPropertiesEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, LIBRARYPROPERTIES_CONNECTION_ID)] = this
}
// 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.updateOneToOneChildOfParent(LIBRARYPROPERTIES_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, LIBRARYPROPERTIES_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, LIBRARYPROPERTIES_CONNECTION_ID)] = value
}
changedProperty.add("libraryProperties")
}
override var libraryFilesPackagingElement: LibraryFilesPackagingElementEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneChild(LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true,
LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID)] as? LibraryFilesPackagingElementEntity
}
else {
this.entityLinks[EntityLink(true, LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID)] as? LibraryFilesPackagingElementEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID)] = this
}
// 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.updateOneToOneChildOfParent(LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID)] = value
}
changedProperty.add("libraryFilesPackagingElement")
}
override fun getEntityData(): LibraryEntityData = result ?: super.getEntityData() as LibraryEntityData
override fun getEntityClass(): Class<LibraryEntity> = LibraryEntity::class.java
}
}
class LibraryEntityData : WorkspaceEntityData.WithCalculablePersistentId<LibraryEntity>(), SoftLinkable {
lateinit var name: String
lateinit var tableId: LibraryTableId
lateinit var roots: MutableList<LibraryRoot>
lateinit var excludedRoots: MutableList<VirtualFileUrl>
fun isNameInitialized(): Boolean = ::name.isInitialized
fun isTableIdInitialized(): Boolean = ::tableId.isInitialized
fun isRootsInitialized(): Boolean = ::roots.isInitialized
fun isExcludedRootsInitialized(): Boolean = ::excludedRoots.isInitialized
override fun getLinks(): Set<PersistentEntityId<*>> {
val result = HashSet<PersistentEntityId<*>>()
val _tableId = tableId
when (_tableId) {
is LibraryTableId.GlobalLibraryTableId -> {
}
is LibraryTableId.ModuleLibraryTableId -> {
result.add(_tableId.moduleId)
}
is LibraryTableId.ProjectLibraryTableId -> {
}
}
for (item in roots) {
}
for (item in excludedRoots) {
}
return result
}
override fun index(index: WorkspaceMutableIndex<PersistentEntityId<*>>) {
val _tableId = tableId
when (_tableId) {
is LibraryTableId.GlobalLibraryTableId -> {
}
is LibraryTableId.ModuleLibraryTableId -> {
index.index(this, _tableId.moduleId)
}
is LibraryTableId.ProjectLibraryTableId -> {
}
}
for (item in roots) {
}
for (item in excludedRoots) {
}
}
override fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: WorkspaceMutableIndex<PersistentEntityId<*>>) {
// TODO verify logic
val mutablePreviousSet = HashSet(prev)
val _tableId = tableId
when (_tableId) {
is LibraryTableId.GlobalLibraryTableId -> {
}
is LibraryTableId.ModuleLibraryTableId -> {
val removedItem__tableId_moduleId = mutablePreviousSet.remove(_tableId.moduleId)
if (!removedItem__tableId_moduleId) {
index.index(this, _tableId.moduleId)
}
}
is LibraryTableId.ProjectLibraryTableId -> {
}
}
for (item in roots) {
}
for (item in excludedRoots) {
}
for (removed in mutablePreviousSet) {
index.remove(this, removed)
}
}
override fun updateLink(oldLink: PersistentEntityId<*>, newLink: PersistentEntityId<*>): Boolean {
var changed = false
val _tableId = tableId
val res_tableId = when (_tableId) {
is LibraryTableId.GlobalLibraryTableId -> {
_tableId
}
is LibraryTableId.ModuleLibraryTableId -> {
val _tableId_moduleId_data = if (_tableId.moduleId == oldLink) {
changed = true
newLink as ModuleId
}
else {
null
}
var _tableId_data = _tableId
if (_tableId_moduleId_data != null) {
_tableId_data = _tableId_data.copy(moduleId = _tableId_moduleId_data)
}
_tableId_data
}
is LibraryTableId.ProjectLibraryTableId -> {
_tableId
}
}
if (res_tableId != null) {
tableId = res_tableId
}
return changed
}
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<LibraryEntity> {
val modifiable = LibraryEntityImpl.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): LibraryEntity {
val entity = LibraryEntityImpl()
entity._name = name
entity._tableId = tableId
entity._roots = roots.toList()
entity._excludedRoots = excludedRoots.toList()
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun clone(): LibraryEntityData {
val clonedEntity = super.clone()
clonedEntity as LibraryEntityData
clonedEntity.roots = clonedEntity.roots.toMutableWorkspaceList()
clonedEntity.excludedRoots = clonedEntity.excludedRoots.toMutableWorkspaceList()
return clonedEntity
}
override fun persistentId(): PersistentEntityId<*> {
return LibraryId(name, tableId)
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return LibraryEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return LibraryEntity(name, tableId, roots, excludedRoots, entitySource) {
}
}
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 LibraryEntityData
if (this.entitySource != other.entitySource) return false
if (this.name != other.name) return false
if (this.tableId != other.tableId) return false
if (this.roots != other.roots) return false
if (this.excludedRoots != other.excludedRoots) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as LibraryEntityData
if (this.name != other.name) return false
if (this.tableId != other.tableId) return false
if (this.roots != other.roots) return false
if (this.excludedRoots != other.excludedRoots) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + tableId.hashCode()
result = 31 * result + roots.hashCode()
result = 31 * result + excludedRoots.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + tableId.hashCode()
result = 31 * result + roots.hashCode()
result = 31 * result + excludedRoots.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.add(LibraryRootTypeId::class.java)
collector.add(LibraryRoot.InclusionOptions::class.java)
collector.add(LibraryRoot::class.java)
collector.add(LibraryTableId::class.java)
collector.add(LibraryTableId.ModuleLibraryTableId::class.java)
collector.add(LibraryTableId.GlobalLibraryTableId::class.java)
collector.add(ModuleId::class.java)
collector.addObject(LibraryTableId.ProjectLibraryTableId::class.java)
this.roots?.let { collector.add(it::class.java) }
this.excludedRoots?.let { collector.add(it::class.java) }
collector.sameForAllEntities = false
}
}
| platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/LibraryEntityImpl.kt | 1416269793 |
package com.pluscubed.velociraptor.api.raptor
import android.content.Context
import android.location.Location
import androidx.annotation.WorkerThread
import com.android.billingclient.api.Purchase
import com.google.maps.android.PolyUtil
import com.pluscubed.velociraptor.BuildConfig
import com.pluscubed.velociraptor.api.*
import com.pluscubed.velociraptor.api.cache.CacheLimitProvider
import com.pluscubed.velociraptor.billing.BillingConstants
import com.pluscubed.velociraptor.utils.PrefUtils
import com.pluscubed.velociraptor.utils.Utils
import okhttp3.OkHttpClient
import java.util.*
class RaptorLimitProvider(
private val context: Context,
client: OkHttpClient,
private val cacheLimitProvider: CacheLimitProvider
) : LimitProvider {
private val SERVER_URL = "http://overpass.pluscubed.com:4000/"
private val raptorService: RaptorService
private var id: String
private var hereToken: String
private var tomtomToken: String
companion object {
const val USE_DEBUG_ID = BuildConfig.BUILD_TYPE == "debug"
}
init {
val interceptor = LimitInterceptor(LimitInterceptor.Callback())
val raptorClient = client.newBuilder()
.addInterceptor(interceptor)
.build()
val raptorRest = LimitFetcher.buildRetrofit(raptorClient, SERVER_URL)
raptorService = raptorRest.create(RaptorService::class.java)
id = UUID.randomUUID().toString()
if (USE_DEBUG_ID) {
val resId =
context.resources.getIdentifier("debug_id", "string", context.getPackageName())
if (resId != 0) {
id = context.getString(resId);
}
}
hereToken = ""
tomtomToken = ""
}
/**
* Returns whether updated token
*/
@WorkerThread
fun verify(purchase: Purchase): Boolean {
var updated = false
val verificationNetworkResponse = raptorService.verify(id, purchase.originalJson).execute()
val verificationResponse = Utils.getResponseBody(verificationNetworkResponse)
val token = verificationResponse.token
if (purchase.sku == BillingConstants.SKU_HERE || USE_DEBUG_ID) {
if (hereToken.isEmpty())
updated = true
hereToken = token
}
if (purchase.sku == BillingConstants.SKU_TOMTOM || USE_DEBUG_ID) {
if (tomtomToken.isEmpty())
updated = true
tomtomToken = token
}
return updated
}
override fun getSpeedLimit(
location: Location,
lastResponse: LimitResponse?,
origin: Int
): List<LimitResponse> {
val latitude = String.format(Locale.ROOT, "%.5f", location.latitude)
val longitude = String.format(Locale.ROOT, "%.5f", location.longitude)
when (origin) {
LimitResponse.ORIGIN_HERE ->
if (!hereToken.isEmpty()) {
val hereResponse = queryRaptorApi(true, latitude, longitude, location)
return listOf(hereResponse)
}
LimitResponse.ORIGIN_TOMTOM ->
if (!tomtomToken.isEmpty()) {
val tomtomResponse = queryRaptorApi(false, latitude, longitude, location)
return listOf(tomtomResponse)
}
}
return emptyList()
}
private fun queryRaptorApi(
isHere: Boolean,
latitude: String,
longitude: String,
location: Location
): LimitResponse {
val raptorQuery = if (isHere) {
raptorService.getHere(
"Bearer $hereToken",
id,
latitude,
longitude,
location.bearing.toInt(),
"Metric"
)
} else {
raptorService.getTomtom(
"Bearer $tomtomToken",
id,
latitude,
longitude,
location.bearing.toInt(),
"Metric"
)
}
val debuggingEnabled = PrefUtils.isDebuggingEnabled(context)
try {
val raptorNetworkResponse = raptorQuery.execute();
val raptorResponse = Utils.getResponseBody(raptorNetworkResponse)
val coords = PolyUtil.decode(raptorResponse.polyline).map { latLng ->
Coord(latLng.latitude, latLng.longitude)
}
val speedLimit = if (raptorResponse.generalSpeedLimit == 0) {
-1
} else {
raptorResponse.generalSpeedLimit!!
}
val response = LimitResponse(
roadName = if (raptorResponse.name.isEmpty()) "null" else raptorResponse.name,
speedLimit = speedLimit,
timestamp = System.currentTimeMillis(),
coords = coords,
origin = getOriginInt(isHere)
).initDebugInfo(debuggingEnabled)
cacheLimitProvider.put(response)
return response
} catch (e: Exception) {
return LimitResponse(
error = e,
timestamp = System.currentTimeMillis(),
origin = getOriginInt(isHere)
).initDebugInfo(debuggingEnabled)
}
}
private fun getOriginInt(here: Boolean) =
if (here) LimitResponse.ORIGIN_HERE else LimitResponse.ORIGIN_TOMTOM
}
| app/src/main/java/com/pluscubed/velociraptor/api/raptor/RaptorLimitProvider.kt | 3998255837 |
package com.dbflow5.processor.definition.column
import com.dbflow5.processor.SQLiteHelper
import com.dbflow5.quote
import com.squareup.javapoet.CodeBlock
import com.squareup.javapoet.TypeName
/**
* Description:
*/
object DefinitionUtils {
fun getCreationStatement(elementTypeName: TypeName?,
wrapperTypeName: TypeName?,
columnName: String): CodeBlock.Builder {
var statement: String? = null
if (SQLiteHelper.containsType(wrapperTypeName ?: elementTypeName)) {
statement = SQLiteHelper[wrapperTypeName ?: elementTypeName].toString()
}
return CodeBlock.builder().add("\$L \$L", columnName.quote(), statement)
}
fun getLoadFromCursorMethodString(elementTypeName: TypeName?,
wrapperTypeName: TypeName?): String {
var method = ""
if (SQLiteHelper.containsMethod(wrapperTypeName ?: elementTypeName)) {
method = SQLiteHelper.getMethod(elementTypeName)
}
return method
}
}
| processor/src/main/kotlin/com/dbflow5/processor/definition/column/DefinitionUtils.kt | 1805904486 |
@file:Suppress("unused")
package com.agoda.kakao.pager2
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.test.espresso.DataInteraction
import androidx.test.espresso.Root
import androidx.test.espresso.matcher.RootMatchers
import com.agoda.kakao.common.KakaoDslMarker
import com.agoda.kakao.common.actions.SwipeableActions
import com.agoda.kakao.common.assertions.BaseAssertions
import com.agoda.kakao.common.builders.ViewBuilder
import com.agoda.kakao.common.matchers.PositionMatcher
import com.agoda.kakao.delegate.ViewInteractionDelegate
import org.hamcrest.Matcher
import kotlin.reflect.KClass
/**
* View with SwipeableActions and ViewPager2Assertions
*
* @see SwipeableActions
*/
@KakaoDslMarker
class KViewPager2 : ViewPager2Actions, ViewPager2AdapterAssertions, SwipeableActions, BaseAssertions {
val matcher: Matcher<View>
val itemTypes: Map<KClass<out KViewPagerItem<*>>, KViewPagerItemType<KViewPagerItem<*>>>
override val view: ViewInteractionDelegate
override var root: Matcher<Root> = RootMatchers.DEFAULT
/**
* Constructs view class with view interaction from given ViewBuilder
*
* @param builder ViewBuilder which will result in view's interaction
* @param itemTypeBuilder Lambda with receiver where you pass your item providers
*
* @see ViewBuilder
*/
constructor(builder: ViewBuilder.() -> Unit, itemTypeBuilder: KViewPagerItemTypeBuilder.() -> Unit) {
val vb = ViewBuilder().apply(builder)
matcher = vb.getViewMatcher()
view = vb.getViewInteractionDelegate()
itemTypes = KViewPagerItemTypeBuilder().apply(itemTypeBuilder).itemTypes
}
/**
* Constructs view class with parent and view interaction from given ViewBuilder
*
* @param parent Matcher that will be used as parent in isDescendantOfA() matcher
* @param builder ViewBuilder which will result in view's interaction
* @param itemTypeBuilder Lambda with receiver where you pass your item providers
*
* @see ViewBuilder
*/
constructor(
parent: Matcher<View>, builder: ViewBuilder.() -> Unit,
itemTypeBuilder: KViewPagerItemTypeBuilder.() -> Unit
) : this({
isDescendantOfA { withMatcher(parent) }
builder(this)
}, itemTypeBuilder)
/**
* Constructs view class with parent and view interaction from given ViewBuilder
*
* @param parent DataInteraction that will be used as parent to ViewBuilder
* @param builder ViewBuilder which will result in view's interaction
* @param itemTypeBuilder Lambda with receiver where you pass your item providers
*
* @see ViewBuilder
*/
@Suppress("UNCHECKED_CAST")
constructor(
parent: DataInteraction, builder: ViewBuilder.() -> Unit,
itemTypeBuilder: KViewPagerItemTypeBuilder.() -> Unit
) {
val makeTargetMatcher = DataInteraction::class.java.getDeclaredMethod("makeTargetMatcher")
val parentMatcher = makeTargetMatcher.invoke(parent)
val vb = ViewBuilder().apply {
isDescendantOfA { withMatcher(parentMatcher as Matcher<View>) }
builder(this)
}
matcher = vb.getViewMatcher()
view = vb.getViewInteractionDelegate()
itemTypes = KViewPagerItemTypeBuilder().apply(itemTypeBuilder).itemTypes
}
/**
* Performs given actions/assertion on child at given position
*
* @param T Type of item at given position. Must be registered via constructor.
* @param position Position of item in adapter
* @param function Tail lambda which receiver will be matched item with given type T
*/
inline fun <reified T : KViewPagerItem<*>> childAt(position: Int, function: T.() -> Unit) {
val provideItem = itemTypes.getOrElse(T::class) {
throw IllegalStateException("${T::class.java.simpleName} did not register to KViewPager2")
}.provideItem
try {
scrollTo(position)
} catch (error: Throwable) {
}
val vb = ViewBuilder().apply {
isDescendantOfA { withMatcher([email protected]) }
isInstanceOf(RecyclerView::class.java)
}
function(provideItem(PositionMatcher(vb.getViewMatcher(), position)) as T)
.also { inRoot { withMatcher([email protected]) } }
}
/**
* Operator that allows usage of DSL style
*
* @param function Tail lambda with receiver which is your view
*/
operator fun invoke(function: KViewPager2.() -> Unit) {
function(this)
}
/**
* Infix function for invoking lambda on your view
*
* Sometimes instance of view is a result of a function or constructor.
* In this specific case you can't call invoke() since it will be considered as
* tail lambda of your fun/constructor. In such cases please use this function.
*
* @param function Tail lambda with receiver which is your view
* @return This object
*/
infix fun perform(function: KViewPager2.() -> Unit): KViewPager2 {
function(this)
return this
}
}
| kakao/src/main/kotlin/com/agoda/kakao/pager2/KViewPager2.kt | 4292568053 |
// 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.diff.editor
import com.intellij.diff.impl.DiffRequestProcessor
import com.intellij.openapi.actionSystem.CommonShortcuts
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.VirtualFile
class DefaultDiffFileEditorCustomizer : DiffRequestProcessorEditorCustomizer {
override fun customize(file: VirtualFile, editor: FileEditor, processor: DiffRequestProcessor) {
val escapeHandler = file.getUserData(DiffVirtualFile.ESCAPE_HANDLER)
?: DumbAwareAction.create { Disposer.dispose(editor) }
escapeHandler.registerCustomShortcutSet(CommonShortcuts.ESCAPE, editor.component, editor)
}
}
| platform/diff-impl/src/com/intellij/diff/editor/DefaultDiffFileEditorCustomizer.kt | 4026489786 |
// PROBLEM: none
// WITH_RUNTIME
fun foo() {
val xs = listOf(1, 2, 3).flatMap { x ->
listOf(3, 4, 5).map { y ->
object {
val <caret>value = x + y
}
}
}
xs.forEach {
println("value: " + it.value)
}
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/unusedSymbol/inAnonymousDeeply.kt | 1154159466 |
fun foo(b: Boolean) {
<caret>if (b) 1 // 1
else 2
} | plugins/kotlin/idea/tests/testData/intentions/branched/ifWhen/ifToWhen/comment.kt | 2115344339 |
package io.mironov.sento.compiler.reflect
import io.mironov.sento.compiler.common.Opener
import io.mironov.sento.compiler.common.Types
import org.objectweb.asm.AnnotationVisitor
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.FieldVisitor
import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes
import org.objectweb.asm.Type
internal class ClassSpecVisitor(
private val access: Int,
private val type: Type,
private val parent: Type,
private val interfaces: Collection<Type>,
private val opener: Opener,
private val action: (ClassSpec) -> Unit
) : ClassVisitor(Opcodes.ASM5) {
private val builder = ClassSpec.Builder(access, type, parent, opener).interfaces(interfaces)
override fun visitAnnotation(desc: String, visible: Boolean): AnnotationVisitor? {
return if (Types.isSystemClass(Type.getType(desc))) null else {
AnnotationSpecVisitor(Type.getType(desc)) {
builder.annotation(it)
}
}
}
override fun visitMethod(access: Int, name: String, desc: String, signature: String?, exceptions: Array<out String>?): MethodVisitor? {
return MethodSpecVisitor(access, name, Type.getType(desc), signature) {
builder.method(it)
}
}
override fun visitField(access: Int, name: String, desc: String, signature: String?, value: Any?): FieldVisitor? {
return FieldSpecVisitor(access, name, Type.getType(desc)) {
builder.field(it)
}
}
override fun visitEnd() {
action(builder.build())
}
}
| sento-compiler/src/main/kotlin/io/mironov/sento/compiler/reflect/ClassSpecVisitor.kt | 857205211 |
@file:Suppress("NOTHING_TO_INLINE")
package uy.kohesive.injekt.api
import java.lang.reflect.Type
import kotlin.reflect.KClass
public interface InjektFactory {
public fun <R: Any> getInstance(forType: Type): R
public fun <R: Any> getInstanceOrElse(forType: Type, default: R): R
public fun <R: Any> getInstanceOrElse(forType: Type, default: ()->R): R
public fun <R: Any, K: Any> getKeyedInstance(forType: Type, key: K): R
public fun <R: Any, K: Any> getKeyedInstanceOrElse(forType: Type, key: K, default: R): R
public fun <R: Any, K: Any> getKeyedInstanceOrElse(forType: Type, key: K, default: ()->R): R
public fun <R: Any> getLogger(expectedLoggerType: Type, byName: String): R
public fun <R: Any, T: Any> getLogger(expectedLoggerType: Type, forClass: Class<T>): R
}
public inline fun <R: Any> InjektFactory.get(forType: TypeReference<R>): R = getInstance(forType.type)
public inline fun <reified R: Any> InjektFactory.getOrElse(forType: TypeReference<R>, default: R): R = getInstanceOrElse(forType.type, default)
public inline fun <reified R: Any> InjektFactory.getOrElse(forType: TypeReference<R>, noinline default: ()->R): R = getInstanceOrElse(forType.type, default)
public inline fun <reified R: Any> InjektFactory.invoke(): R = getInstance(fullType<R>().type)
public inline fun <reified R: Any> InjektFactory.get(): R = getInstance(fullType<R>().type)
public inline fun <reified R: Any> InjektFactory.getOrElse(default: R): R = getInstanceOrElse(fullType<R>().type, default)
public inline fun <reified R: Any> InjektFactory.getOrElse(noinline default: ()->R): R = getInstanceOrElse(fullType<R>().type, default)
public inline fun <R: Any> InjektFactory.get(forType: TypeReference<R>, key: Any): R = getKeyedInstance(forType.type, key)
public inline fun <reified R: Any> InjektFactory.getOrElse(forType: TypeReference<R>, key: Any, default: R): R = getKeyedInstanceOrElse(forType.type, key, default)
public inline fun <reified R: Any> InjektFactory.getOrElse(forType: TypeReference<R>, key: Any, noinline default: ()->R): R = getKeyedInstanceOrElse(forType.type, key, default)
public inline fun <reified R: Any> InjektFactory.get(key: Any): R = getKeyedInstance(fullType<R>().type, key)
public inline fun <reified R: Any> InjektFactory.getOrElse(key: Any, default: R): R = getKeyedInstanceOrElse(fullType<R>().type, key, default)
public inline fun <reified R: Any> InjektFactory.getOrElse(key: Any, noinline default: ()->R): R = getKeyedInstanceOrElse(fullType<R>().type, key, default)
public inline fun <R: Any, T: Any> InjektFactory.logger(expectedLoggerType: TypeReference<R>, forClass: Class<T>): R = getLogger(expectedLoggerType.type, forClass)
public inline fun <reified R: Any, T: Any> InjektFactory.logger(forClass: Class<T>): R = getLogger(fullType<R>().type, forClass)
public inline fun <R: Any, T: Any> InjektFactory.logger(expectedLoggerType: TypeReference<R>, forClass: KClass<T>): R = getLogger(expectedLoggerType.type, forClass.java)
public inline fun <reified R: Any, T: Any> InjektFactory.logger(forClass: KClass<T>): R = getLogger(fullType<R>().type, forClass.java)
public inline fun <R: Any> InjektFactory.logger(expectedLoggerType: TypeReference<R>, byName: String): R = getLogger(expectedLoggerType.type, byName)
public inline fun <reified R: Any> InjektFactory.logger(byName: String): R = getLogger(fullType<R>().type, byName)
public inline fun <R: Any> InjektFactory.logger(expectedLoggerType: TypeReference<R>, byObject: Any): R = getLogger(expectedLoggerType.type, byObject.javaClass)
public inline fun <reified R: Any> InjektFactory.logger(byObject: Any): R = getLogger(fullType<R>().type, byObject.javaClass)
| api/src/main/kotlin/uy/kohesive/injekt/api/Factory.kt | 2151534993 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vfs
import com.intellij.openapi.vfs.newvfs.ArchiveFileSystem
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.testFramework.fixtures.BareTestFixtureTestCase
import org.junit.Before
import org.junit.Test
import kotlin.properties.Delegates
import kotlin.test.assertEquals
class ArchiveFileSystemPerformanceTest : BareTestFixtureTestCase() {
private var fs: ArchiveFileSystem by Delegates.notNull()
private var entry: VirtualFile by Delegates.notNull()
@Before fun setUp() {
fs = StandardFileSystems.jar() as ArchiveFileSystem
entry = fs.findFileByPath("${PlatformTestUtil.getRtJarPath()}!/java/lang/Object.class")!!
}
@Test fun getRootByEntry() {
val root = fs.getRootByEntry(entry)!!
PlatformTestUtil.startPerformanceTest("ArchiveFileSystem.getRootByEntry()", 50, {
for (i in 0..100000) {
assertEquals(root, fs.getRootByEntry(entry))
}
}).cpuBound().useLegacyScaling().assertTiming()
}
@Test fun getLocalByEntry() {
val local = fs.getLocalByEntry(entry)!!
PlatformTestUtil.startPerformanceTest("ArchiveFileSystem.getLocalByEntry()", 50, {
for (i in 0..100000) {
assertEquals(local, fs.getLocalByEntry(entry))
}
}).cpuBound().useLegacyScaling().assertTiming()
}
} | platform/platform-tests/testSrc/com/intellij/openapi/vfs/ArchiveFileSystemPerformanceTest.kt | 164094566 |
package info.touchimage.demo
import android.annotation.SuppressLint
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.ortiz.touchview.OnZoomFinishedListener
import info.touchimage.demo.databinding.ActivitySingleTouchimageviewBinding
class AnimateZoomActivity : AppCompatActivity(), OnZoomFinishedListener {
private lateinit var binding: ActivitySingleTouchimageviewBinding
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// https://developer.android.com/topic/libraries/view-binding
binding = ActivitySingleTouchimageviewBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
binding.currentZoom.setOnClickListener {
when {
binding.imageSingle.isZoomed -> binding.imageSingle.resetZoomAnimated()
binding.imageSingle.isZoomed.not() -> binding.imageSingle.setZoomAnimated(0.9f, 0.5f, 0f, this)
}
}
// It's not needed, but help to see if it proper centers on bigger screens (or smaller images)
binding.imageSingle.setZoom(1.1f, 0f, 0f)
}
@SuppressLint("SetTextI18n")
override fun onZoomFinished() {
binding.scrollPosition.text = "Zoom done"
}
}
| app/src/main/java/info/touchimage/demo/AnimateZoomActivity.kt | 4223276223 |
/**
* Copyright 2010 - 2022 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
*
* 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 jetbrains.exodus.crypto
import jetbrains.exodus.InvalidSettingException
import jetbrains.exodus.util.HexUtil
import java.io.InputStream
import java.io.OutputStream
fun newCipherProvider(cipherId: String) = StreamCipherProvider.getProvider(cipherId) ?:
throw ExodusCryptoException("Failed to load StreamCipherProvider with id = $cipherId")
fun newCipher(cipherId: String): StreamCipher = newCipherProvider(cipherId).newCipher()
fun StreamCipher.with(key: ByteArray, iv: Long) = this.apply { init(key, iv) }
fun toBinaryKey(cipherKey: String): ByteArray {
if (cipherKey.length and 1 == 1) {
throw InvalidSettingException("Odd length of hex representation of cipher key")
}
return HexUtil.stringToByteArray(cipherKey)
}
infix fun OutputStream.encryptBy(cipher: StreamCipher) = StreamCipherOutputStream(this, cipher)
infix fun InputStream.decryptBy(cipherGetter: () -> StreamCipher) = StreamCipherInputStream(this, cipherGetter)
internal fun StreamCipher.cryptAsInt(b: Byte) = this.crypt(b).toInt() and 0xff
| openAPI/src/main/kotlin/jetbrains/exodus/crypto/Krypt.kt | 2383450232 |
// 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.maven
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.idea.maven.plugins.api.MavenFixedValueReferenceProvider
import org.jetbrains.kotlin.cli.common.arguments.DefaultValues
import org.jetbrains.kotlin.config.JvmTarget
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.config.isStableOrReadyForPreview
class MavenLanguageVersionsCompletionProvider : MavenFixedValueReferenceProvider(
LanguageVersion.values().filter { it.isStableOrReadyForPreview() || ApplicationManager.getApplication().isInternal }.map { it.versionString }
.toTypedArray()
)
class MavenApiVersionsCompletionProvider : MavenFixedValueReferenceProvider(
LanguageVersion.values().filter { it.isStableOrReadyForPreview() || ApplicationManager.getApplication().isInternal }.map { it.versionString }
.toTypedArray()
)
class MavenJvmTargetsCompletionProvider : MavenFixedValueReferenceProvider(
JvmTarget.values().map(JvmTarget::description).toTypedArray()
)
class MavenJsModuleKindsCompletionProvider : MavenFixedValueReferenceProvider(
DefaultValues.JsModuleKinds.possibleValues!!.map(StringUtil::unquoteString).toTypedArray()
)
class MavenJsMainCallCompletionProvider : MavenFixedValueReferenceProvider(
DefaultValues.JsMain.possibleValues!!.map(StringUtil::unquoteString).toTypedArray()
) | plugins/kotlin/maven/src/org/jetbrains/kotlin/idea/maven/MavenCompletionProviders.kt | 4037569751 |
// 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.statistics
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
import com.intellij.internal.statistic.utils.getPluginInfoById
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinIdePlugin
class KotlinCreateFileFUSCollector : CounterUsagesCollector() {
override fun getGroup(): EventLogGroup = GROUP
companion object {
private val GROUP = EventLogGroup("kotlin.ide.new.file", 2)
private val pluginInfo = getPluginInfoById(KotlinIdePlugin.id)
private val allowedTemplates = listOf(
"Kotlin_Class",
"Kotlin_File",
"Kotlin_Interface",
"Kotlin_Data_Class",
"Kotlin_Enum",
"Kotlin_Sealed_Class",
"Kotlin_Annotation",
"Kotlin_Object",
"Kotlin_Scratch",
"Kotlin_Script",
"Kotlin_Worksheet"
)
private val newFileEvent = GROUP.registerEvent(
"Created",
EventFields.String("file_template", allowedTemplates),
EventFields.PluginInfo
)
fun logFileTemplate(template: String) = newFileEvent.log(template.replace(' ', '_'), pluginInfo)
}
}
| plugins/kotlin/core/src/org/jetbrains/kotlin/idea/statistics/KotlinCreateFileFUSCollector.kt | 94213712 |
/*
* Copyright 2010-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 kotlin.test.tests
import kotlin.test.*
import kotlin.native.internal.test.*
@Test
fun test() {
println("test")
}
fun main(args: Array<String>) {
println("Custom main")
testLauncherEntryPoint(args)
} | backend.native/tests/testing/custom_main.kt | 2371496726 |
package com.maubis.scarlet.base.support.utils
import android.app.Activity
import android.view.View
import androidx.annotation.IdRes
fun <T : View> Activity.bind(@IdRes idRes: Int): Lazy<T> {
@Suppress("UNCHECKED_CAST")
return unsafeLazy { findViewById(idRes) as T }
}
fun <T : View> View.bind(@IdRes idRes: Int): Lazy<T> {
@Suppress("UNCHECKED_CAST")
return unsafeLazy { findViewById(idRes) as T }
}
private fun <T> unsafeLazy(initializer: () -> T) = lazy(LazyThreadSafetyMode.NONE, initializer) | base/src/main/java/com/maubis/scarlet/base/support/utils/BindSupport.kt | 1041795719 |
// "Replace '@JvmField' with 'const'" "false"
// WITH_STDLIB
// ERROR: This annotation is not applicable to target 'top level property without backing field or delegate'
// ACTION: Do not show return expression hints
// ACTION: Make internal
// ACTION: Remove explicit type specification
<caret>@JvmField val number: Int
get() = 42 | plugins/kotlin/idea/tests/testData/quickfix/replaceJvmFieldWithConst/getter.kt | 3301096895 |
// "Create object 'A'" "false"
// ACTION: Convert to block body
// ACTION: Create annotation 'A'
// ACTION: Create class 'A'
// ACTION: Create enum 'A'
// ACTION: Create interface 'A'
// ACTION: Create type parameter 'A' in function 'foo'
// ACTION: Do not show return expression hints
// ACTION: Remove explicit type specification
// ERROR: Unresolved reference: A
package p
internal fun foo(): <caret>A = throw Throwable("") | plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createClass/typeReference/objectNotQualifierNoTypeArgs.kt | 2048242131 |
package wasing
import vgrechka.*
// TODO:vgrechka Kill
object WaXplatfConst {
object ElementDataSet {
val drawingNodeType by prefixed()
private fun prefixed() = named {"wasing${it.capitalize()}"}
}
object CSSClass {
val textContainer by prefixed()
val drawingContainer by prefixed()
val bodyContextMenu by prefixed()
private fun prefixed() = named {"wasing-$it"}
}
}
| alraune/alxplatf/src/wasing/wasing-xplatf.kt | 731079236 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.intellij.build.impl
import com.intellij.openapi.util.Pair
import com.intellij.util.containers.MultiMap
import org.jetbrains.intellij.build.BuildContext
import org.jetbrains.intellij.build.JvmArchitecture
import org.jetbrains.intellij.build.OsFamily
import org.jetbrains.intellij.build.PluginBundlingRestrictions
import java.nio.file.Files
import java.nio.file.Path
import java.util.function.*
/**
* Describes layout of a plugin in the product distribution
*/
class PluginLayout(val mainModule: String): BaseLayout() {
private var mainJarName = "${convertModuleNameToFileName(mainModule)}.jar"
lateinit var directoryName: String
var versionEvaluator: VersionEvaluator = object : VersionEvaluator {
override fun evaluate(pluginXml: Path, ideBuildVersion: String, context: BuildContext): String {
return ideBuildVersion
}
}
var pluginXmlPatcher: UnaryOperator<String> = UnaryOperator.identity()
var directoryNameSetExplicitly: Boolean = false
lateinit var bundlingRestrictions: PluginBundlingRestrictions
val pathsToScramble: MutableList<String> = mutableListOf()
val scrambleClasspathPlugins: MutableList<Pair<String /*plugin name*/, String /*relative path*/>> = mutableListOf()
var scrambleClasspathFilter: BiPredicate<BuildContext, Path> = BiPredicate { _, _ -> true }
/**
* See {@link org.jetbrains.intellij.build.impl.PluginLayout.PluginLayoutSpec#zkmScriptStub}
*/
var zkmScriptStub: String? = null
var pluginCompatibilityExactVersion = false
var retainProductDescriptorForBundledPlugin = false
val resourceGenerators: MutableList<Pair<BiFunction<Path, BuildContext, Path>, String>> = mutableListOf()
val patchers: MutableList<BiConsumer<ModuleOutputPatcher, BuildContext>> = mutableListOf()
fun getMainJarName() = mainJarName
companion object {
/**
* Creates the plugin layout description. The default plugin layout is composed of a jar with name {@code mainModuleName}.jar containing
* production output of {@code mainModuleName} module, and the module libraries of {@code mainModuleName} with scopes 'Compile' and 'Runtime'
* placed under 'lib' directory in a directory with name {@code mainModuleName}.
* If you need to include additional resources or modules into the plugin layout specify them in
* {@code body} parameter. If you don't need to change the default layout there is no need to call this method at all, it's enough to
* specify the plugin module in {@link org.jetbrains.intellij.build.ProductModulesLayout#bundledPluginModules bundledPluginModules/pluginModulesToPublish} list.
*
* <p>Note that project-level libraries on which the plugin modules depend, are automatically put to 'IDE_HOME/lib' directory for all IDEs
* which are compatible with the plugin. If this isn't desired (e.g. a library is used in a single plugin only, or if plugins where
* a library is used aren't bundled with IDEs so we don't want to increase size of the distribution, you may invoke {@link PluginLayoutSpec#withProjectLibrary}
* to include such a library to the plugin distribution.</p>
* @param mainModuleName name of the module containing META-INF/plugin.xml file of the plugin
*/
@JvmStatic
fun plugin(mainModuleName: String, body: Consumer<PluginLayoutSpec>): PluginLayout {
if (mainModuleName.isEmpty()) {
error("mainModuleName must be not empty")
}
val layout = PluginLayout(mainModuleName)
val spec = PluginLayoutSpec(layout)
body.accept(spec)
layout.directoryName = spec.directoryName
if (!layout.getIncludedModuleNames().contains(mainModuleName)) {
layout.withModule(mainModuleName, layout.mainJarName)
}
if (spec.mainJarNameSetExplicitly) {
layout.explicitlySetJarPaths.add(layout.mainJarName)
}
else {
layout.explicitlySetJarPaths.remove(layout.mainJarName)
}
layout.directoryNameSetExplicitly = spec.directoryNameSetExplicitly
layout.bundlingRestrictions = spec.bundlingRestrictions.build()
return layout
}
@JvmStatic
fun simplePlugin(mainModuleName: String): PluginLayout {
if (mainModuleName.isEmpty()) {
error("mainModuleName must be not empty")
}
val layout = PluginLayout(mainModuleName)
layout.directoryName = convertModuleNameToFileName(layout.mainModule)
layout.withModuleImpl(mainModuleName, layout.mainJarName)
layout.bundlingRestrictions = PluginBundlingRestrictions.NONE
return layout
}
}
override fun toString(): String {
return "Plugin '$mainModule'"
}
override fun withModule(moduleName: String) {
if (moduleName.endsWith(".jps") || moduleName.endsWith(".rt")) {
// must be in a separate JAR
super.withModule(moduleName)
}
else {
withModuleImpl(moduleName, mainJarName)
}
}
fun withGeneratedResources(generator: BiConsumer<Path, BuildContext>) {
resourceGenerators.add(Pair(BiFunction<Path, BuildContext, Path>{ targetDir, context ->
generator.accept(targetDir, context)
null
}, ""))
}
fun mergeServiceFiles() {
patchers.add(BiConsumer { patcher, context ->
val discoveredServiceFiles: MultiMap<String, Pair<String, Path>> = MultiMap.createLinkedSet()
moduleJars.get(mainJarName).forEach { moduleName: String ->
val path = context.findFileInModuleSources(moduleName, "META-INF/services")
if (path == null) return@forEach
Files.list(path).use { stream ->
stream
.filter { Files.isRegularFile(it) }
.forEach { serviceFile: Path ->
discoveredServiceFiles.putValue(serviceFile.fileName.toString(), Pair.create(moduleName, serviceFile))
}
}
}
discoveredServiceFiles.entrySet().forEach { entry: Map.Entry<String, Collection<Pair<String, Path>>> ->
val serviceFileName = entry.key
val serviceFiles: Collection<Pair<String, Path>> = entry.value
if (serviceFiles.size <= 1) return@forEach
val content = serviceFiles.joinToString("\n") { Files.readString(it.second) }
context.messages.info("Merging service file " + serviceFileName + " (" + serviceFiles.joinToString(", ") { it.first } + ")")
patcher.patchModuleOutput(serviceFiles.first().first, // first one wins
"META-INF/services/$serviceFileName",
content)
}
})
}
class PluginLayoutSpec(private val layout: PluginLayout): BaseLayoutSpec(layout) {
var directoryName: String = convertModuleNameToFileName(layout.mainModule)
/**
* Custom name of the directory (under 'plugins' directory) where the plugin should be placed. By default the main module name is used
* (with stripped {@code intellij} prefix and dots replaced by dashes).
* <strong>Don't set this property for new plugins</strong>; it is temporary added to keep layout of old plugins unchanged.
*/
set(value) {
field = value
directoryNameSetExplicitly = true
}
var mainJarNameSetExplicitly: Boolean = false
private set
var directoryNameSetExplicitly: Boolean = false
private set
val mainModule
get() = layout.mainModule
/**
* Returns {@link PluginBundlingRestrictions} instance which can be used to exclude the plugin from some distributions.
*/
val bundlingRestrictions: PluginBundlingRestrictionBuilder = PluginBundlingRestrictionBuilder()
class PluginBundlingRestrictionBuilder {
/**
* Change this value if the plugin works in some OS only and therefore don't need to be bundled with distributions for other OS.
*/
var supportedOs: List<OsFamily> = OsFamily.ALL
/**
* Change this value if the plugin works on some architectures only and
* therefore don't need to be bundled with distributions for other architectures.
*/
var supportedArch: List<JvmArchitecture> = JvmArchitecture.ALL
/**
* Set to {@code true} if the plugin should be included in distribution for EAP builds only.
*/
var includeInEapOnly: Boolean = false
fun build(): PluginBundlingRestrictions =
PluginBundlingRestrictions(supportedOs, supportedArch, includeInEapOnly)
}
var mainJarName: String
get() = layout.mainJarName
/**
* Custom name of the main plugin JAR file. By default the main module name with 'jar' extension is used (with stripped {@code intellij}
* prefix and dots replaced by dashes).
* <strong>Don't set this property for new plugins</strong>; it is temporary added to keep layout of old plugins unchanged.
*/
set(value) {
layout.mainJarName = value
mainJarNameSetExplicitly = true
}
/**
* @param binPathRelativeToCommunity path to resource file or directory relative to the intellij-community repo root
* @param outputPath target path relative to the plugin root directory
*/
@JvmOverloads
fun withBin(binPathRelativeToCommunity: String, outputPath: String, skipIfDoesntExist: Boolean = false) {
withGeneratedResources(BiConsumer { targetDir, context ->
val source = context.paths.communityHomeDir.resolve(binPathRelativeToCommunity).normalize()
if (Files.notExists(source)) {
if (skipIfDoesntExist) {
return@BiConsumer
}
error("'$source' doesn't exist")
}
if (Files.isRegularFile(source)) {
BuildHelper.copyFileToDir(source, targetDir.resolve(outputPath))
}
else {
BuildHelper.copyDir(source, targetDir.resolve(outputPath))
}
})
}
/**
* @param resourcePath path to resource file or directory relative to the plugin's main module content root
* @param relativeOutputPath target path relative to the plugin root directory
*/
fun withResource(resourcePath: String, relativeOutputPath: String) {
withResourceFromModule(layout.mainModule, resourcePath, relativeOutputPath)
}
/**
* @param resourcePath path to resource file or directory relative to {@code moduleName} module content root
* @param relativeOutputPath target path relative to the plugin root directory
*/
fun withResourceFromModule(moduleName: String, resourcePath: String, relativeOutputPath: String) {
layout.resourcePaths.add(ModuleResourceData(moduleName, resourcePath, relativeOutputPath, false))
}
/**
* @param resourcePath path to resource file or directory relative to the plugin's main module content root
* @param relativeOutputFile target path relative to the plugin root directory
*/
fun withResourceArchive(resourcePath: String, relativeOutputFile: String) {
withResourceArchiveFromModule(layout.mainModule, resourcePath, relativeOutputFile)
}
/**
* @param resourcePath path to resource file or directory relative to {@code moduleName} module content root
* @param relativeOutputFile target path relative to the plugin root directory
*/
fun withResourceArchiveFromModule(moduleName: String, resourcePath: String, relativeOutputFile: String) {
layout.resourcePaths.add(ModuleResourceData(moduleName, resourcePath, relativeOutputFile, true))
}
/**
* Copy output produced by {@code generator} to the directory specified by {@code relativeOutputPath} under the plugin directory.
*/
fun withGeneratedResources(generator: org.jetbrains.intellij.build.ResourcesGenerator, relativeOutputPath: String) {
layout.resourceGenerators.add(Pair(BiFunction<Path, BuildContext, Path> { _, context ->
generator.generateResources(context)?.toPath()
}, relativeOutputPath))
}
fun withPatch(patcher: BiConsumer<ModuleOutputPatcher, BuildContext> ) {
layout.patchers.add(patcher)
}
fun withGeneratedResources(generator: BiConsumer<Path, BuildContext>) {
layout.withGeneratedResources(generator)
}
/**
* By default, version of a plugin is equal to the build number of the IDE it's built with. This method allows to specify custom version evaluator.
*/
fun withCustomVersion(versionEvaluator: VersionEvaluator) {
layout.versionEvaluator = versionEvaluator
}
fun withPluginXmlPatcher(pluginXmlPatcher: UnaryOperator<String>) {
layout.pluginXmlPatcher = pluginXmlPatcher
}
@Deprecated(message = "localizable resources are always put to the module JAR, so there is no need to call this method anymore")
fun doNotCreateSeparateJarForLocalizableResources() {
}
/**
* This plugin will be compatible only with exactly the same IDE version.
* See {@link org.jetbrains.intellij.build.CompatibleBuildRange#EXACT}
*/
fun pluginCompatibilityExactVersion() {
layout.pluginCompatibilityExactVersion = true
}
/**
* <product-description> is usually removed for bundled plugins.
* Call this method to retain it in plugin.xml
*/
fun retainProductDescriptorForBundledPlugin() {
layout.retainProductDescriptorForBundledPlugin = true
}
/**
* Do not automatically include module libraries from {@code moduleNames}
* <strong>Do not use this for new plugins, this method is temporary added to keep layout of old plugins</strong>.
*/
fun doNotCopyModuleLibrariesAutomatically(moduleNames: List<String>) {
layout.modulesWithExcludedModuleLibraries.addAll(moduleNames)
}
/**
* Specifies a relative path to a plugin jar that should be scrambled.
* Scrambling is performed by the {@link org.jetbrains.intellij.build.ProprietaryBuildTools#scrambleTool}
* If scramble tool is not defined, scrambling will not be performed
* Multiple invocations of this method will add corresponding paths to a list of paths to be scrambled
*
* @param relativePath - a path to a jar file relative to plugin root directory
*/
fun scramble(relativePath: String) {
layout.pathsToScramble.add(relativePath)
}
/**
* Specifies a relative to {@link org.jetbrains.intellij.build.BuildPaths#communityHome} path to a zkm script stub file.
* If scramble tool is not defined, scramble toot will expect to find the script stub file at "{@link org.jetbrains.intellij.build.BuildPaths#projectHome}/plugins/{@code pluginName}/build/script.zkm.stub".
* Project home cannot be used since it is not constant (for example for Rider).
*
* @param communityRelativePath - a path to a jar file relative to community project home directory
*/
fun zkmScriptStub(communityRelativePath: String) {
layout.zkmScriptStub = communityRelativePath
}
/**
* Specifies a dependent plugin name to be added to scrambled classpath
* Scrambling is performed by the {@link org.jetbrains.intellij.build.ProprietaryBuildTools#scrambleTool}
* If scramble tool is not defined, scrambling will not be performed
* Multiple invocations of this method will add corresponding plugin names to a list of name to be added to scramble classpath
*
* @param pluginName - a name of dependent plugin, whose jars should be added to scramble classpath
* @param relativePath - a directory where jars should be searched (relative to plugin home directory, "lib" by default)
*/
@JvmOverloads
fun scrambleClasspathPlugin(pluginName: String, relativePath: String = "lib") {
layout.scrambleClasspathPlugins.add(Pair(pluginName, relativePath))
}
/**
* Allows control over classpath entries that will be used by the scrambler to resolve references from jars being scrambled.
* By default all platform jars are added to the 'scramble classpath'
*/
fun filterScrambleClasspath(filter: BiPredicate<BuildContext, Path>) {
layout.scrambleClasspathFilter = filter
}
/**
* Concatenates `META-INF/services` files with the same name from different modules together.
* By default the first service file silently wins.
*/
fun mergeServiceFiles() {
layout.mergeServiceFiles()
}
}
interface VersionEvaluator {
fun evaluate(pluginXml: Path, ideBuildVersion: String, context: BuildContext): String
}
} | platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/PluginLayout.kt | 975677679 |
// FIR_IDENTICAL
// FIR_COMPARISON
val property: Int
get() {
<caret>
}
// EXIST: return
| plugins/kotlin/completion/tests/testData/keywords/Return7.kt | 1695174796 |
// 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.uast.kotlin.psi
import com.intellij.openapi.components.ServiceManager
import com.intellij.psi.*
import com.intellij.psi.impl.light.LightTypeElement
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.asJava.elements.LightVariableBuilder
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.uast.*
import org.jetbrains.uast.kotlin.*
@ApiStatus.Internal
class UastKotlinPsiVariable private constructor(
manager: PsiManager,
name: String,
typeProducer: () -> PsiType,
val ktInitializer: KtExpression?,
psiParentProducer: () -> PsiElement?,
val containingElement: UElement,
val ktElement: KtElement
) : LightVariableBuilder(
manager,
name,
UastErrorType, // Type is calculated lazily
KotlinLanguage.INSTANCE
), PsiLocalVariable {
val psiParent by lz(psiParentProducer)
private val psiType: PsiType by lz(typeProducer)
private val psiTypeElement: PsiTypeElement by lz {
LightTypeElement(manager, psiType)
}
private val psiInitializer: PsiExpression? by lz {
ktInitializer?.let { KotlinUastPsiExpression(it, containingElement) }
}
override fun getType(): PsiType = psiType
override fun getText(): String = ktElement.text
override fun getParent() = psiParent
override fun hasInitializer() = ktInitializer != null
override fun getInitializer(): PsiExpression? = psiInitializer
override fun getTypeElement() = psiTypeElement
override fun setInitializer(initializer: PsiExpression?) = throw NotImplementedError()
override fun getContainingFile(): PsiFile? = ktElement.containingFile
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || other::class.java != this::class.java) return false
return ktElement == (other as? UastKotlinPsiVariable)?.ktElement
}
override fun isEquivalentTo(another: PsiElement?): Boolean = this == another || ktElement.isEquivalentTo(another)
override fun hashCode() = ktElement.hashCode()
companion object {
fun create(
declaration: KtVariableDeclaration,
parent: PsiElement?,
containingElement: KotlinUDeclarationsExpression,
initializer: KtExpression? = null
): PsiLocalVariable {
val psi = containingElement.psiAnchor ?: containingElement.sourcePsi
val psiParent = psi?.getNonStrictParentOfType<KtDeclaration>() ?: parent
val initializerExpression = initializer ?: declaration.initializer
return UastKotlinPsiVariable(
manager = declaration.manager,
name = declaration.name.orAnonymous("<unnamed>"),
typeProducer = {
val service = ServiceManager.getService(BaseKotlinUastResolveProviderService::class.java)
service.getType(declaration, containingElement) ?: UastErrorType
},
ktInitializer = initializerExpression,
psiParentProducer = { psiParent },
containingElement = containingElement,
ktElement = declaration)
}
fun create(
declaration: KtDestructuringDeclaration,
containingElement: UElement
): PsiLocalVariable =
UastKotlinPsiVariable(
manager = declaration.manager,
name = "var" + Integer.toHexString(declaration.getHashCode()),
typeProducer = {
val service = ServiceManager.getService(BaseKotlinUastResolveProviderService::class.java)
service.getType(declaration, containingElement) ?: UastErrorType
},
ktInitializer = declaration.initializer,
psiParentProducer = { containingElement.getParentOfType<UDeclaration>()?.psi ?: declaration.parent },
containingElement = containingElement,
ktElement = declaration
)
fun create(
initializer: KtExpression,
containingElement: UElement,
parent: PsiElement
): PsiLocalVariable =
UastKotlinPsiVariable(
manager = initializer.manager,
name = "var" + Integer.toHexString(initializer.getHashCode()),
typeProducer = {
val service = ServiceManager.getService(BaseKotlinUastResolveProviderService::class.java)
service.getType(initializer, containingElement) ?: UastErrorType
},
ktInitializer = initializer,
psiParentProducer = { containingElement.getParentOfType<UDeclaration>()?.psi ?: parent },
containingElement = containingElement,
ktElement = initializer
)
fun create(
name: String,
localFunction: KtFunction,
containingElement: UElement
): PsiLocalVariable =
UastKotlinPsiVariable(
manager = localFunction.manager,
name = name,
typeProducer = {
val service = ServiceManager.getService(BaseKotlinUastResolveProviderService::class.java)
service.getFunctionType(localFunction, containingElement) ?: UastErrorType
},
ktInitializer = localFunction,
psiParentProducer = { containingElement.getParentOfType<UDeclaration>()?.psi ?: localFunction.parent },
containingElement = containingElement,
ktElement = localFunction
)
}
}
private class KotlinUastPsiExpression(
val ktExpression: KtExpression,
val parent: UElement
) : PsiElement by ktExpression, PsiExpression {
override fun getType(): PsiType? {
val service = ServiceManager.getService(BaseKotlinUastResolveProviderService::class.java)
return service.getType(ktExpression, parent)
}
}
private fun PsiElement.getHashCode(): Int {
var result = 42
result = 41 * result + (containingFile?.name?.hashCode() ?: 0)
result = 41 * result + startOffset
result = 41 * result + text.hashCode()
return result
}
| plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/psi/UastKotlinPsiVariable.kt | 2918962038 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.grazie
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.grazie.config.CheckingContext
import com.intellij.grazie.config.DetectionContext
import com.intellij.grazie.config.SuppressingContext
import com.intellij.grazie.config.migration.VersionedState
import com.intellij.grazie.grammar.LanguageToolChecker
import com.intellij.grazie.ide.msg.GrazieInitializerManager
import com.intellij.grazie.jlanguage.Lang
import com.intellij.grazie.jlanguage.LangTool
import com.intellij.grazie.text.Rule
import com.intellij.openapi.components.*
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.util.ModificationTracker
import com.intellij.util.containers.CollectionFactory
import com.intellij.util.xmlb.annotations.Property
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.VisibleForTesting
import java.util.*
import java.util.concurrent.atomic.AtomicLong
@State(name = "GraziConfig", presentableName = GrazieConfig.PresentableNameGetter::class, storages = [
Storage("grazie_global.xml"),
Storage(value = "grazi_global.xml", deprecated = true)
], category = SettingsCategory.CODE)
class GrazieConfig : PersistentStateComponent<GrazieConfig.State>, ModificationTracker {
@Suppress("unused")
enum class Version : VersionedState.Version<State> {
INITIAL,
//Since commit abc7e5f5
OLD_UI {
@Suppress("DEPRECATION")
override fun migrate(state: State) = state.copy(
checkingContext = CheckingContext(
isCheckInCommitMessagesEnabled = state.enabledCommitIntegration
)
)
},
//Since commit cc47dd17
NEW_UI;
override fun next() = values().getOrNull(ordinal + 1)
override fun toString() = ordinal.toString()
companion object {
val CURRENT = NEW_UI
}
}
/**
* State of Grazie plugin
*
* Note, that all serialized values should be MUTABLE.
* Immutable values (like emptySet()) as default may lead to deserialization failure
*/
data class State(
@Property val enabledLanguages: Set<Lang> = hashSetOf(Lang.AMERICAN_ENGLISH),
@Deprecated("Use checkingContext.disabledLanguages") @ApiStatus.ScheduledForRemoval @Property val enabledGrammarStrategies: Set<String> = HashSet(defaultEnabledStrategies),
@Deprecated("Use checkingContext.disabledLanguages") @ApiStatus.ScheduledForRemoval @Property val disabledGrammarStrategies: Set<String> = HashSet(),
@Deprecated("Moved to checkingContext in version 2") @ApiStatus.ScheduledForRemoval @Property val enabledCommitIntegration: Boolean = false,
@Property val userDisabledRules: Set<String> = HashSet(),
@Property val userEnabledRules: Set<String> = HashSet(),
//Formerly suppressionContext -- name changed due to compatibility issues
@Property val suppressingContext: SuppressingContext = SuppressingContext(),
@Property val detectionContext: DetectionContext.State = DetectionContext.State(),
@Property val checkingContext: CheckingContext = CheckingContext(),
@Property override val version: Version = Version.CURRENT
) : VersionedState<Version, State> {
/**
* The available language set depends on currently loaded LanguageTool modules.
*
* Note that after loading of a new module, this field will not change. It will
* remain equal to the moment the field was accessed first time.
*
* Lazy is used, because deserialized properties are updated during initial deserialization
*
* NOTE: By default, availableLanguages are not included into [equals]. Check for it manually.
*/
val availableLanguages: Set<Lang> by lazy {
enabledLanguages.asSequence().filter { lang -> lang.jLanguage != null }.toCollection(CollectionFactory.createSmallMemoryFootprintLinkedSet())
}
val missedLanguages: Set<Lang>
get() = enabledLanguages.asSequence().filter { it.jLanguage == null }.toCollection(CollectionFactory.createSmallMemoryFootprintLinkedSet())
override fun increment() = copy(version = version.next() ?: error("Attempt to increment latest version $version"))
fun hasMissedLanguages(): Boolean {
return enabledLanguages.any { it.jLanguage == null }
}
}
companion object {
private val defaultEnabledStrategies =
Collections.unmodifiableSet(hashSetOf("nl.rubensten.texifyidea:Latex", "org.asciidoctor.intellij.asciidoc:AsciiDoc"))
@VisibleForTesting
fun migrateLTRuleIds(state: State): State {
val ltRules: List<Rule> by lazy {
state.enabledLanguages.filter { it.jLanguage != null }.flatMap { LanguageToolChecker.grammarRules(LangTool.createTool(it, state), it) }
}
fun convert(ids: Set<String>): Set<String> =
ids.flatMap { id ->
if (id.contains(".")) listOf(id)
else ltRules.asSequence().map { it.globalId }.filter { it.startsWith("LanguageTool.") && it.endsWith(".$id") }.toList()
}.toSet()
return state.copy(userEnabledRules = convert(state.userEnabledRules), userDisabledRules = convert(state.userDisabledRules))
}
private val instance by lazy { service<GrazieConfig>() }
/**
* Get copy of Grazie config state
*
* Should never be called in GrazieStateLifecycle actions
*/
fun get() = instance.state
/** Update Grazie config state */
@Synchronized
fun update(change: (State) -> State) = instance.loadState(change(get()))
fun stateChanged(prevState: State, newState: State) {
service<GrazieInitializerManager>().publisher.update(prevState, newState)
ProjectManager.getInstance().openProjects.forEach {
DaemonCodeAnalyzer.getInstance(it).restart()
}
}
}
class PresentableNameGetter : com.intellij.openapi.components.State.NameGetter() {
override fun get() = GrazieBundle.message("grazie.config.name")
}
private var myState = State()
private var myModCount = AtomicLong()
override fun getModificationCount(): Long = myModCount.get()
override fun getState() = myState
override fun loadState(state: State) {
myModCount.incrementAndGet()
val prevState = myState
myState = migrateLTRuleIds(VersionedState.migrate(state))
if (prevState != myState) {
stateChanged(prevState, myState)
}
}
}
| plugins/grazie/src/main/kotlin/com/intellij/grazie/GrazieConfig.kt | 3579460933 |
// "Cast expression 'listOf(1)' to 'List<T>'" "true"
// WITH_STDLIB
// ERROR: Type mismatch: inferred type is IntegerLiteralType[Int,Long,Byte,Short] but T was expected
// IGNORE_FE10
fun <T> f() {
val someList: List<T> = lis<caret>tOf(1)
} | plugins/kotlin/idea/tests/testData/quickfix/typeMismatch/casts/typeMismatch5.kt | 511184927 |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.integration.uiwidgets.rotations
import android.content.ContentResolver
import android.net.Uri
import android.util.Size
import androidx.camera.core.ImageProxy
import androidx.camera.core.impl.utils.Exif
import java.io.File
/** A wrapper around an ImageCapture result, used for testing. */
sealed class ImageCaptureResult {
abstract fun getResolution(): Size
abstract fun getRotation(): Int
abstract fun delete()
class InMemory(private val imageProxy: ImageProxy) : ImageCaptureResult() {
override fun getResolution() = Size(imageProxy.width, imageProxy.height)
override fun getRotation() = imageProxy.imageInfo.rotationDegrees
override fun delete() {}
}
class FileOrOutputStream(private val file: File) : ImageCaptureResult() {
private val exif = Exif.createFromFile(file)
override fun getResolution() = Size(exif.width, exif.height)
override fun getRotation() = exif.rotation
override fun delete() {
file.delete()
}
}
class MediaStore(private val contentResolver: ContentResolver, private val uri: Uri) :
ImageCaptureResult() {
private val exif: Exif
init {
val inputStream = contentResolver.openInputStream(uri)
exif = Exif.createFromInputStream(inputStream!!)
}
override fun getResolution() = Size(exif.width, exif.height)
override fun getRotation() = exif.rotation
override fun delete() {
contentResolver.delete(uri, null, null)
}
}
} | camera/integration-tests/uiwidgetstestapp/src/main/java/androidx/camera/integration/uiwidgets/rotations/ImageCaptureResult.kt | 1320876588 |
package org.thoughtcrime.securesms.components.settings.app.subscription.manage
import org.thoughtcrime.securesms.badges.models.Badge
import org.thoughtcrime.securesms.subscription.Subscription
import org.whispersystems.signalservice.api.subscriptions.ActiveSubscription
data class ManageDonationsState(
val hasOneTimeBadge: Boolean = false,
val hasReceipts: Boolean = false,
val featuredBadge: Badge? = null,
val transactionState: TransactionState = TransactionState.Init,
val availableSubscriptions: List<Subscription> = emptyList(),
private val subscriptionRedemptionState: SubscriptionRedemptionState = SubscriptionRedemptionState.NONE
) {
fun getMonthlyDonorRedemptionState(): SubscriptionRedemptionState {
return when (transactionState) {
TransactionState.Init -> subscriptionRedemptionState
TransactionState.NetworkFailure -> subscriptionRedemptionState
TransactionState.InTransaction -> SubscriptionRedemptionState.IN_PROGRESS
is TransactionState.NotInTransaction -> getStateFromActiveSubscription(transactionState.activeSubscription) ?: subscriptionRedemptionState
}
}
fun getStateFromActiveSubscription(activeSubscription: ActiveSubscription): SubscriptionRedemptionState? {
return when {
activeSubscription.isFailedPayment -> SubscriptionRedemptionState.FAILED
activeSubscription.isInProgress -> SubscriptionRedemptionState.IN_PROGRESS
else -> null
}
}
sealed class TransactionState {
object Init : TransactionState()
object NetworkFailure : TransactionState()
object InTransaction : TransactionState()
class NotInTransaction(val activeSubscription: ActiveSubscription) : TransactionState()
}
enum class SubscriptionRedemptionState {
NONE,
IN_PROGRESS,
FAILED
}
}
| app/src/main/java/org/thoughtcrime/securesms/components/settings/app/subscription/manage/ManageDonationsState.kt | 1105013290 |
package org.joltsphere.scenes
import org.joltsphere.main.JoltSphereMain
import org.joltsphere.mountain.MountainSpace
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Screen
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer
import com.badlogic.gdx.physics.box2d.World
class Scene3(internal val game: JoltSphereMain) : Screen {
internal var world: World
internal var debugRender: Box2DDebugRenderer
internal var mountainSpace: MountainSpace
internal var ppm = JoltSphereMain.ppm
init {
world = World(Vector2(0f, -9.8f), false) //ignore inactive objects false
debugRender = Box2DDebugRenderer()
mountainSpace = MountainSpace(world)
}
private fun update(dt: Float) {
mountainSpace.update(dt, game.cam.viewportWidth / 2f, game.cam.viewportHeight / 2f)
world.step(dt, 6, 2)
}
override fun render(dt: Float) {
update(dt)
Gdx.gl.glClearColor(0f, 0f, 0f, 1f)
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
game.shapeRender.begin(ShapeType.Filled)
mountainSpace.shapeRender(game.shapeRender)
game.shapeRender.end()
debugRender.render(world, game.phys2DCam.combined)
game.batch.begin()
//game.font.draw(game.batch, mountainSpace.points + "boombooms FPS: " + Gdx.graphics.getFramesPerSecond(), game.width*0.27f, game.height * 0.85f);
game.batch.end()
val zoom = mountainSpace.getZoom(game.cam.viewportHeight)
game.cam.zoom = zoom
game.phys2DCam.zoom = zoom
game.cam.position.set(mountainSpace.cameraPostion, 0f)
game.phys2DCam.position.set(mountainSpace.debugCameraPostion, 0f)
game.cam.update()
game.phys2DCam.update()
}
override fun dispose() {
}
override fun resize(width: Int, height: Int) {
game.resize(width, height)
}
override fun show() {}
override fun pause() {}
override fun resume() {}
override fun hide() {}
} | core/src/org/joltsphere/scenes/Scene3.kt | 3113386045 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.integration.uiwidgets.compose.ui.screen.components
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.size
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.dp
private val CAMERA_CONTROL_BUTTON_SIZE = 64.dp
@Composable
fun CameraControlButton(
imageVector: ImageVector,
contentDescription: String,
modifier: Modifier = Modifier,
tint: Color = Color.Unspecified,
onClick: () -> Unit
) {
IconButton(
onClick = onClick,
modifier = modifier.size(CAMERA_CONTROL_BUTTON_SIZE)
) {
Icon(
imageVector = imageVector,
contentDescription = contentDescription,
modifier = modifier.size(CAMERA_CONTROL_BUTTON_SIZE),
tint = tint
)
}
}
@Composable
fun CameraControlText(
text: String,
modifier: Modifier = Modifier
) {
Text(
text = text,
modifier = modifier.size(CAMERA_CONTROL_BUTTON_SIZE)
)
}
@Composable
fun CameraControlButtonPlaceholder(modifier: Modifier = Modifier) {
Spacer(modifier = modifier.size(CAMERA_CONTROL_BUTTON_SIZE))
} | camera/integration-tests/uiwidgetstestapp/src/main/java/androidx/camera/integration/uiwidgets/compose/ui/screen/components/CameraControlButton.kt | 271255396 |
fun f(a: Int) {
if (a > 0) {
<lineMarker text="Recursive call">f</lineMarker>(a - 1)
}
} | plugins/kotlin/code-insight/line-markers/testData/recursive/simple.kt | 4194398324 |
package com.intellij.xdebugger.impl.ui.attach.dialog
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.UserDataHolder
import com.intellij.xdebugger.attach.XAttachHost
import com.intellij.xdebugger.attach.XAttachHostProvider
import com.intellij.xdebugger.attach.XAttachPresentationGroup
import javax.swing.Icon
@Suppress("UNCHECKED_CAST")
data class AttachHostAndProvider(
val host: XAttachHost,
val provider: XAttachHostProvider<out XAttachHost>,
val project: Project,
val dataHolder: UserDataHolder) {
override fun toString(): String {
val presentationGroup = provider.presentationGroup as XAttachPresentationGroup<XAttachHost>
return presentationGroup.getItemDisplayText(project, host, dataHolder)
}
fun getIcon(): Icon {
val presentationGroup = provider.presentationGroup as XAttachPresentationGroup<XAttachHost>
return presentationGroup.getItemIcon(project, host, dataHolder)
}
override fun equals(other: Any?): Boolean {
if (other !is AttachHostAndProvider) {
return false
}
return other.host == host
}
override fun hashCode(): Int {
return host.hashCode()
}
} | platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/attach/dialog/AttachHostAndProvider.kt | 2255948996 |
// 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.stubindex
import com.intellij.openapi.project.Project
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.stubs.StubIndex
import com.intellij.psi.stubs.StubIndexKey
import org.jetbrains.kotlin.psi.KtNamedFunction
object KotlinFunctionShortNameIndex : KotlinStringStubIndexExtension<KtNamedFunction>(KtNamedFunction::class.java) {
private val KEY: StubIndexKey<String, KtNamedFunction> =
StubIndexKey.createIndexKey("org.jetbrains.kotlin.idea.stubindex.KotlinFunctionShortNameIndex")
override fun getKey(): StubIndexKey<String, KtNamedFunction> = KEY
override fun get(s: String, project: Project, scope: GlobalSearchScope): Collection<KtNamedFunction> {
return StubIndex.getElements(KEY, s, project, scope, KtNamedFunction::class.java)
}
@JvmStatic
@Deprecated("Use KotlinFunctionShortNameIndex as an object.", ReplaceWith("KotlinFunctionShortNameIndex"))
fun getInstance(): KotlinFunctionShortNameIndex = KotlinFunctionShortNameIndex
} | plugins/kotlin/base/indices/src/org/jetbrains/kotlin/idea/stubindex/KotlinFunctionShortNameIndex.kt | 3135463129 |
// COMPILER_ARGUMENTS: -XXLanguage:+GenericInlineClassParameter
package filterFunctionCallsFromInlineClass
@JvmInline
value class A<T>(val str: T) {
fun foo(): A<T> {
return this
}
private fun foo(i: Int, j: Int): A<T> {
return this
}
fun bar(): A<T> {
return this
}
private fun baz(): A<T> {
return this
}
inline fun inlineFoo(): A<T> {
return this
}
private inline fun inlineFoo(i: Int, j: Int): A<T> {
return this
}
inline fun inlineBar(): A<T> {
return this
}
private inline fun inlineBaz(): A<T> {
return this
}
fun testNoInlineCalls() {
// STEP_OVER: 1
//Breakpoint!
stopHere()
// SMART_STEP_INTO_BY_INDEX: 1
// STEP_OUT: 1
// SMART_STEP_TARGETS_EXPECTED_NUMBER: 3
foo().bar().foo(1, 2).baz()
// STEP_OVER: 1
//Breakpoint!
stopHere()
// SMART_STEP_INTO_BY_INDEX: 2
// STEP_OUT: 1
// SMART_STEP_TARGETS_EXPECTED_NUMBER: 2
foo().bar().foo(1, 2).baz()
// STEP_OVER: 1
//Breakpoint!
stopHere()
// SMART_STEP_INTO_BY_INDEX: 3
// STEP_OUT: 1
// SMART_STEP_TARGETS_EXPECTED_NUMBER: 1
foo().bar().foo(1, 2).baz()
}
fun testFirstCallIsInline() {
// STEP_OVER: 1
//Breakpoint!
stopHere()
// SMART_STEP_INTO_BY_INDEX: 1
// STEP_OUT: 1
// SMART_STEP_TARGETS_EXPECTED_NUMBER: 3
inlineFoo().bar().foo(1, 2).baz()
// STEP_OVER: 1
//Breakpoint!
stopHere()
// SMART_STEP_INTO_BY_INDEX: 2
// STEP_OUT: 1
// SMART_STEP_TARGETS_EXPECTED_NUMBER: 2
inlineFoo().bar().foo(1, 2).baz()
// STEP_OVER: 1
//Breakpoint!
stopHere()
// SMART_STEP_INTO_BY_INDEX: 3
// STEP_OUT: 1
// SMART_STEP_TARGETS_EXPECTED_NUMBER: 1
inlineFoo().bar().foo(1, 2).baz()
}
fun testFirstAndThirdCallsAreInline() {
// STEP_OVER: 1
//Breakpoint!
stopHere()
// SMART_STEP_INTO_BY_INDEX: 1
// STEP_OUT: 1
// SMART_STEP_TARGETS_EXPECTED_NUMBER: 3
inlineFoo().bar().inlineFoo(1, 2).baz()
// STEP_OVER: 1
//Breakpoint!
stopHere()
// SMART_STEP_INTO_BY_INDEX: 2
// STEP_OUT: 1
// SMART_STEP_TARGETS_EXPECTED_NUMBER: 2
inlineFoo().bar().inlineFoo(1, 2).baz()
// STEP_OVER: 1
//Breakpoint!
stopHere()
// SMART_STEP_INTO_BY_INDEX: 3
// STEP_OUT: 1
// SMART_STEP_TARGETS_EXPECTED_NUMBER: 1
inlineFoo().bar().inlineFoo(1, 2).baz()
}
fun testAllCallsAreInline() {
// STEP_OVER: 1
//Breakpoint!
stopHere()
// SMART_STEP_INTO_BY_INDEX: 1
// STEP_OUT: 1
// SMART_STEP_TARGETS_EXPECTED_NUMBER: 3
inlineFoo().inlineBar().inlineFoo(1, 2).inlineBaz()
// STEP_OVER: 1
//Breakpoint!
stopHere()
// SMART_STEP_INTO_BY_INDEX: 2
// STEP_OUT: 1
// SMART_STEP_TARGETS_EXPECTED_NUMBER: 2
inlineFoo().inlineBar().inlineFoo(1, 2).inlineBaz()
// STEP_OVER: 1
//Breakpoint!
stopHere()
// SMART_STEP_INTO_BY_INDEX: 3
// STEP_OUT: 1
// SMART_STEP_TARGETS_EXPECTED_NUMBER: 1
inlineFoo().inlineBar().inlineFoo(1, 2).inlineBaz()
}
}
fun Int.foo(a: A<*>): Int {
return 1
}
fun Int.bar(a: A<*>): Int {
return 2
}
fun testMethodContainsInlineClassInValueArguments() {
val a = A("TEXT")
// STEP_OVER: 1
//Breakpoint!
stopHere()
// SMART_STEP_INTO_BY_INDEX: 1
// STEP_OUT: 1
// SMART_STEP_TARGETS_EXPECTED_NUMBER: 2
1.foo(a).bar(a).foo(a)
// STEP_OVER: 1
//Breakpoint!
stopHere()
// SMART_STEP_INTO_BY_INDEX: 2
// STEP_OUT: 1
// SMART_STEP_TARGETS_EXPECTED_NUMBER: 1
1.foo(a).bar(a).foo(a)
}
fun main() {
val a = A("TEXT")
a.testNoInlineCalls()
a.testFirstCallIsInline()
a.testFirstAndThirdCallsAreInline()
a.testAllCallsAreInline()
testMethodContainsInlineClassInValueArguments()
}
fun stopHere() {
}
// IGNORE_K2 | plugins/kotlin/jvm-debugger/test/testData/stepping/custom/filterFunctionCallsFromInlineClass.kt | 2930573841 |
open class Base {
open fun f() {}
fun g() {
println("g() called")
}
}
abstract class Derived : Base() {
override abstract fun f()
}
class Derived2 : Base() {
override fun f() {
println("f() called")
}
}
fun main(args: Array<String>) {
Derived2().f()
Derived2().g()
}
| test-src/18_abstract.kt | 2661109093 |
// p.AllPrivate
// WITH_RUNTIME
@file:kotlin.jvm.JvmMultifileClass
@file:kotlin.jvm.JvmName("AllPrivate")
package p
private fun f(): Int = 3
private fun g(p: String): String = "p"
// FIR_COMPARISON | plugins/kotlin/idea/tests/testData/compiler/asJava/lightClasses/facades/AllPrivate.kt | 764149369 |
package com.lucasgomes.consultacep.models
import com.google.gson.annotations.SerializedName
/**
* Created by Lucas Gomes on 11/09/2017.
*/
data class Endereco(
@SerializedName("cep")
val Cep : String,
@SerializedName("logradouro")
val Logradouro : String,
@SerializedName("complemento")
val Complemento : String,
@SerializedName("bairro")
val Bairro : String,
@SerializedName("localidade")
val Localidade : String,
@SerializedName("uf")
val Uf : String,
@SerializedName("ibge")
val Ibge : Int
) | ConsultaCEP/app/src/main/java/com/lucasgomes/consultacep/models/Endereco.kt | 1518600384 |
package com.maubis.scarlet.base.export.data
class ExportableFileFormat(
val version: Int,
val notes: List<ExportableNote>,
val tags: List<ExportableTag>,
val folders: List<ExportableFolder>?) | base/src/main/java/com/maubis/scarlet/base/export/data/ExportableFileFormat.kt | 2568581778 |
// FIR_COMPARISON
fun main(args: Array<String>) {
println(R.<caret>)
}
// INVOCATION_COUNT: 1
// EXIST: layout | plugins/kotlin/completion/tests/testData/basic/multifile/JavaInnerClasses/JavaInnerClasses.kt | 909501409 |
package alraune
import alraune.operations.*
import vgrechka.*
import java.io.File
import java.nio.file.Files
import java.nio.file.attribute.PosixFilePermission
import java.util.*
object MakeAlCtlLinux {
@JvmStatic fun main(args: Array<String>) {
val cp = System.getProperty("java.class.path")
fun fart(filePrefix: String, cmdPrefix: String) {
val file = File("${System.getProperty("user.home")}/bin/${filePrefix}al-ctl")
file.writeText("""
#!/bin/bash
# Generated on ${Date()}
SWT_GTK3=0 ${cmdPrefix}java -D${AlopsConst.JavaSystemProperty.AlCtlCommand}=$1 \
-cp $cp ${AlExecuteCtlCommand::class.qualifiedName} \
"$@"
""".trimIndent())
Files.setPosixFilePermissions(file.toPath(), setOf(
PosixFilePermission.OWNER_READ,
PosixFilePermission.OWNER_WRITE,
PosixFilePermission.OWNER_EXECUTE))
}
fart(filePrefix = "", cmdPrefix = "")
fart(filePrefix = "su-", cmdPrefix = "sudo ")
}
}
//object MakeAlCtl {
// var binDir by notNullOnce<File>()
//
// @JvmStatic
// fun main(args: Array<String>) {
// AlGlobal_MergeMeToKotlinVersion.commandLineArgs = args
// binDir = File(FEProps.shitDir + "/bin")
// if (binDir.exists() && !binDir.isDirectory)
// bitch("I want this to be a directory: ${binDir.path}")
// if (!binDir.exists())
// binDir.mkdir()
//
// forUnix()
// }
//
// private fun forUnix() {
// val buf = StringBuilder()
// fun line(x: String) = buf.append(x + "\n")
//
// line("#!/bin/bash")
// line("CP=${AlConst.cpFirstDir(FEProps.shitDir)}")
// for (entry in System.getProperty("java.class.path").split(File.pathSeparator)) {
// line("CP=\$CP${File.pathSeparator}$entry")
// }
// line("")
// line("java -cp \$CP ${AlExecuteCtlCommand::class.qualifiedName} \"$@\"")
//
// fun writeOut(scriptName: String, content: String) {
// val file = File("${binDir.path}/$scriptName")
// file.writeText(content)
// file.setExecutable(true)
// }
//
// exhaustive=when (AlConfig.envKind) {
// AlConfig.EnvKind.Staging -> {
// writeOut("al-ctl", buf.toString())
// }
// AlConfig.EnvKind.WSLLocalDev -> {
// writeOut("al-ctl--staging", buf.toString())
//
// val p = Alk.Projects
// writeOut("al-ctl", buf.toString()
// .replace("/mnt/e/fegh/fe-private/alraune-private/build/classes/java/main", "boobs")
// .replace("/mnt/e/fegh/fe-private/alraune-private/build/classes/kotlin/main", p.alraunePrivate.ideaOutputClasses)
// .replace("/mnt/e/fegh/fe-private/alraune-private/build/resources/main", p.alraunePrivate.ideaOutputResources)
// .replace(Regex("""/mnt/e/fegh/alraune/alraune/build/libs/alraune-\d+.\d+.\d+.*?\.jar"""), "${p.alraune.ideaOutputClasses}${File.pathSeparator}${p.alraune.ideaOutputResources}")
// .replace(Regex("""/mnt/e/fegh/alraune/alraune-ap/build/libs/alraune-ap-\d+.\d+.\d+.*?\.jar"""), "${p.alrauneAp.ideaOutputClasses}${File.pathSeparator}${p.alrauneAp.ideaOutputResources}")
// .replace(Regex("""/mnt/e/fegh/alraune/alraune-ap-light/build/libs/alraune-ap-light-\d+.\d+.\d+.*?\.jar"""), "${p.alrauneApLight.ideaOutputClasses}${File.pathSeparator}${p.alrauneApLight.ideaOutputResources}")
// .replace(Regex("""/mnt/e/fegh/fe-private/alraune-private/build/libs/alraune-private-\d+.\d+.\d+.*?\.jar"""), "${p.alraunePrivate.ideaOutputClasses}${File.pathSeparator}${p.alraunePrivate.ideaOutputResources}")
// .replace(Regex("""/mnt/e/fegh/hot-reloadable-idea-piece-of-shit/build/libs/hot-reloadable-idea-piece-of-shit-\d+.\d+.\d+.*?\.jar"""), "${p.hotReloadableIdeaPieceOfShit.ideaOutputClasses}${File.pathSeparator}${p.hotReloadableIdeaPieceOfShit.ideaOutputResources}")
// .replace(Regex("""/mnt/e/fegh/idea-backdoor-client/build/libs/idea-backdoor-client-\d+.\d+.\d+.*?\.jar"""), "${p.ideaBackdoorClient.ideaOutputClasses}${File.pathSeparator}${p.ideaBackdoorClient.ideaOutputResources}")
// .replace(Regex("""/mnt/e/fegh/jaco-0/build/libs/jaco-0-\d+.\d+.\d+.*?\.jar"""), "${p.jaco0.ideaOutputClasses}${File.pathSeparator}${p.jaco0.ideaOutputResources}")
// .replace(Regex("""/mnt/e/fegh/shared-idea/build/libs/shared-idea-\d+.\d+.\d+.*?\.jar"""), "${p.sharedIdea.ideaOutputClasses}${File.pathSeparator}${p.sharedIdea.ideaOutputResources}")
// .replace(Regex("""/mnt/e/fegh/1/shared-jvm/build/libs/shared-jvm-\d+.\d+.\d+.*?\.jar"""), "${p.sharedJvm.ideaOutputClasses}${File.pathSeparator}${p.sharedJvm.ideaOutputResources}")
// )
// }
// }
// }
//
//}
| alraune/alraune/src/main/java/alraune/MakeAlCtlLinux.kt | 2044764232 |
// 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.application.options
import com.intellij.application.options.editor.EditorOptionsProvider
import com.intellij.codeInsight.CodeInsightSettings
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.ide.PowerSaveMode
import com.intellij.ide.ui.UISettings
import com.intellij.lang.LangBundle
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.application.ApplicationBundle
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.BaseExtensionPointName
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.options.BoundCompositeConfigurable
import com.intellij.openapi.options.Configurable
import com.intellij.openapi.options.Configurable.WithEpDependencies
import com.intellij.openapi.options.UnnamedConfigurable
import com.intellij.openapi.options.ex.ConfigurableWrapper
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.DialogPanel
import com.intellij.ui.IdeUICustomization
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.JBRadioButton
import com.intellij.ui.dsl.builder.*
import com.intellij.ui.dsl.builder.Cell
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.layout.*
class CodeCompletionConfigurable : BoundCompositeConfigurable<UnnamedConfigurable>(
ApplicationBundle.message("title.code.completion"), "reference.settingsdialog.IDE.editor.code.completion"),
EditorOptionsProvider, WithEpDependencies {
companion object {
const val ID = "editor.preferences.completion"
private val LOG = Logger.getInstance(CodeCompletionConfigurable::class.java)
}
private lateinit var cbMatchCase: JBCheckBox
private lateinit var rbLettersOnly: JBRadioButton
private lateinit var rbAllOnly: JBRadioButton
override fun createConfigurables(): List<UnnamedConfigurable> =
ConfigurableWrapper.createConfigurables(CodeCompletionConfigurableEP.EP_NAME)
override fun getId() = ID
override fun getDependencies(): Collection<BaseExtensionPointName<*>> =
listOf(CodeCompletionConfigurableEP.EP_NAME)
var caseSensitive: Int
get() =
if (cbMatchCase.isSelected) {
if (rbAllOnly.isSelected) CodeInsightSettings.ALL else CodeInsightSettings.FIRST_LETTER
}
else {
CodeInsightSettings.NONE
}
set(value) =
when (value) {
CodeInsightSettings.ALL -> {
cbMatchCase.isSelected = true
rbAllOnly.setSelected(true)
}
CodeInsightSettings.NONE -> {
cbMatchCase.isSelected = false
}
CodeInsightSettings.FIRST_LETTER -> {
cbMatchCase.isSelected = true
rbLettersOnly.setSelected(true)
}
else -> LOG.warn("Unsupported caseSensitive: $value")
}
override fun reset() {
super<BoundCompositeConfigurable>.reset()
val codeInsightSettings = CodeInsightSettings.getInstance()
caseSensitive = codeInsightSettings.completionCaseSensitive
}
override fun apply() {
super.apply()
val codeInsightSettings = CodeInsightSettings.getInstance()
codeInsightSettings.completionCaseSensitive = caseSensitive
for (project in ProjectManager.getInstance().openProjects) {
DaemonCodeAnalyzer.getInstance(project).settingsChanged()
}
}
override fun isModified(): Boolean {
val result = super<BoundCompositeConfigurable>.isModified()
val codeInsightSettings = CodeInsightSettings.getInstance()
return result || caseSensitive != codeInsightSettings.completionCaseSensitive
}
override fun createPanel(): DialogPanel {
val actionManager = ActionManager.getInstance()
val settings = CodeInsightSettings.getInstance()
return panel {
buttonsGroup {
row {
cbMatchCase = checkBox(ApplicationBundle.message("completion.option.match.case"))
.component
rbLettersOnly = radioButton(ApplicationBundle.message("completion.option.first.letter.only"))
.enabledIf(cbMatchCase.selected)
.component.apply { isSelected = true }
rbAllOnly = radioButton(ApplicationBundle.message("completion.option.all.letters"))
.enabledIf(cbMatchCase.selected)
.component
}
}
val codeCompletion = OptionsApplicabilityFilter.isApplicable(OptionId.AUTOCOMPLETE_ON_BASIC_CODE_COMPLETION)
val smartTypeCompletion = OptionsApplicabilityFilter.isApplicable(OptionId.COMPLETION_SMART_TYPE)
if (codeCompletion || smartTypeCompletion) {
buttonsGroup(ApplicationBundle.message("label.autocomplete.when.only.one.choice")) {
if (codeCompletion) {
row {
checkBox(ApplicationBundle.message("checkbox.autocomplete.basic"))
.bindSelected(settings::AUTOCOMPLETE_ON_CODE_COMPLETION)
.gap(RightGap.SMALL)
comment(KeymapUtil.getFirstKeyboardShortcutText(actionManager.getAction(IdeActions.ACTION_CODE_COMPLETION)))
}
}
if (smartTypeCompletion) {
row {
checkBox(ApplicationBundle.message("checkbox.autocomplete.smart.type"))
.bindSelected(settings::AUTOCOMPLETE_ON_SMART_TYPE_COMPLETION)
.gap(RightGap.SMALL)
comment(KeymapUtil.getFirstKeyboardShortcutText(actionManager.getAction(IdeActions.ACTION_SMART_TYPE_COMPLETION)))
}
}
}
}
row {
checkBox(ApplicationBundle.message("completion.option.sort.suggestions.alphabetically"))
.bindSelected(UISettings.getInstance()::sortLookupElementsLexicographically)
}
lateinit var cbAutocompletion: Cell<JBCheckBox>
row {
cbAutocompletion = checkBox(ApplicationBundle.message("editbox.auto.complete") +
if (PowerSaveMode.isEnabled()) LangBundle.message("label.not.available.in.power.save.mode") else "")
.bindSelected(settings::AUTO_POPUP_COMPLETION_LOOKUP)
}
indent {
row {
checkBox(IdeUICustomization.getInstance().selectAutopopupByCharsText)
.bindSelected(settings::isSelectAutopopupSuggestionsByChars, settings::setSelectAutopopupSuggestionsByChars)
.enabledIf(cbAutocompletion.selected)
}
}
row {
val cbAutopopupJavaDoc = checkBox(ApplicationBundle.message("editbox.autopopup.javadoc.in"))
.bindSelected(settings::AUTO_POPUP_JAVADOC_INFO)
.gap(RightGap.SMALL)
intTextField(CodeInsightSettings.JAVADOC_INFO_DELAY_RANGE.asRange(), 100)
.bindIntText(settings::JAVADOC_INFO_DELAY)
.columns(4)
.enabledIf(cbAutopopupJavaDoc.selected)
.gap(RightGap.SMALL)
label(ApplicationBundle.message("editbox.ms"))
}
addOptions()
group(ApplicationBundle.message("title.parameter.info")) {
if (OptionsApplicabilityFilter.isApplicable(OptionId.SHOW_PARAMETER_NAME_HINTS_ON_COMPLETION)) {
row {
checkBox(ApplicationBundle.message("editbox.complete.with.parameters"))
.bindSelected(settings::SHOW_PARAMETER_NAME_HINTS_ON_COMPLETION)
}
}
row {
val cbParameterInfoPopup = checkBox(ApplicationBundle.message("editbox.autopopup.in"))
.bindSelected(settings::AUTO_POPUP_PARAMETER_INFO)
.gap(RightGap.SMALL)
intTextField(CodeInsightSettings.PARAMETER_INFO_DELAY_RANGE.asRange(), 100)
.bindIntText(settings::PARAMETER_INFO_DELAY)
.columns(4)
.enabledIf(cbParameterInfoPopup.selected)
.gap(RightGap.SMALL)
label(ApplicationBundle.message("editbox.ms"))
}
row {
checkBox(ApplicationBundle.message("checkbox.show.full.signatures"))
.bindSelected(settings::SHOW_FULL_SIGNATURES_IN_PARAMETER_INFO)
}
}
addSections()
}
}
private fun Panel.addOptions() {
configurables.filter { it !is CodeCompletionOptionsCustomSection }
.forEach { appendDslConfigurable(it) }
}
private fun Panel.addSections() {
configurables.filterIsInstance<CodeCompletionOptionsCustomSection>()
.sortedWith(Comparator.comparing { c ->
(c as? Configurable)?.displayName ?: ""
})
.forEach { appendDslConfigurable(it) }
}
} | platform/lang-impl/src/com/intellij/application/options/CodeCompletionConfigurable.kt | 680760436 |
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.backend.konan
import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.GroupingMessageCollector
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.konan.CompilerVersion
import org.jetbrains.kotlin.konan.file.File
import org.jetbrains.kotlin.konan.library.defaultResolver
import org.jetbrains.kotlin.konan.parseCompilerVersion
import org.jetbrains.kotlin.konan.target.Distribution
import org.jetbrains.kotlin.konan.target.KonanTarget
import org.jetbrains.kotlin.library.UnresolvedLibrary
import org.jetbrains.kotlin.library.resolver.impl.libraryResolver
import org.jetbrains.kotlin.library.toUnresolvedLibraries
import org.jetbrains.kotlin.util.Logger
import kotlin.system.exitProcess
class KonanLibrariesResolveSupport(
configuration: CompilerConfiguration,
target: KonanTarget,
distribution: Distribution
) {
private val includedLibraryFiles =
configuration.getList(KonanConfigKeys.INCLUDED_LIBRARIES).map { File(it) }
private val librariesToCacheFiles =
configuration.getList(KonanConfigKeys.LIBRARIES_TO_CACHE).map { File(it) } +
configuration.get(KonanConfigKeys.LIBRARY_TO_ADD_TO_CACHE).let {
if (it.isNullOrEmpty()) emptyList() else listOf(File(it))
}
private val libraryNames = configuration.getList(KonanConfigKeys.LIBRARY_FILES)
private val unresolvedLibraries = libraryNames.toUnresolvedLibraries
private val repositories = configuration.getList(KonanConfigKeys.REPOSITORIES)
private val resolverLogger =
object : Logger {
private val collector = configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY)
override fun warning(message: String)= collector.report(CompilerMessageSeverity.STRONG_WARNING, message)
override fun error(message: String) = collector.report(CompilerMessageSeverity.ERROR, message)
override fun log(message: String) = collector.report(CompilerMessageSeverity.LOGGING, message)
override fun fatal(message: String): Nothing {
collector.report(CompilerMessageSeverity.ERROR, message)
(collector as? GroupingMessageCollector)?.flush()
exitProcess(1)
}
}
private val resolver = defaultResolver(
repositories,
libraryNames.filter { it.contains(File.separator) },
target,
distribution,
resolverLogger
).libraryResolver()
// We pass included libraries by absolute paths to avoid repository-based resolution for them.
// Strictly speaking such "direct" libraries should be specially handled by the resolver, not by KonanConfig.
// But currently the resolver is in the middle of a complex refactoring so it was decided to avoid changes in its logic.
// TODO: Handle included libraries in KonanLibraryResolver when it's refactored and moved into the big Kotlin repo.
internal val resolvedLibraries = run {
val additionalLibraryFiles = includedLibraryFiles + librariesToCacheFiles
resolver.resolveWithDependencies(
unresolvedLibraries + additionalLibraryFiles.map { UnresolvedLibrary(it.absolutePath, null) },
noStdLib = configuration.getBoolean(KonanConfigKeys.NOSTDLIB),
noDefaultLibs = configuration.getBoolean(KonanConfigKeys.NODEFAULTLIBS),
noEndorsedLibs = configuration.getBoolean(KonanConfigKeys.NOENDORSEDLIBS)
)
}
internal val exportedLibraries =
getExportedLibraries(configuration, resolvedLibraries, resolver.searchPathResolver, report = true)
internal val coveredLibraries =
getCoveredLibraries(configuration, resolvedLibraries, resolver.searchPathResolver)
internal val includedLibraries =
getIncludedLibraries(includedLibraryFiles, configuration, resolvedLibraries)
} | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/KonanLibrariesResolveSupport.kt | 3087906955 |
// 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.refactoring.memberInfo
import com.intellij.openapi.util.NlsSafe
import com.intellij.refactoring.classMembers.DependencyMemberInfoModel
import com.intellij.refactoring.classMembers.MemberInfoBase
import com.intellij.refactoring.classMembers.MemberInfoModel
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.utils.ifEmpty
class KotlinInterfaceDependencyMemberInfoModel<T : KtNamedDeclaration, M : MemberInfoBase<T>>(
aClass: KtClassOrObject
) : DependencyMemberInfoModel<T, M>(KotlinInterfaceMemberDependencyGraph<T, M>(aClass), MemberInfoModel.WARNING) {
init {
setTooltipProvider { memberInfo ->
val dependencies = myMemberDependencyGraph.getDependenciesOf(memberInfo.member).ifEmpty { return@setTooltipProvider null }
@NlsSafe
val text = buildString {
append(KotlinBundle.message("interface.member.dependency.required.by.interfaces", dependencies.size))
append(" ")
dependencies.joinTo(this) { it.name ?: "" }
}
text
}
}
override fun isCheckedWhenDisabled(member: M) = false
override fun isFixedAbstract(member: M) = null
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinInterfaceDependencyMemberInfoModel.kt | 1386909139 |
// "Create enum constant 'A'" "true"
package p
fun foo() = X.<caret>A
enum class X {
} | plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createClass/referenceExpression/enumEntryWithEnumQualifier.kt | 2211187941 |
// IS_APPLICABLE: false
object Test {
const val foo = <caret>"""foo
bar
baz"""
} | plugins/kotlin/idea/tests/testData/intentions/indentRawString/const.kt | 1271738230 |
// 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.codeInliner
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.util.containers.stopAfter
import org.jetbrains.kotlin.idea.util.isLineBreak
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtReturnExpression
import org.jetbrains.kotlin.psi.psiUtil.children
import org.jetbrains.kotlin.psi.psiUtil.nextLeaf
import org.jetbrains.kotlin.psi.psiUtil.prevLeaf
class CommentHolder(val leadingComments: List<CommentNode>, val trailingComments: List<CommentNode>) {
fun restoreComments(element: PsiElement) {
val factory = KtPsiFactory(element)
for (leadingComment in leadingComments) {
addComment(factory, leadingComment, element, true)
}
for (trailingComment in trailingComments.asReversed()) {
addComment(factory, trailingComment, element, false)
}
}
fun merge(other: CommentHolder): CommentHolder = CommentHolder(
other.leadingComments + this.leadingComments,
this.trailingComments + other.trailingComments
)
val isEmpty: Boolean get() = leadingComments.isEmpty() && trailingComments.isEmpty()
class CommentNode(val indentBefore: String, val comment: String, val indentAfter: String) {
companion object {
fun create(comment: PsiComment): CommentNode = CommentNode(indentBefore(comment), comment.text, indentAfter(comment))
fun PsiElement.mergeComments(commentHolder: CommentHolder) {
val oldHolder = getCopyableUserData(COMMENTS_TO_RESTORE_KEY)
val newCommentHolder = oldHolder?.merge(commentHolder) ?: commentHolder
putCopyableUserData(COMMENTS_TO_RESTORE_KEY, newCommentHolder)
}
}
}
companion object {
val COMMENTS_TO_RESTORE_KEY: Key<CommentHolder> = Key("COMMENTS_TO_RESTORE")
fun extract(blockExpression: KtBlockExpression): Sequence<CommentHolder> = sequence {
val children = blockExpression.children().mapNotNull { it.psi }.iterator()
while (children.hasNext()) {
val before = children.stopAfter { it is KtExpression }.asSequence().collectComments()
val after = children.stopAfter { it.isLineBreak() || it is KtExpression }.asSequence().collectComments()
yield(CommentHolder(before, after))
}
}
fun Sequence<PsiElement>.collectComments(): List<CommentNode> = this.filterIsInstance<PsiComment>()
.map { CommentNode.create(it) }
.toList()
}
}
private fun indentBefore(comment: PsiComment): String {
val prevWhiteSpace = comment.prevLeaf() as? PsiWhiteSpace ?: return ""
val whiteSpaceText = prevWhiteSpace.text
if (prevWhiteSpace.prevSibling is PsiComment) return whiteSpaceText
val indexOfLineBreak = whiteSpaceText.indexOfLast { StringUtil.isLineBreak(it) }
if (indexOfLineBreak == -1) return whiteSpaceText
val startIndex = indexOfLineBreak + 1
if (startIndex >= whiteSpaceText.length) return ""
return whiteSpaceText.substring(startIndex)
}
private fun indentAfter(comment: PsiComment): String {
val nextWhiteSpace = comment.nextLeaf() as? PsiWhiteSpace ?: return ""
if (nextWhiteSpace.nextSibling is PsiComment) return ""
val whiteSpaceText = nextWhiteSpace.text
val indexOfLineBreak = whiteSpaceText.indexOfFirst { StringUtil.isLineBreak(it) }
if (indexOfLineBreak == -1) return whiteSpaceText
val endIndex = indexOfLineBreak + 1
if (endIndex > whiteSpaceText.length) return whiteSpaceText
return whiteSpaceText.substring(0, endIndex)
}
private fun addSiblingFunction(before: Boolean): (PsiElement, PsiElement, PsiElement) -> PsiElement = if (before)
PsiElement::addBefore
else
PsiElement::addAfter
private fun PsiElement.addWhiteSpace(factory: KtPsiFactory, whiteSpaceText: String, before: Boolean) {
if (whiteSpaceText.isEmpty()) return
val siblingWhiteSpace = (if (before) prevLeaf() else nextLeaf()) as? PsiWhiteSpace
if (siblingWhiteSpace == null) {
addSiblingFunction(before)(parent, factory.createWhiteSpace(whiteSpaceText), this)
} else {
val siblingText = siblingWhiteSpace.text
val containsLineBreak = StringUtil.containsLineBreak(siblingText) && StringUtil.containsLineBreak(whiteSpaceText)
val newWhiteSpaceText = if (before) {
if (containsLineBreak) whiteSpaceText
else siblingText + whiteSpaceText
} else {
if (containsLineBreak) return
whiteSpaceText + siblingText
}
siblingWhiteSpace.replace(factory.createWhiteSpace(newWhiteSpaceText))
}
}
private fun addComment(factory: KtPsiFactory, commentNode: CommentHolder.CommentNode, target: PsiElement, before: Boolean) {
val parent = target.parent
val comment = factory.createComment(commentNode.comment)
addSiblingFunction(before && parent !is KtReturnExpression)(parent, comment, target).updateWhiteSpaces(factory, commentNode)
}
private fun PsiElement.updateWhiteSpaces(factory: KtPsiFactory, commentNode: CommentHolder.CommentNode) {
addWhiteSpace(factory, commentNode.indentBefore, before = true)
addWhiteSpace(factory, commentNode.indentAfter, before = false)
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInliner/CommentHolder.kt | 19405299 |
package com.psenchanka.comant.auth
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.ResponseStatus
@ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "Bad credentials")
class BadCredentialsException : RuntimeException() | comant-site/src/main/kotlin/com/psenchanka/comant/auth/BadCredentialsException.kt | 723695179 |
// 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.project
import com.intellij.ide.impl.OpenProjectTask
import com.intellij.ide.startup.StartupManagerEx
import com.intellij.openapi.application.AccessToken
import com.intellij.openapi.command.impl.DummyProject
import com.intellij.openapi.command.impl.UndoManagerImpl
import com.intellij.openapi.command.undo.UndoManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ex.ProjectEx
import com.intellij.openapi.project.impl.ProjectExImpl
import com.intellij.openapi.project.impl.ProjectImpl
import com.intellij.openapi.project.impl.ProjectManagerExImpl
import com.intellij.project.TestProjectManager.Companion.getCreationPlace
import com.intellij.testFramework.LeakHunter
import com.intellij.testFramework.publishHeapDump
import com.intellij.util.containers.UnsafeWeakList
import com.intellij.util.ref.GCUtil
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.NotNull
import java.nio.file.Path
import java.util.*
import java.util.concurrent.TimeUnit
private const val MAX_LEAKY_PROJECTS = 5
private val LEAK_CHECK_INTERVAL = TimeUnit.MINUTES.toMillis(30)
private var CHECK_START = System.currentTimeMillis()
private val LOG_PROJECT_LEAKAGE = System.getProperty("idea.log.leaked.projects.in.tests", "true")!!.toBoolean()
var totalCreatedProjectsCount = 0
@ApiStatus.Internal
open class TestProjectManager : ProjectManagerExImpl() {
companion object {
@JvmStatic
fun getInstanceExIfCreated(): TestProjectManager? {
return ProjectManager.getInstanceIfCreated() as TestProjectManager?
}
@JvmStatic
fun getCreationPlace(project: Project): String {
return "$project ${(if (project is ProjectEx) project.creationTrace else null) ?: ""}"
}
}
var totalCreatedProjectCount = 0
private set
private val projects = WeakHashMap<Project, String>()
@Volatile
private var isTracking = false
private val trackingProjects = UnsafeWeakList<Project>()
override fun newProject(projectFile: Path, options: OpenProjectTask): Project? {
checkProjectLeaksInTests()
val project = super.newProject(projectFile, options)
if (project != null && LOG_PROJECT_LEAKAGE) {
projects.put(project, null)
}
return project
}
override fun handleErrorOnNewProject(t: Throwable) {
throw t
}
override fun openProject(project: Project): Boolean {
if (project is ProjectExImpl && project.isLight) {
project.setTemporarilyDisposed(false)
val isInitialized = StartupManagerEx.getInstanceEx(project).startupActivityPassed()
if (isInitialized) {
addToOpened(project)
// events already fired
return true
}
}
return super.openProject(project)
}
// method is not used and will be deprecated soon but still have to ensure that every created Project instance is tracked
override fun loadProject(file: Path): Project {
val project = super.loadProject(file)
trackProject(project)
return project
}
private fun trackProject(project: @NotNull Project) {
if (isTracking) {
synchronized(this) {
if (isTracking) {
trackingProjects.add(project)
}
}
}
}
override fun instantiateProject(projectStoreBaseDir: Path, options: OpenProjectTask): ProjectImpl {
val project = super.instantiateProject(projectStoreBaseDir, options)
totalCreatedProjectCount++
trackProject(project)
return project
}
override fun closeProject(project: Project, saveProject: Boolean, dispose: Boolean, checkCanClose: Boolean): Boolean {
if (isTracking) {
synchronized(this) {
if (isTracking) {
trackingProjects.remove(project)
}
}
}
val result = super.closeProject(project, saveProject, dispose, checkCanClose)
val undoManager = UndoManager.getGlobalInstance() as UndoManagerImpl
// test may use WrapInCommand (it is ok - in this case HeavyPlatformTestCase will call dropHistoryInTests)
if (!undoManager.isInsideCommand) {
undoManager.dropHistoryInTests()
}
return result
}
/**
* Start tracking of created projects. Call [AccessToken.finish] to stop tracking and assert that no leaked projects.
*/
@Synchronized
fun startTracking(): AccessToken {
if (isTracking) {
throw IllegalStateException("Tracking is already started")
}
return object : AccessToken() {
override fun finish() {
synchronized(this@TestProjectManager) {
isTracking = false
var error: StringBuilder? = null
for (project in trackingProjects) {
if (error == null) {
error = StringBuilder()
}
error.append(project.toString())
error.append("\nCreation trace: ")
error.append((project as ProjectEx).creationTrace)
}
trackingProjects.clear()
if (error != null) {
throw IllegalStateException(error.toString())
}
}
}
}
}
private fun getLeakedProjectCount() = getLeakedProjects().count()
private fun getLeakedProjects(): Sequence<Project> {
// process queue
projects.remove(DummyProject.getInstance())
return projects.keys.asSequence()
}
private fun checkProjectLeaksInTests() {
if (!LOG_PROJECT_LEAKAGE || getLeakedProjectCount() < MAX_LEAKY_PROJECTS) {
return
}
val currentTime = System.currentTimeMillis()
if ((currentTime - CHECK_START) < LEAK_CHECK_INTERVAL) {
// check every N minutes
return
}
var i = 0
while (i < 3 && getLeakedProjectCount() >= MAX_LEAKY_PROJECTS) {
GCUtil.tryGcSoftlyReachableObjects()
i++
}
CHECK_START = currentTime
if (getLeakedProjectCount() >= MAX_LEAKY_PROJECTS) {
System.gc()
val copy = getLeakedProjects().toCollection(UnsafeWeakList())
projects.clear()
if (copy.iterator().asSequence().count() >= MAX_LEAKY_PROJECTS) {
reportLeakedProjects(copy)
throw AssertionError("Too many projects leaked, again.")
}
}
}
override fun isRunStartUpActivitiesEnabled(project: Project): Boolean {
val runStartUpActivitiesFlag = project.getUserData(ProjectExImpl.RUN_START_UP_ACTIVITIES)
return runStartUpActivitiesFlag == null || runStartUpActivitiesFlag
}
}
private fun reportLeakedProjects(leakedProjects: Iterable<Project>) {
val hashCodes = HashSet<Int>()
for (project in leakedProjects) {
hashCodes.add(System.identityHashCode(project))
}
val dumpPath = publishHeapDump("leakedProjects")
val leakers = StringBuilder()
leakers.append("Too many projects leaked (hashCodes=$hashCodes): \n")
LeakHunter.processLeaks(LeakHunter.allRoots(), ProjectImpl::class.java,
{ hashCodes.contains(System.identityHashCode(it)) },
{ leaked: ProjectImpl?, backLink: Any? ->
val hashCode = System.identityHashCode(leaked)
leakers.append("Leaked project found:").append(leaked)
.append(", hash=").append(hashCode)
.append(", place=").append(getCreationPlace(leaked!!)).append('\n')
.append(backLink).append('\n')
.append("-----\n")
hashCodes.remove(hashCode)
!hashCodes.isEmpty()
})
leakers.append("\nPlease see `").append(dumpPath).append("` for a memory dump")
throw AssertionError(leakers.toString())
} | platform/testFramework/src/com/intellij/project/TestProjectManager.kt | 3075183746 |
package Kotlin101.Ranges
fun main(args : Array<String>){
for (i in 1..10)
print("$i,")
println("")
for (i in 'A'..'z')
print("$i,")
} | src/Ranges.kt | 1762952981 |
package bj.vinylbrowser.model.order
import com.google.gson.annotations.SerializedName
/**
* Created by Josh Laird on 19/05/2017.
*/
data class Actor(val username: String, @SerializedName("resource_url") val resourceUrl: String) | app/src/main/java/bj/vinylbrowser/model/order/Actor.kt | 2759378838 |
/**
* Extension method to remove the required boilerplate for running code after a view has been
* inflated and measured.
*
* @author Antonio Leiva
* @see <a href="https://antonioleiva.com/kotlin-ongloballayoutlistener/>Kotlin recipes: OnGlobalLayoutListener</a>
*/
inline fun <T : View> T.afterMeasured(crossinline f: T.() -> Unit) {
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
if (measuredWidth > 0 && measuredHeight > 0) {
viewTreeObserver.removeOnGlobalLayoutListener(this)
f()
}
}
})
}
/**
* Extension method to simplify the code needed to apply spans on a specific sub string.
*/
inline fun SpannableStringBuilder.withSpan(vararg spans: Any, action: SpannableStringBuilder.() -> Unit):
SpannableStringBuilder {
val from = length
action()
for (span in spans) {
setSpan(span, from, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
return this
}
/**
* Extension method to provide simpler access to {@link ContextCompat#getColor(int)}.
*/
fun Context.getColorCompat(color: Int) = ContextCompat.getColor(this, color)
/**
* Extension method to provide simpler access to {@link View#getResources()#getString(int)}.
*/
fun View.getString(stringResId: Int): String = resources.getString(stringResId)
/**
* Extension method to provide show keyboard for View.
*/
fun View.showKeyboard() {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
this.requestFocus()
imm.showSoftInput(this, 0)
}
/**
* Extension method to provide hide keyboard for [Activity].
*/
fun Activity.hideSoftKeyboard() {
if (currentFocus != null) {
val inputMethodManager = getSystemService(Context
.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(currentFocus!!.windowToken, 0)
}
}
/**
* Extension method to provide hide keyboard for [Fragment].
*/
fun Fragment.hideSoftKeyboard() {
activity?.hideSoftKeyboard()
}
/**
* Extension method to provide hide keyboard for [View].
*/
fun View.hideKeyboard() {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(windowToken, 0)
}
/**
* Extension method to int time to 2 digit String
*/
fun Int.twoDigitTime() = if (this < 10) "0" + toString() else toString()
/**
* Extension method to provide quicker access to the [LayoutInflater] from [Context].
*/
fun Context.getLayoutInflater() = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
/**
* Extension method to provide quicker access to the [LayoutInflater] from a [View].
*/
fun View.getLayoutInflater() = context.getLayoutInflater()
/**
* Extension method to replace all text inside an [Editable] with the specified [newValue].
*/
fun Editable.replaceAll(newValue: String) {
replace(0, length, newValue)
}
/**
* Extension method to replace all text inside an [Editable] with the specified [newValue] while
* ignoring any [android.text.InputFilter] set on the [Editable].
*/
fun Editable.replaceAllIgnoreFilters(newValue: String) {
val currentFilters = filters
filters = emptyArray()
replaceAll(newValue)
filters = currentFilters
}
/**
* Extension method to cast a char with a decimal value to an [Int].
*/
fun Char.decimalValue(): Int {
if (!isDigit())
throw IllegalArgumentException("Out of range")
return this.toInt() - '0'.toInt()
}
/**
* Extension method to simplify view binding.
*/
fun <T : ViewDataBinding> View.bind() = DataBindingUtil.bind<T>(this) as T
/**
* Extension method to simplify view inflating and binding inside a [ViewGroup].
*
* e.g.
* This:
*<code>
* binding = bind(R.layout.widget_card)
*</code>
*
* Will replace this:
*<code>
* binding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.widget_card, this, true)
*</code>
*/
fun <T : ViewDataBinding> ViewGroup.bind(layoutId: Int): T {
return DataBindingUtil.inflate(getLayoutInflater(), layoutId, this, true)
}
/**
* Extension method to get Date for String with specified format.
*/
fun String.dateInFormat(format: String): Date? {
val dateFormat = SimpleDateFormat(format, Locale.US)
var parsedDate: Date? = null
try {
parsedDate = dateFormat.parse(this)
} catch (ignored: ParseException) {
ignored.printStackTrace()
}
return parsedDate
}
/**
* Convert a given date to milliseconds
*/
fun Date.toMillis() : Long {
val calendar = Calendar.getInstance()
calendar.time = this
return calendar.timeInMillis
}
/**
* Checks if dates are same
*/
fun Date.isSame(to : Date) : Boolean {
val sdf = SimpleDateFormat("yyyMMdd", Locale.getDefault())
return sdf.format(this) == sdf.format(to)
}
/**
* Extension method to get ClickableSpan.
* e.g.
* val loginLink = getClickableSpan(context.getColorCompat(R.color.colorAccent), { })
*/
fun getClickableSpan(color: Int, action: (view: View) -> Unit): ClickableSpan {
return object : ClickableSpan() {
override fun onClick(view: View) {
action
}
override fun updateDrawState(ds: TextPaint) {
super.updateDrawState(ds)
ds.color = color
}
}
}
| Extensions.kt | 3917155404 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.