repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Heiner1/AndroidAPS
|
omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/LTKExchanger.kt
|
1
|
5871
|
package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.pair
import info.nightscout.androidaps.extensions.hexStringToByteArray
import info.nightscout.androidaps.extensions.toHex
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.Ids
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.MessageIOException
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.PairingException
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessageIO
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessagePacket
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessageSendSuccess
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.StringLengthPrefixEncoding.Companion.parseKeys
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.RandomByteGenerator
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.X25519KeyGenerator
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
internal class LTKExchanger(
private val aapsLogger: AAPSLogger,
private val msgIO: MessageIO,
private val ids: Ids,
) {
private val podAddress = Ids.notActivated()
private val keyExchange = KeyExchange(aapsLogger, X25519KeyGenerator(), RandomByteGenerator())
private var seq: Byte = 1
@Throws(PairingException::class)
fun negotiateLTK(): PairResult {
val sp1sp2 = PairMessage(
sequenceNumber = seq,
source = ids.myId,
destination = podAddress,
keys = arrayOf(SP1, SP2),
payloads = arrayOf(ids.podId.address, sp2())
)
throwOnSendError(sp1sp2.messagePacket, SP1 + SP2)
seq++
val sps1 = PairMessage(
sequenceNumber = seq,
source = ids.myId,
destination = podAddress,
keys = arrayOf(SPS1),
payloads = arrayOf(keyExchange.pdmPublic + keyExchange.pdmNonce)
)
throwOnSendError(sps1.messagePacket, SPS1)
val podSps1 = msgIO.receiveMessage() ?: throw PairingException("Could not read SPS1")
processSps1FromPod(podSps1)
// now we have all the data to generate: confPod, confPdm, ltk and noncePrefix
seq++
val sps2 = PairMessage(
sequenceNumber = seq,
source = ids.myId,
destination = podAddress,
keys = arrayOf(SPS2),
payloads = arrayOf(keyExchange.pdmConf)
)
throwOnSendError(sps2.messagePacket, SPS2)
val podSps2 = msgIO.receiveMessage() ?: throw PairingException("Could not read SPS2")
validatePodSps2(podSps2)
// No exception throwing after this point. It is possible that the pod saved the LTK
seq++
// send SP0GP0
val sp0gp0 = PairMessage(
sequenceNumber = seq,
source = ids.myId,
destination = podAddress,
keys = arrayOf(SP0GP0),
payloads = arrayOf(ByteArray(0))
)
val result = msgIO.sendMessage(sp0gp0.messagePacket)
if (result !is MessageSendSuccess) {
aapsLogger.warn(LTag.PUMPBTCOMM, "Error sending SP0GP0: $result")
}
msgIO.receiveMessage()
?.let { validateP0(it) }
?: aapsLogger.warn(LTag.PUMPBTCOMM, "Could not read P0")
return PairResult(
ltk = keyExchange.ltk,
msgSeq = seq
)
}
@Throws(PairingException::class)
private fun throwOnSendError(msg: MessagePacket, msgType: String) {
val result = msgIO.sendMessage(msg)
if (result !is MessageSendSuccess) {
throw PairingException("Could not send or confirm $msgType: $result")
}
}
private fun processSps1FromPod(msg: MessagePacket) {
aapsLogger.debug(LTag.PUMPBTCOMM, "Received SPS1 from pod: ${msg.payload.toHex()}")
val payload = parseKeys(arrayOf(SPS1), msg.payload)[0]
keyExchange.updatePodPublicData(payload)
}
private fun validatePodSps2(msg: MessagePacket) {
aapsLogger.debug(LTag.PUMPBTCOMM, "Received SPS2 from pod: ${msg.payload.toHex()}")
val payload = parseKeys(arrayOf(SPS2), msg.payload)[0]
aapsLogger.debug(LTag.PUMPBTCOMM, "SPS2 payload from pod: ${payload.toHex()}")
if (payload.size != KeyExchange.CMAC_SIZE) {
throw MessageIOException("Invalid payload size")
}
keyExchange.validatePodConf(payload)
}
private fun sp2(): ByteArray {
// This is GetPodStatus command, with page 0 parameter.
// We could replace that in the future with the serialized GetPodStatus()
return GET_POD_STATUS_HEX_COMMAND.hexStringToByteArray()
}
private fun validateP0(msg: MessagePacket) {
aapsLogger.debug(LTag.PUMPBTCOMM, "Received P0 from pod: ${msg.payload.toHex()}")
val payload = parseKeys(arrayOf(P0), msg.payload)[0]
aapsLogger.debug(LTag.PUMPBTCOMM, "P0 payload from pod: ${payload.toHex()}")
if (!payload.contentEquals(UNKNOWN_P0_PAYLOAD)) {
aapsLogger.warn(LTag.PUMPBTCOMM, "Received invalid P0 payload: ${payload.toHex()}")
}
}
companion object {
private const val GET_POD_STATUS_HEX_COMMAND =
"ffc32dbd08030e0100008a"
// This is the binary representation of "GetPodStatus command"
private const val SP1 = "SP1="
private const val SP2 = ",SP2="
private const val SPS1 = "SPS1="
private const val SPS2 = "SPS2="
private const val SP0GP0 = "SP0,GP0"
private const val P0 = "P0="
private val UNKNOWN_P0_PAYLOAD = byteArrayOf(0xa5.toByte())
}
}
|
agpl-3.0
|
9ac74c2350404054205de31d382b73c6
| 39.212329 | 126 | 0.669392 | 4.111345 | false | false | false | false |
square/wire
|
wire-library/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Type.kt
|
1
|
3545
|
/*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire.schema
import com.squareup.wire.Syntax
import com.squareup.wire.schema.EnumType.Companion.fromElement
import com.squareup.wire.schema.MessageType.Companion.fromElement
import com.squareup.wire.schema.internal.parser.EnumElement
import com.squareup.wire.schema.internal.parser.MessageElement
import com.squareup.wire.schema.internal.parser.TypeElement
import kotlin.jvm.JvmStatic
sealed class Type {
abstract val location: Location
abstract val type: ProtoType
abstract val name: String
abstract val documentation: String
abstract val options: Options
abstract val nestedTypes: List<Type>
abstract val nestedExtendList: List<Extend>
abstract val syntax: Syntax
abstract fun linkMembers(linker: Linker)
abstract fun linkOptions(linker: Linker, syntaxRules: SyntaxRules, validate: Boolean)
abstract fun validate(linker: Linker, syntaxRules: SyntaxRules)
abstract fun retainAll(schema: Schema, markSet: MarkSet): Type?
/**
* Returns a copy of this containing only the types in [linkedTypes] and extensions in [linkedFields],
* or null if that set is empty. This will return an [EnclosingType] if it is itself not linked, but
* its nested types are linked.
*
* The returned type is a shadow of its former self. It it useful for linking against, but lacks
* most of the members of the original type.
*/
abstract fun retainLinked(linkedTypes: Set<ProtoType>, linkedFields: Set<Field>): Type?
/**
* Returns all types and subtypes which are linked to the type.
*/
fun typesAndNestedTypes(): List<Type> {
val typesAndNestedTypes = mutableListOf<Type>()
typesAndNestedTypes.add(this)
for (type in nestedTypes) {
typesAndNestedTypes.addAll(type.typesAndNestedTypes())
}
return typesAndNestedTypes
}
companion object {
fun get(namespaces: List<String>, protoType: ProtoType, type: TypeElement, syntax: Syntax): Type {
return when (type) {
is EnumElement -> fromElement(protoType, type, syntax)
is MessageElement -> fromElement(namespaces, protoType, type, syntax)
else -> throw IllegalArgumentException("unexpected type: $type")
}
}
@JvmStatic
fun fromElements(
packageName: String?,
elements: List<TypeElement>,
syntax: Syntax
) = elements.map {
val protoType = ProtoType.get(packageName, it.name)
val namespaces = when {
packageName == null -> listOf()
else -> listOf(packageName)
}
return@map get(namespaces, protoType, it, syntax)
}
private fun toElement(type: Type): TypeElement {
return when (type) {
is EnumType -> type.toElement()
is MessageType -> type.toElement()
is EnclosingType -> type.toElement()
else -> throw IllegalArgumentException("unexpected type: $type")
}
}
@JvmStatic
fun toElements(types: List<Type>) = types.map { toElement(it) }
}
}
|
apache-2.0
|
81de2d0333d97b2db28018c7631edca9
| 35.546392 | 104 | 0.715374 | 4.23031 | false | false | false | false |
Maccimo/intellij-community
|
tools/intellij.ide.starter/src/com/intellij/ide/starter/system/SystemInfo.kt
|
3
|
1301
|
package com.intellij.ide.starter.system
import java.util.*
object SystemInfo {
val OS_NAME: String = System.getProperty("os.name")
val OS_VERSION = System.getProperty("os.version").lowercase()
val OS_ARCH: String = System.getProperty("os.arch")
val JAVA_VERSION: String = System.getProperty("java.version")
val JAVA_RUNTIME_VERSION = getRtVersion(JAVA_VERSION)
val JAVA_VENDOR: String = System.getProperty("java.vm.vendor", "Unknown")
private val OS_NAME_LOWERCASED = OS_NAME.lowercase(Locale.ENGLISH)
val isWindows = OS_NAME_LOWERCASED.startsWith("windows")
val isMac = OS_NAME_LOWERCASED.startsWith("mac")
val isLinux = OS_NAME_LOWERCASED.startsWith("linux")
val isFreeBSD = OS_NAME_LOWERCASED.startsWith("freebsd")
val isSolaris = OS_NAME_LOWERCASED.startsWith("sunos")
val isUnix = !isWindows
val isXWindow = isUnix && !isMac
private fun getRtVersion(fallback: String): String? {
val rtVersion = System.getProperty("java.runtime.version")
return if (Character.isDigit(rtVersion[0])) rtVersion else fallback
}
fun getOsNameAndVersion(): String = (if (isMac) "macOS" else OS_NAME) + ' ' + OS_VERSION
fun getOsType(): OsType = when {
isMac -> OsType.MacOS
isWindows -> OsType.Windows
isLinux -> OsType.Linux
else -> OsType.Other
}
}
|
apache-2.0
|
aa074e387210ddca45246a825242cac0
| 36.2 | 90 | 0.719447 | 3.644258 | false | false | false | false |
wordpress-mobile/WordPress-Android
|
WordPress/src/main/java/org/wordpress/android/ui/posts/AuthorFilterSelection.kt
|
1
|
366
|
package org.wordpress.android.ui.posts
enum class AuthorFilterSelection(val id: Long) {
ME(id = 0), EVERYONE(id = 1);
companion object {
@JvmStatic
val defaultValue = EVERYONE
@JvmStatic
fun fromId(id: Long): AuthorFilterSelection {
return values().firstOrNull { it.id == id } ?: defaultValue
}
}
}
|
gpl-2.0
|
63f7daac11057a4b2b13075f5c26e19a
| 23.4 | 71 | 0.603825 | 4.305882 | false | false | false | false |
wordpress-mobile/WordPress-Android
|
WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/sections/viewholders/ValueViewHolder.kt
|
1
|
2209
|
package org.wordpress.android.ui.stats.refresh.lists.sections.viewholders
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.content.res.AppCompatResources
import androidx.recyclerview.widget.RecyclerView.LayoutParams
import org.wordpress.android.R
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ValueItem
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ValueItem.State.NEGATIVE
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ValueItem.State.NEUTRAL
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ValueItem.State.POSITIVE
import org.wordpress.android.util.extensions.getColorResIdFromAttribute
class ValueViewHolder(parent: ViewGroup) : BlockListItemViewHolder(
parent,
R.layout.stats_block_value_item
) {
private val container = itemView.findViewById<LinearLayout>(R.id.value_container)
private val value = itemView.findViewById<TextView>(R.id.value)
private val unit = itemView.findViewById<TextView>(R.id.unit)
private val change = itemView.findViewById<TextView>(R.id.change)
fun bind(item: ValueItem) {
value.text = item.value
unit.setText(item.unit)
val hasChange = item.change != null
val color = when (item.state) {
POSITIVE -> change.context.getColorResIdFromAttribute(R.attr.wpColorSuccess)
NEGATIVE -> change.context.getColorResIdFromAttribute(R.attr.wpColorError)
NEUTRAL -> change.context.getColorResIdFromAttribute(R.attr.wpColorOnSurfaceMedium)
}
change.setTextColor(AppCompatResources.getColorStateList(change.context, color))
change.visibility = if (hasChange) View.VISIBLE else View.GONE
change.text = item.change
val params = container.layoutParams as LayoutParams
val topMargin = if (item.isFirst) container.resources.getDimensionPixelSize(R.dimen.margin_medium) else 0
params.setMargins(0, topMargin, 0, 0)
container.layoutParams = params
container.contentDescription = item.contentDescription
}
}
|
gpl-2.0
|
64503f9061632894ca86ccb0de20ab05
| 50.372093 | 113 | 0.767316 | 4.281008 | false | false | false | false |
byu-oit/android-byu-suite-v2
|
support/src/main/java/edu/byu/support/retrofit/ByuClient.kt
|
2
|
1154
|
package edu.byu.support.retrofit
import android.content.Context
import okhttp3.OkHttpClient
import retrofit2.Converter
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
/**
* Created by geogor37 on 7/3/18
* This class handles sending requests and receiving responses from the various web services that provide data for the app. If a web service returns errors in a specific format, be sure to
* include a companion object containing a PATH_TO_READABLE_ERROR value that can be used by the ByuCallback for parsing the error response.
*/
abstract class ByuClient<Api> {
protected abstract val baseUrl: String
protected open val timeOut = OkHttpClient().connectTimeoutMillis() / 1000
protected open fun getAuthType() = ByuApiGenerator.AuthType.BEARER_TOKEN
protected open fun getConverter(): Converter.Factory = GsonConverterFactory.create()
protected abstract fun getApiInterface(): Class<Api>
protected fun getBuilder(): OkHttpClient.Builder = OkHttpClient.Builder().connectTimeout(timeOut.toLong(), TimeUnit.SECONDS)
fun getApi(context: Context?): Api = ByuApiGenerator.createApi(context, this)
}
|
apache-2.0
|
1ecd268497b1e5958c5e95de1bad5d3a
| 41.740741 | 188 | 0.802426 | 4.472868 | false | false | false | false |
OnyxDevTools/onyx-database-parent
|
onyx-database/src/main/kotlin/com/onyx/lang/map/LastRecentlyUsedMap.kt
|
1
|
2335
|
package com.onyx.lang.map
import java.util.LinkedHashMap
/**
* Created by Tim Osborn on 3/24/17.
*
* This map will retain value that are most recently used. If an value has expired, it will
* eject the last recently used object.
*/
open class LastRecentlyUsedMap<K, V> @JvmOverloads constructor(maxCapacity: Int, private var timeToLive: Int = 60 * 5 * 1000) : LinkedHashMap<K, V>(maxCapacity + 1, 1.0f) {
private val maxCapacity = 100
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<K, V>?): Boolean = size >= maxCapacity || (eldest!!.value as ExpirationValue).lastTouched + timeToLive < System.currentTimeMillis()
override fun put(key: K, value: V): V? {
@Suppress("UNCHECKED_CAST")
super.put(key, ExpirationValue(System.currentTimeMillis(), value as Any) as V)
return value
}
/**
* Get the object for key. Also indicate it as touched so it marks the record as recently used
*
* @param key Map entry key
* @return Value null if it doesn't exist
*/
@Suppress("UNCHECKED_CAST")
override operator fun get(key: K): V? {
val expirationValue = super.remove(key) as ExpirationValue?
if (expirationValue != null) {
expirationValue.lastTouched = System.currentTimeMillis()
super.put(key, expirationValue as V)
} else {
return null
}
return expirationValue.value as V
}
/**
* Override to not return the expiration value but the actual value
* @param action The action to be performed for each entry
*/
@Suppress("UNCHECKED_CAST")
open fun forEach(action: (K,V?) -> Unit) = entries.forEach { action.invoke(it.key, (it.value as ExpirationValue).value as V)}
/**
* POJO for tracking last touched
*/
class ExpirationValue internal constructor(internal var lastTouched: Long, internal val value: Any) {
/**
* Hash Code
* @return The value's hash code
*/
override fun hashCode(): Int = value.hashCode()
/**
* Equals compares the values equals
* @param other Object to compare
* @return Whether the values are equal
*/
override fun equals(other: Any?): Boolean = other is ExpirationValue && other.value == value
}
}
|
agpl-3.0
|
ba69239c2f7ded908cc543fec18b0a82
| 33.338235 | 198 | 0.639829 | 4.245455 | false | false | false | false |
GunoH/intellij-community
|
platform/platform-tests/testSrc/com/intellij/internal/statistics/metadata/validator/FeatureUsageCustomValidatorsUtilTest.kt
|
10
|
4684
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistics.metadata.validator
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.findPluginTypeByValue
import org.junit.Assert
import org.junit.Test
class FeatureUsageCustomValidatorsUtilTest {
@Test
fun `test plugin type detected by value`() {
Assert.assertEquals(PluginType.NOT_LISTED, findPluginTypeByValue("NOT_LISTED"))
Assert.assertEquals(PluginType.UNKNOWN, findPluginTypeByValue("UNKNOWN"))
Assert.assertEquals(PluginType.LISTED, findPluginTypeByValue("LISTED"))
Assert.assertEquals(PluginType.JB_NOT_BUNDLED, findPluginTypeByValue("JB_NOT_BUNDLED"))
Assert.assertEquals(PluginType.JB_BUNDLED, findPluginTypeByValue("JB_BUNDLED"))
Assert.assertEquals(PluginType.PLATFORM, findPluginTypeByValue("PLATFORM"))
Assert.assertEquals(PluginType.JVM_CORE, findPluginTypeByValue("JVM_CORE"))
Assert.assertEquals(PluginType.JB_UPDATED_BUNDLED, findPluginTypeByValue("JB_UPDATED_BUNDLED"))
Assert.assertEquals(PluginType.JB_UPDATED_BUNDLED, findPluginTypeByValue("JB_UPDATED_BUNDLED"))
}
@Test
fun `test rejected invalid plugin type`() {
Assert.assertNull(findPluginTypeByValue(""))
Assert.assertNull(findPluginTypeByValue("OTHER_VALUE"))
}
@Test
fun `test reject action from unknown or not listed plugin`() {
doRejectTest(newContext(null, null))
doRejectTest(newContext("", null))
doRejectTest(newContext("SOME_TYPE", null))
doRejectTest(newContext("SOME_TYPE", "my.plugin.id"))
doRejectTest(newContext("", "my.plugin.id"))
doRejectTest(newContext(null, "my.plugin.id"))
doRejectTest(newContext("UNKNOWN", "my.plugin.id"))
doRejectTest(newContext("UNKNOWN", ""))
doRejectTest(newContext("UNKNOWN", null))
doRejectTest(newContext("NOT_LISTED", "my.plugin.id"))
doRejectTest(newContext("NOT_LISTED", ""))
doRejectTest(newContext("NOT_LISTED", null))
}
@Test
fun `test actions from listed plugin`() {
doAcceptTest(false, newContext("LISTED", "my.plugin.id"))
doRejectTest(false, newContext("NOT_LISTED", ""))
doRejectTest(false, newContext("NOT_LISTED", null))
}
@Test
fun `test action from jb plugin`() {
doRejectTest(true, newContext("LISTED", "my.plugin.id"))
doRejectTest(true, newContext("LISTED", ""))
doRejectTest(true, newContext("LISTED", null))
}
@Test
fun `test action from platform or jb plugin`() {
doAcceptTest(newContext("JB_NOT_BUNDLED", "my.plugin.id"))
doAcceptTest(newContext("JB_BUNDLED", "my.plugin.id"))
doAcceptTest(newContext("PLATFORM", "my.plugin.id"))
doAcceptTest(newContext("PLATFORM", ""))
doAcceptTest(newContext("PLATFORM", null))
doRejectTest(newContext("JB_BUNDLED", ""))
doRejectTest(newContext("JB_BUNDLED", null))
doRejectTest(newContext("JB_NOT_BUNDLED", ""))
doRejectTest(newContext("JB_NOT_BUNDLED", null))
}
private fun doAcceptTest(context: EventContext) {
doAcceptTest(true, context)
doAcceptTest(false, context)
}
private fun doAcceptTest(fromJBPlugin: Boolean, context: EventContext) {
val rule = TestCheckPluginTypeCustomValidationRule(fromJBPlugin)
Assert.assertEquals(ValidationResultType.ACCEPTED, rule.validate("data", context))
}
private fun doRejectTest(context: EventContext) {
doRejectTest(true, context)
doRejectTest(false, context)
}
private fun doRejectTest(fromJBPlugin: Boolean, context: EventContext) {
val rule = TestCheckPluginTypeCustomValidationRule(fromJBPlugin)
Assert.assertEquals(ValidationResultType.REJECTED, rule.validate("data", context))
}
}
private fun newContext(plugin_type: String?, plugin: String?): EventContext {
val data = HashMap<String, Any>()
plugin?.let { data["plugin"] = plugin }
plugin_type?.let { data["plugin_type"] = plugin_type }
return EventContext.create("data", data)
}
class TestCheckPluginTypeCustomValidationRule(private val fromJBPlugin: Boolean) : CustomValidationRule() {
override fun acceptRuleId(ruleId: String?): Boolean = true
override fun doValidate(data: String, context: EventContext): ValidationResultType {
return if (fromJBPlugin) acceptWhenReportedByJetBrainsPlugin(context) else acceptWhenReportedByPluginFromPluginRepository(context)
}
}
|
apache-2.0
|
19bfc2c07a72cedea8fbc9564247f36b
| 40.830357 | 140 | 0.750427 | 4.123239 | false | true | false | false |
GunoH/intellij-community
|
plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/core/DebuggerUtils.kt
|
1
|
9370
|
// 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.debugger.core
import com.intellij.debugger.SourcePosition
import com.intellij.debugger.impl.DebuggerUtilsAsync
import com.intellij.debugger.impl.DebuggerUtilsImpl.getLocalVariableBorders
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.concurrency.annotations.RequiresReadLock
import com.sun.jdi.LocalVariable
import com.sun.jdi.Location
import com.sun.jdi.ReferenceType
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.analysis.api.analyze
import org.jetbrains.kotlin.analysis.api.calls.successfulFunctionCallOrNull
import org.jetbrains.kotlin.asJava.finder.JavaElementFinder
import org.jetbrains.kotlin.idea.base.facet.platform.platform
import org.jetbrains.kotlin.idea.base.indices.KotlinPackageIndexUtils.findFilesWithExactPackage
import org.jetbrains.kotlin.idea.base.projectStructure.scope.KotlinSourceFilterScope
import org.jetbrains.kotlin.idea.base.psi.getLineStartOffset
import org.jetbrains.kotlin.idea.base.util.KOTLIN_FILE_EXTENSIONS
import org.jetbrains.kotlin.idea.debugger.base.util.FileApplicabilityChecker
import org.jetbrains.kotlin.idea.debugger.base.util.KotlinSourceMapCache
import org.jetbrains.kotlin.idea.stubindex.KotlinFileFacadeFqNameIndex
import com.intellij.openapi.application.runReadAction
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.kotlin.PackagePartClassUtils
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.platform.isCommon
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import java.util.*
object DebuggerUtils {
@set:TestOnly
var forceRanking = false
private val IR_BACKEND_LAMBDA_REGEX = ".+\\\$lambda[$-]\\d+".toRegex()
fun findSourceFileForClassIncludeLibrarySources(
project: Project,
scope: GlobalSearchScope,
className: JvmClassName,
fileName: String,
location: Location? = null
): KtFile? {
return runReadAction {
findSourceFileForClass(
project,
listOf(scope, KotlinSourceFilterScope.librarySources(GlobalSearchScope.allScope(project), project)),
className,
fileName,
location
)
}
}
fun findSourceFileForClass(
project: Project,
scopes: List<GlobalSearchScope>,
className: JvmClassName,
fileName: String,
location: Location?
): KtFile? {
if (!isKotlinSourceFile(fileName)) return null
if (DumbService.getInstance(project).isDumb) return null
val partFqName = className.fqNameForClassNameWithoutDollars
for (scope in scopes) {
val files = findFilesByNameInPackage(className, fileName, project, scope)
.filter { it.platform.isJvm() || it.platform.isCommon() }
if (files.isEmpty()) {
continue
}
if (files.size == 1 && !forceRanking || location == null) {
return files.first()
}
val singleFile = runReadAction {
val matchingFiles = KotlinFileFacadeFqNameIndex.get(partFqName.asString(), project, scope)
PackagePartClassUtils.getFilesWithCallables(matchingFiles).singleOrNull { it.name == fileName }
}
if (singleFile != null) {
return singleFile
}
return chooseApplicableFile(files, location)
}
return null
}
private fun chooseApplicableFile(files: List<KtFile>, location: Location): KtFile {
return if (Registry.`is`("kotlin.debugger.analysis.api.file.applicability.checker")) {
FileApplicabilityChecker.chooseMostApplicableFile(files, location)
} else {
KotlinDebuggerLegacyFacade.getInstance()?.fileSelector?.chooseMostApplicableFile(files, location)
?: FileApplicabilityChecker.chooseMostApplicableFile(files, location)
}
}
private fun findFilesByNameInPackage(
className: JvmClassName,
fileName: String,
project: Project,
searchScope: GlobalSearchScope
): List<KtFile> {
val files = findFilesWithExactPackage(className.packageFqName, searchScope, project).filter { it.name == fileName }
return files.sortedWith(JavaElementFinder.byClasspathComparator(searchScope))
}
fun isKotlinSourceFile(fileName: String): Boolean {
val extension = FileUtilRt.getExtension(fileName).lowercase(Locale.getDefault())
return extension in KOTLIN_FILE_EXTENSIONS
}
fun String.trimIfMangledInBytecode(isMangledInBytecode: Boolean): String =
if (isMangledInBytecode)
getMethodNameWithoutMangling()
else
this
private fun String.getMethodNameWithoutMangling() =
substringBefore('-')
fun String.isGeneratedIrBackendLambdaMethodName() =
matches(IR_BACKEND_LAMBDA_REGEX)
fun LocalVariable.getBorders(): ClosedRange<Location>? {
val range = getLocalVariableBorders(this) ?: return null
return range.from..range.to
}
@RequiresReadLock
@ApiStatus.Internal
fun getLocationsOfInlinedLine(type: ReferenceType, position: SourcePosition, sourceSearchScope: GlobalSearchScope): List<Location> {
val line = position.line
val file = position.file
val project = position.file.project
val lineStartOffset = file.getLineStartOffset(line) ?: return listOf()
val element = file.findElementAt(lineStartOffset) ?: return listOf()
val ktElement = element.parents.firstIsInstanceOrNull<KtElement>() ?: return listOf()
val isInInline = element.parents.any { it is KtFunction && it.hasModifier(KtTokens.INLINE_KEYWORD) }
if (!isInInline) {
// Lambdas passed to cross-inline arguments are inlined when they are used in non-inlined lambdas
val isInCrossInlineArgument = isInCrossInlineArgument(ktElement)
if (!isInCrossInlineArgument) {
return listOf()
}
}
val lines = inlinedLinesNumbers(line + 1, position.file.name, FqName(type.name()), type.sourceName(), project, sourceSearchScope)
return lines.flatMap { DebuggerUtilsAsync.locationsOfLineSync(type, it) }
}
private fun isInCrossInlineArgument(ktElement: KtElement): Boolean {
for (function in ktElement.parents.filterIsInstance<KtFunction>()) {
when (function) {
is KtFunctionLiteral -> {
val lambdaExpression = function.parent as? KtLambdaExpression ?: continue
val argumentExpression = lambdaExpression.parent
if (argumentExpression is KtValueArgument && isCrossInlineArgument(lambdaExpression)) {
return true
}
}
is KtNamedFunction -> {
if (function.parent is KtValueArgument && isCrossInlineArgument(function)) {
return true
}
}
}
}
return false
}
private fun isCrossInlineArgument(argumentExpression: KtExpression): Boolean {
val callExpression = KtPsiUtil.getParentCallIfPresent(argumentExpression) ?: return false
return analyze(callExpression) f@ {
val call = callExpression.resolveCall()?.successfulFunctionCallOrNull() ?: return@f false
val parameter = call.argumentMapping[argumentExpression]?.symbol ?: return@f false
return@f parameter.isCrossinline
}
}
private fun inlinedLinesNumbers(
inlineLineNumber: Int, inlineFileName: String,
destinationTypeFqName: FqName, destinationFileName: String,
project: Project, sourceSearchScope: GlobalSearchScope
): List<Int> {
val internalName = destinationTypeFqName.asString().replace('.', '/')
val jvmClassName = JvmClassName.byInternalName(internalName)
val file = findSourceFileForClassIncludeLibrarySources(project, sourceSearchScope, jvmClassName, destinationFileName)
?: return listOf()
val virtualFile = file.virtualFile ?: return listOf()
val sourceMap = KotlinSourceMapCache.getInstance(project).getSourceMap(virtualFile, jvmClassName) ?: return listOf()
val mappingsToInlinedFile = sourceMap.fileMappings.filter { it.name == inlineFileName }
val mappingIntervals = mappingsToInlinedFile.flatMap { it.lineMappings }
return mappingIntervals.asSequence().filter { rangeMapping -> rangeMapping.hasMappingForSource(inlineLineNumber) }
.map { rangeMapping -> rangeMapping.mapSourceToDest(inlineLineNumber) }.filter { line -> line != -1 }.toList()
}
}
|
apache-2.0
|
e01cf209e16754460793c065c5f96d85
| 40.830357 | 137 | 0.695838 | 5.078591 | false | false | false | false |
AsamK/TextSecure
|
app/src/main/java/org/thoughtcrime/securesms/stories/viewer/StoryViewerFragment.kt
|
1
|
3180
|
package org.thoughtcrime.securesms.stories.viewer
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.LiveDataReactiveStreams
import androidx.viewpager2.widget.ViewPager2
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.recipients.RecipientId
import org.thoughtcrime.securesms.stories.StoryViewerArgs
import org.thoughtcrime.securesms.stories.viewer.page.StoryViewerPageFragment
/**
* Fragment which manages a vertical pager fragment of stories.
*/
class StoryViewerFragment : Fragment(R.layout.stories_viewer_fragment), StoryViewerPageFragment.Callback {
private val onPageChanged = OnPageChanged()
private lateinit var storyPager: ViewPager2
private val viewModel: StoryViewerViewModel by viewModels(
factoryProducer = {
StoryViewerViewModel.Factory(storyViewerArgs, StoryViewerRepository())
}
)
private val storyViewerArgs: StoryViewerArgs by lazy { requireArguments().getParcelable(ARGS)!! }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
storyPager = view.findViewById(R.id.story_item_pager)
val adapter = StoryViewerPagerAdapter(this, storyViewerArgs.storyId, storyViewerArgs.isFromNotification, storyViewerArgs.groupReplyStartPosition)
storyPager.adapter = adapter
viewModel.isChildScrolling.observe(viewLifecycleOwner) {
storyPager.isUserInputEnabled = !it
}
LiveDataReactiveStreams.fromPublisher(viewModel.state).observe(viewLifecycleOwner) { state ->
adapter.setPages(state.pages)
if (state.pages.isNotEmpty() && storyPager.currentItem != state.page) {
storyPager.setCurrentItem(state.page, state.previousPage > -1)
if (state.page >= state.pages.size) {
requireActivity().onBackPressed()
}
}
if (state.loadState.isReady()) {
requireActivity().supportStartPostponedEnterTransition()
}
}
}
override fun onResume() {
super.onResume()
viewModel.setIsScrolling(false)
storyPager.registerOnPageChangeCallback(onPageChanged)
}
override fun onPause() {
super.onPause()
viewModel.setIsScrolling(false)
storyPager.unregisterOnPageChangeCallback(onPageChanged)
}
override fun onGoToPreviousStory(recipientId: RecipientId) {
viewModel.onGoToPrevious(recipientId)
}
override fun onFinishedPosts(recipientId: RecipientId) {
viewModel.onGoToNext(recipientId)
}
override fun onStoryHidden(recipientId: RecipientId) {
viewModel.onRecipientHidden()
}
inner class OnPageChanged : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
viewModel.setSelectedPage(position)
}
override fun onPageScrollStateChanged(state: Int) {
viewModel.setIsScrolling(state == ViewPager2.SCROLL_STATE_DRAGGING)
}
}
companion object {
private const val ARGS = "args"
fun create(storyViewerArgs: StoryViewerArgs): Fragment {
return StoryViewerFragment().apply {
arguments = Bundle().apply {
putParcelable(ARGS, storyViewerArgs)
}
}
}
}
}
|
gpl-3.0
|
f01217cf79dd18301c189982574c32c8
| 30.176471 | 149 | 0.749057 | 4.704142 | false | false | false | false |
yongce/AndroidLib
|
archLintRules/src/main/java/me/ycdev/android/arch/lint/base/WrapperDetectorBase.kt
|
1
|
1554
|
package me.ycdev.android.arch.lint.base
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.JavaContext
import com.intellij.psi.PsiMethod
import org.jetbrains.uast.UCallExpression
import org.jetbrains.uast.UElement
import org.jetbrains.uast.getContainingUClass
abstract class WrapperDetectorBase : Detector(), Detector.UastScanner {
protected abstract val applicableMethods: List<String>
protected abstract val wrapperClassName: String
protected abstract val targetClassNames: Array<String>
protected abstract fun reportViolation(context: JavaContext, element: UElement)
override fun getApplicableMethodNames(): List<String> = applicableMethods
override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
val evaluator = context.evaluator
val surroundingClass = node.getContainingUClass()?.javaPsi
if (surroundingClass == null) {
println(
"Fatal error in WrapperDetectorBase! Failed to get surrounding" +
" class \'" + node.uastParent + "\'"
)
return
}
val containingClassName = surroundingClass.qualifiedName
if (wrapperClassName == containingClassName) {
return
}
for (targetClassName in targetClassNames) {
if (evaluator.isMemberInSubClassOf(method, targetClassName, false)) {
reportViolation(context, node)
return
}
}
}
}
|
apache-2.0
|
4e3335c1261c12c77c4d61bd441fa55e
| 36.902439 | 98 | 0.686615 | 5.197324 | false | false | false | false |
ktorio/ktor
|
ktor-server/ktor-server-plugins/ktor-server-locations/jvm/src/io/ktor/server/locations/BackwardCompatibleImpl.kt
|
1
|
12141
|
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.locations
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.plugins.*
import io.ktor.server.plugins.dataconversion.*
import io.ktor.server.routing.*
import io.ktor.util.converters.*
import io.ktor.util.reflect.*
import java.lang.reflect.*
import java.util.*
import kotlin.reflect.*
import kotlin.reflect.full.*
import kotlin.reflect.jvm.*
@OptIn(KtorExperimentalLocationsAPI::class)
internal abstract class LocationsImpl(
protected val application: Application,
protected val routeService: LocationRouteService
) {
protected val info: MutableMap<KClass<*>, LocationInfo> = HashMap()
@Suppress("DEPRECATION_ERROR")
protected val conversionService: ConversionService
get() = application.conversionService
val registeredLocations: List<LocationInfo>
get() = Collections.unmodifiableList(info.values.toList())
public abstract fun getOrCreateInfo(locationClass: KClass<*>): LocationInfo
public abstract fun instantiate(info: LocationInfo, allParameters: Parameters): Any
public abstract fun href(instance: Any): String
public abstract fun href(location: Any, builder: URLBuilder)
}
@OptIn(KtorExperimentalLocationsAPI::class)
internal class BackwardCompatibleImpl(
application: Application,
routeService: LocationRouteService
) : LocationsImpl(application, routeService) {
private data class ResolvedUriInfo(val path: String, val query: List<Pair<String, String>>)
private val rootUri = ResolvedUriInfo("", emptyList())
override fun getOrCreateInfo(locationClass: KClass<*>): LocationInfo {
return info[locationClass] ?: getOrCreateInfo(locationClass, HashSet())
}
override fun instantiate(info: LocationInfo, allParameters: Parameters): Any {
return info.create(allParameters)
}
override fun href(instance: Any): String {
val info = pathAndQuery(instance)
return info.path + if (info.query.any()) "?" + info.query.formUrlEncode() else ""
}
override fun href(location: Any, builder: URLBuilder) {
val info = pathAndQuery(location)
builder.encodedPath = info.path
for ((name, value) in info.query) {
builder.parameters.append(name, value)
}
}
private fun pathAndQuery(location: Any): ResolvedUriInfo {
val info = getOrCreateInfo(location::class.java.kotlin)
fun propertyValue(instance: Any, name: String): List<String> {
// TODO: Cache properties by name in info
val property = info.pathParameters.single { it.name == name }
val value = property.getter(instance)
return conversionService.toValues(value)
}
val substituteParts = RoutingPath.parse(info.path).parts.flatMap {
when (it.kind) {
RoutingPathSegmentKind.Constant -> listOf(it.value)
RoutingPathSegmentKind.Parameter -> {
if (info.klass.objectInstance != null) {
throw IllegalArgumentException(
"There is no place to bind ${it.value} in object for '${info.klass}'"
)
}
propertyValue(location, PathSegmentSelectorBuilder.parseName(it.value))
}
}
}
val relativePath = substituteParts
.filterNot { it.isEmpty() }
.joinToString("/") { it.encodeURLQueryComponent() }
val parentInfo = when {
info.parent == null -> rootUri
info.parentParameter != null -> {
val enclosingLocation = info.parentParameter.getter(location)!!
pathAndQuery(enclosingLocation)
}
else -> ResolvedUriInfo(info.parent.path, emptyList())
}
val queryValues = info.queryParameters.flatMap { property ->
val value = property.getter(location)
conversionService.toValues(value).map { property.name to it }
}
return parentInfo.combine(relativePath, queryValues, info.path.endsWith('/'))
}
private fun LocationInfo.create(allParameters: Parameters): Any {
val objectInstance = klass.objectInstance
if (objectInstance != null) return objectInstance
val constructor: KFunction<Any> = klass.primaryConstructor ?: klass.constructors.single()
val parameters = constructor.parameters
val arguments = parameters.map { parameter ->
val parameterType = parameter.type
val parameterTypeInfo =
TypeInfo(parameterType.classifier as KClass<*>, parameterType.javaType, parameterType)
val parameterName = parameter.name ?: getParameterNameFromAnnotation(parameter)
val value: Any? = if (parent != null && parameterType == parent.klass.starProjectedType) {
parent.create(allParameters)
} else {
createFromParameters(allParameters, parameterName, parameterTypeInfo, parameter.isOptional)
}
parameter to value
}.filterNot { it.first.isOptional && it.second == null }.toMap()
try {
return constructor.callBy(arguments)
} catch (cause: InvocationTargetException) {
throw cause.cause ?: cause
}
}
private fun createFromParameters(parameters: Parameters, name: String, type: TypeInfo, optional: Boolean): Any? {
return when (val values = parameters.getAll(name)) {
null -> when {
!optional -> {
throw MissingRequestParameterException(name)
}
else -> null
}
else -> {
try {
conversionService.fromValues(values, type) ?: emptyList<Unit>()
} catch (cause: Throwable) {
throw ParameterConversionException(name, type.toString(), cause)
}
}
}
}
@Suppress("UNUSED_PARAMETER")
private fun getParameterNameFromAnnotation(parameter: KParameter): String = TODO()
private fun ResolvedUriInfo.combine(
relativePath: String,
queryValues: List<Pair<String, String>>,
trailingSlash: Boolean,
): ResolvedUriInfo {
val pathElements = (path.split("/") + relativePath.split("/")).filterNot { it.isEmpty() }
val combinedPath = if (pathElements.isNotEmpty()) {
pathElements.joinToString("/", "/", if (trailingSlash) "/" else "")
} else "/"
return ResolvedUriInfo(combinedPath, query + queryValues)
}
private fun getOrCreateInfo(
locationClass: KClass<*>,
visited: MutableSet<KClass<*>>
): LocationInfo {
return info.getOrPut(locationClass) {
check(visited.add(locationClass)) { "Cyclic dependencies in locations are not allowed." }
val outerClass = locationClass.java.declaringClass?.kotlin
val parentInfo = outerClass?.let {
if (routeService.findRoute(outerClass) != null) getOrCreateInfo(outerClass, visited) else null
}
if (parentInfo != null && locationClass.isKotlinObject && parentInfo.klass.isKotlinObject) {
application.log.warn(
"Object nesting in Ktor Locations is going to be deprecated. " +
"Convert nested object to a class with parameter. " +
"See https://github.com/ktorio/ktor/issues/1660 for more details."
)
}
val path = routeService.findRoute(locationClass) ?: ""
if (locationClass.objectInstance != null) {
return@getOrPut LocationInfo(locationClass, parentInfo, null, path, emptyList(), emptyList())
}
val constructor: KFunction<Any> =
locationClass.primaryConstructor
?: locationClass.constructors.singleOrNull()
?: throw IllegalArgumentException(
"Class $locationClass cannot be instantiated because the constructor is missing"
)
val declaredProperties = constructor.parameters.map { parameter ->
val property =
locationClass.declaredMemberProperties.singleOrNull { property -> property.name == parameter.name }
?: throw LocationRoutingException(
"Parameter ${parameter.name} of constructor " +
"for class ${locationClass.qualifiedName} should have corresponding property"
)
@Suppress("UNCHECKED_CAST")
LocationPropertyInfoImpl(
parameter.name ?: "<unnamed>",
(property as KProperty1<Any, Any?>).getter,
parameter.isOptional
)
}
val parentParameter = declaredProperties.firstOrNull {
it.kGetter.returnType == outerClass?.starProjectedType
}
if (parentInfo != null && parentParameter == null) {
if (parentInfo.parentParameter != null) {
throw LocationRoutingException(
"Nested location '$locationClass' should have parameter for parent location " +
"because it is chained to its parent"
)
}
if (parentInfo.pathParameters.any { !it.isOptional }) {
throw LocationRoutingException(
"Nested location '$locationClass' should have parameter for parent location " +
"because of non-optional path parameters " +
"${parentInfo.pathParameters.filter { !it.isOptional }}"
)
}
if (parentInfo.queryParameters.any { !it.isOptional }) {
throw LocationRoutingException(
"Nested location '$locationClass' should have parameter for parent location " +
"because of non-optional query parameters " +
"${parentInfo.queryParameters.filter { !it.isOptional }}"
)
}
if (!parentInfo.klass.isKotlinObject) {
application.log.warn(
"A nested location class should have a parameter with the type " +
"of the outer location class. " +
"See https://github.com/ktorio/ktor/issues/1660 for more details."
)
}
}
val pathParameterNames = RoutingPath.parse(path).parts
.filter { it.kind == RoutingPathSegmentKind.Parameter }
.map { PathSegmentSelectorBuilder.parseName(it.value) }
val declaredParameterNames = declaredProperties.map { it.name }.toSet()
val invalidParameters = pathParameterNames.filter { it !in declaredParameterNames }
if (invalidParameters.any()) {
throw LocationRoutingException(
"Path parameters '$invalidParameters' are not bound to '$locationClass' properties"
)
}
val pathParameters = declaredProperties.filter { it.name in pathParameterNames }
val queryParameters =
declaredProperties.filterNot { pathParameterNames.contains(it.name) || it == parentParameter }
LocationInfo(locationClass, parentInfo, parentParameter, path, pathParameters, queryParameters)
}
}
@KtorExperimentalLocationsAPI
private val LocationPropertyInfo.getter: (Any) -> Any?
get() = (this as LocationPropertyInfoImpl).kGetter
private val KClass<*>.isKotlinObject: Boolean
get() = isFinal && objectInstance != null
}
|
apache-2.0
|
9505e849880567a2d77b3997476415da
| 41.451049 | 119 | 0.599786 | 5.301747 | false | false | false | false |
WataruSuzuki/Now-Slack-Android
|
mobile/src/main/java/jp/co/devjchankchan/now_slack_android/MainActivity.kt
|
1
|
4957
|
package jp.co.devjchankchan.now_slack_android
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.support.design.widget.FloatingActionButton
import android.support.design.widget.Snackbar
import android.view.View
import android.support.design.widget.NavigationView
import android.support.v4.view.GravityCompat
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.Menu
import android.view.MenuItem
import jp.co.devjchankchan.physicalbotlibrary.PhysicalBotService
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
private val mMainLooperHandler = Handler(Looper.getMainLooper())
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (this.checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(android.Manifest.permission.ACCESS_COARSE_LOCATION), PERMISSION_REQUEST_COARSE_LOCATION)
}
}
setupToolbar()
setupNavigationView()
setupFloatingActionButton()
changePage(R.id.nav_summary)
}
private fun setupFloatingActionButton() {
val fab = findViewById<View>(R.id.fab) as FloatingActionButton
fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
}
private fun setupToolbar() {
val toolbar = findViewById<View>(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
val drawer = findViewById<View>(R.id.drawer_layout) as DrawerLayout
val toggle = ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawer.addDrawerListener(toggle)
toggle.syncState()
}
private fun setupNavigationView() {
val navigationView = findViewById<View>(R.id.nav_view) as NavigationView
navigationView.setNavigationItemSelectedListener(this)
}
override fun onBackPressed() {
val drawer = findViewById<View>(R.id.drawer_layout) as DrawerLayout
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_restart_beacon -> restartPhysicalBotService()
//R.id.action_other_settings,
else -> {
}
}
return super.onOptionsItemSelected(item)
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
// Handle navigation view item clicks here.
changePage(item.itemId)
val id = item.itemId
if (id == R.id.nav_beacon) {
} else if (id == R.id.nav_account) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
val drawer = findViewById<View>(R.id.drawer_layout) as DrawerLayout
drawer.closeDrawer(GravityCompat.START)
return true
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
PERMISSION_REQUEST_COARSE_LOCATION -> restartPhysicalBotService()
else -> {
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
private fun restartPhysicalBotService() {
val service = Intent(this, PhysicalBotService::class.java)
stopService(service)
mMainLooperHandler.postDelayed({ startService(service) }, 500)
}
private fun changePage(itemId: Int) {
val page = DrawerPages.values().filter { itemId == it.menuId }.first()
// mSelectedContent = selectedPage
// mActionBar.setTitle(selectedPage)
// Swap page.
val fragmentManager = fragmentManager
val ft = fragmentManager.beginTransaction()
ft.replace(R.id.content_container, page.createFragment())
ft.commit()
}
companion object {
private val PERMISSION_REQUEST_COARSE_LOCATION = 1
}
}
|
apache-2.0
|
0b0245e496ca6bb6a43a4a0b14103802
| 32.493243 | 132 | 0.675005 | 4.63271 | false | false | false | false |
inorichi/mangafeed
|
app/src/main/java/eu/kanade/tachiyomi/network/AndroidCookieJar.kt
|
2
|
1461
|
package eu.kanade.tachiyomi.network
import android.webkit.CookieManager
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl
class AndroidCookieJar : CookieJar {
private val manager = CookieManager.getInstance()
override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
val urlString = url.toString()
cookies.forEach { manager.setCookie(urlString, it.toString()) }
}
override fun loadForRequest(url: HttpUrl): List<Cookie> {
return get(url)
}
fun get(url: HttpUrl): List<Cookie> {
val cookies = manager.getCookie(url.toString())
return if (cookies != null && cookies.isNotEmpty()) {
cookies.split(";").mapNotNull { Cookie.parse(url, it) }
} else {
emptyList()
}
}
fun remove(url: HttpUrl, cookieNames: List<String>? = null, maxAge: Int = -1) {
val urlString = url.toString()
val cookies = manager.getCookie(urlString) ?: return
fun List<String>.filterNames(): List<String> {
return if (cookieNames != null) {
this.filter { it in cookieNames }
} else {
this
}
}
cookies.split(";")
.map { it.substringBefore("=") }
.filterNames()
.onEach { manager.setCookie(urlString, "$it=;Max-Age=$maxAge") }
}
fun removeAll() {
manager.removeAllCookies {}
}
}
|
apache-2.0
|
6724f1f632f41275b982de0db61b81ed
| 26.566038 | 83 | 0.587953 | 4.440729 | false | false | false | false |
code-disaster/lwjgl3
|
modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/ARB_texture_compression.kt
|
4
|
9906
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengl.templates
import org.lwjgl.generator.*
import opengl.*
val ARB_texture_compression = "ARBTextureCompression".nativeClassGL("ARB_texture_compression", postfix = ARB) {
documentation =
"""
Native bindings to the $registryLink extension.
Compressing texture images can reduce texture memory utilization and improve performance when rendering textured primitives. This extension allows
OpenGL applications to use compressed texture images by providing:
${ol(
"A framework upon which extensions providing specific compressed image formats can be built.",
"""
A set of generic compressed internal formats that allow applications to specify that texture images should be stored in compressed form without
needing to code for specific compression formats.
"""
)}
An application can define compressed texture images by providing a texture image stored in a specific compressed image format. This extension does not
define any specific compressed image formats, but it does provide the mechanisms necessary to enable other extensions that do.
An application can also define compressed texture images by providing an uncompressed texture image but specifying a compressed internal format. In this
case, the GL will automatically compress the texture image using the appropriate image format. Compressed internal formats can either be specific (as
above) or generic. Generic compressed internal formats are not actual image formats, but are instead mapped into one of the specific compressed formats
provided by the GL (or to an uncompressed base internal format if no appropriate compressed format is available). Generic compressed internal formats
allow applications to use texture compression without needing to code to any particular compression algorithm. Generic compressed formats allow the use
of texture compression across a wide range of platforms with differing compression algorithms and also allow future GL implementations to substitute
improved compression methods transparently.
${GL13.promoted}
"""
IntConstant(
"Accepted by the {@code internalformat} parameter of TexImage1D, TexImage2D, TexImage3D, CopyTexImage1D, and CopyTexImage2D.",
"COMPRESSED_ALPHA_ARB"..0x84E9,
"COMPRESSED_LUMINANCE_ARB"..0x84EA,
"COMPRESSED_LUMINANCE_ALPHA_ARB"..0x84EB,
"COMPRESSED_INTENSITY_ARB"..0x84EC,
"COMPRESSED_RGB_ARB"..0x84ED,
"COMPRESSED_RGBA_ARB"..0x84EE
)
IntConstant(
"Accepted by the {@code target} parameter of Hint and the {@code value} parameter of GetIntegerv, GetBooleanv, GetFloatv, and GetDoublev.",
"TEXTURE_COMPRESSION_HINT_ARB"..0x84EF
)
IntConstant(
"Accepted by the {@code value} parameter of GetTexLevelParameter.",
"TEXTURE_COMPRESSED_IMAGE_SIZE_ARB"..0x86A0,
"TEXTURE_COMPRESSED_ARB"..0x86A1
)
IntConstant(
"Accepted by the {@code value} parameter of GetIntegerv, GetBooleanv, GetFloatv, and GetDoublev.",
"NUM_COMPRESSED_TEXTURE_FORMATS_ARB"..0x86A2,
"COMPRESSED_TEXTURE_FORMATS_ARB"..0x86A3
)
// KHR_texture_compression_astc_ldr formats are only accepted in CompressedTexImage* functions
val CompressTexImageFormats = "$SPECIFIC_COMPRESSED_TEXTURE_INTERNAL_FORMATS @##KHRTextureCompressionASTCLDR"
void(
"CompressedTexImage3DARB",
"Specifies a three-dimensional texture image in a compressed format.",
GLenum("target", "the target texture", "$TEXTURE_3D_TARGETS $PROXY_TEXTURE_3D_TARGETS"),
GLint("level", "the level-of-detail number. Level 0 is the base image level. Level n is the nth mipmap reduction image."),
GLenum("internalformat", "the format of the compressed image data", CompressTexImageFormats),
GLsizei("width", "the width of the texture image"),
GLsizei("height", "the height of the texture image"),
GLsizei("depth", "the depth of the texture image"),
Expression("0")..GLint("border", "must be 0"),
AutoSize("data")..GLsizei("imageSize", "the number of unsigned bytes of image data starting at the address specified by {@code data}"),
RawPointer..void.const.p("data", "a pointer to the compressed image data")
)
void(
"CompressedTexImage2DARB",
"Specifies a two-dimensional texture image in a compressed format.",
GLenum("target", "the target texture", "$TEXTURE_2D_TARGETS $PROXY_TEXTURE_2D_TARGETS"),
GLint("level", "the level-of-detail number. Level 0 is the base image level. Level n is the nth mipmap reduction image."),
GLenum("internalformat", "the format of the compressed image data", CompressTexImageFormats),
GLsizei("width", "the width of the texture image"),
GLsizei("height", "the height of the texture image"),
Expression("0")..GLint("border", "must be 0"),
AutoSize("data")..GLsizei("imageSize", "the number of unsigned bytes of image data starting at the address specified by {@code data}"),
RawPointer..void.const.p("data", "a pointer to the compressed image data")
)
void(
"CompressedTexImage1DARB",
"Specifies a one-dimensional texture image in a compressed format.",
GLenum("target", "the target texture", "#TEXTURE_1D #PROXY_TEXTURE_1D"),
GLint("level", "the level-of-detail number. Level 0 is the base image level. Level n is the nth mipmap reduction image."),
GLenum("internalformat", "the format of the compressed image data", CompressTexImageFormats),
GLsizei("width", "the width of the texture image"),
Expression("0")..GLint("border", "must be 0"),
AutoSize("data")..GLsizei("imageSize", "the number of unsigned bytes of image data starting at the address specified by {@code data}"),
RawPointer..void.const.p("data", "a pointer to the compressed image data")
)
void(
"CompressedTexSubImage3DARB",
"Respecifies only a cubic subregion of an existing 3D texel array, with incoming data stored in a specific compressed image format.",
GLenum("target", "the target texture", TEXTURE_3D_TARGETS),
GLint("level", "the level-of-detail number. Level 0 is the base image level. Level n is the nth mipmap reduction image."),
GLint("xoffset", "a texel offset in the x direction within the texture array"),
GLint("yoffset", "a texel offset in the y direction within the texture array"),
GLint("zoffset", "a texel offset in the z direction within the texture array"),
GLsizei("width", "the width of the texture subimage"),
GLsizei("height", "the height of the texture subimage"),
GLsizei("depth", "the depth of the texture subimage"),
GLenum("format", "the format of the compressed image data stored at address {@code data}", CompressTexImageFormats),
AutoSize("data")..GLsizei("imageSize", "the number of unsigned bytes of image data starting at the address specified by {@code data}"),
RawPointer..void.const.p("data", "a pointer to the compressed image data")
)
void(
"CompressedTexSubImage2DARB",
"Respecifies only a rectangular subregion of an existing 2D texel array, with incoming data stored in a specific compressed image format.",
GLenum("target", "the target texture", TEXTURE_2D_TARGETS),
GLint("level", "the level-of-detail number. Level 0 is the base image level. Level n is the nth mipmap reduction image."),
GLint("xoffset", "a texel offset in the x direction within the texture array"),
GLint("yoffset", "a texel offset in the y direction within the texture array"),
GLsizei("width", "the width of the texture subimage"),
GLsizei("height", "the height of the texture subimage"),
GLenum("format", "the format of the compressed image data stored at address {@code data}", CompressTexImageFormats),
AutoSize("data")..GLsizei("imageSize", "the number of unsigned bytes of image data starting at the address specified by {@code data}"),
RawPointer..void.const.p("data", "a pointer to the compressed image data")
)
void(
"CompressedTexSubImage1DARB",
"Respecifies only a subregion of an existing 1D texel array, with incoming data stored in a specific compressed image format.",
GLenum("target", "the target texture", "#TEXTURE_1D"),
GLint("level", "the level-of-detail number. Level 0 is the base image level. Level n is the nth mipmap reduction image."),
GLint("xoffset", "a texel offset in the x direction within the texture array"),
GLsizei("width", "the width of the texture subimage"),
GLenum("format", "the format of the compressed image data stored at address {@code data}", CompressTexImageFormats),
AutoSize("data")..GLsizei("imageSize", "the number of unsigned bytes of image data starting at the address specified by {@code data}"),
RawPointer..void.const.p("data", "a pointer to the compressed image data")
)
void(
"GetCompressedTexImageARB",
"Returns a compressed texture image.",
GLenum("target", "the target texture", "#TEXTURE_1D $TEXTURE_2D_FACE_TARGETS $TEXTURE_3D_TARGETS"),
GLint("level", "the level-of-detail number. Level 0 is the base image level. Level n is the nth mipmap reduction image."),
Check(
expression = "GL11.glGetTexLevelParameteri(target, level, GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB)", debug = true
)..RawPointer..void.p("pixels", "a buffer in which to return the compressed texture image")
)
}
|
bsd-3-clause
|
ce17417ced7730edf7218baec389fc5e
| 57.276471 | 160 | 0.694831 | 4.737446 | false | false | false | false |
code-disaster/lwjgl3
|
modules/lwjgl/zstd/src/templates/kotlin/zstd/templates/Zdict.kt
|
4
|
17393
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package zstd.templates
import org.lwjgl.generator.*
import zstd.*
val Zdict = "Zdict".nativeClass(Module.ZSTD, prefix = "ZDICT", prefixMethod = "ZDICT_") {
nativeDirective(
"""DISABLE_WARNINGS()
#define ZDICT_STATIC_LINKING_ONLY
#include "zdict.h"
ENABLE_WARNINGS()""")
documentation =
"""
Native bindings to the dictionary builder API of ${url("http://facebook.github.io/zstd/", "Zstandard")} (zstd).
<h4>Why should I use a dictionary?</h4>
Zstd can use dictionaries to improve compression ratio of small data. Traditionally small files don't compress well because there is very little
repetition in a single sample, since it is small. But, if you are compressing many similar files, like a bunch of JSON records that share the same
structure, you can train a dictionary on ahead of time on some samples of these files. Then, zstd can use the dictionary to find repetitions that are
present across samples. This can vastly improve compression ratio.
<h4>When is a dictionary useful?</h4>
Dictionaries are useful when compressing many small files that are similar. The larger a file is, the less benefit a dictionary will have. Generally,
we don't expect dictionary compression to be effective past 100KB. And the smaller a file is, the more we would expect the dictionary to help.
<h4>How do I use a dictionary?</h4>
Simply pass the dictionary to the zstd compressor with #CCtx_loadDictionary(). The same dictionary must then be passed to the decompressor, using
#DCtx_loadDictionary(). There are other more advanced functions that allow selecting some options, see {@code zstd.h} for complete documentation.
<h4>What is a zstd dictionary?</h4>
A zstd dictionary has two pieces: Its header, and its content. The header contains a magic number, the dictionary ID, and entropy tables. These entropy
tables allow zstd to save on header costs in the compressed file, which really matters for small data. The content is just bytes, which are repeated
content that is common across many samples.
<h4>What is a raw content dictionary?</h4>
A raw content dictionary is just bytes. It doesn't have a zstd dictionary header, a dictionary ID, or entropy tables. Any buffer is a valid raw content
dictionary.
<h4>How do I train a dictionary?</h4>
Gather samples from your use case. These samples should be similar to each other. If you have several use cases, you could try to train one dictionary
per use case.
Pass those samples to #trainFromBuffer() and that will train your dictionary. There are a few advanced versions of this function, but this is a great
starting point. If you want to further tune your dictionary you could try #optimizeTrainFromBuffer_cover(). If that is too slow you can try
#optimizeTrainFromBuffer_fastCover().
If the dictionary training function fails, that is likely because you either passed too few samples, or a dictionary would not be effective for your
data. Look at the messages that the dictionary trainer printed, if it doesn't say too few samples, then a dictionary would not be effective.
<h4>How large should my dictionary be?</h4>
A reasonable dictionary size, the {@code dictBufferCapacity}, is about 100KB. The zstd CLI defaults to a 110KB dictionary. You likely don't need a
dictionary larger than that. But, most use cases can get away with a smaller dictionary. The advanced dictionary builders can automatically shrink the
dictionary for you, and select a the smallest size that doesn't hurt compression ratio too much. See the {@code shrinkDict} parameter. A smaller
dictionary can save memory, and potentially speed up compression.
<h4>How many samples should I provide to the dictionary builder?</h4>
We generally recommend passing ~100x the size of the dictionary in samples. A few thousand should suffice. Having too few samples can hurt the
dictionaries effectiveness. Having more samples will only improve the dictionaries effectiveness. But having too many samples can slow down the
dictionary builder.
<h4>How do I determine if a dictionary will be effective?</h4>
Simply train a dictionary and try it out. You can use zstd's built in benchmarking tool to test the dictionary effectiveness.
${codeBlock("""
# Benchmark levels 1-3 without a dictionary
zstd -b1e3 -r /path/to/my/files
# Benchmark levels 1-3 with a dictionary
zstd -b1e3 -r /path/to/my/files -D /path/to/my/dictionary""")}
<h4>When should I retrain a dictionary?</h4>
You should retrain a dictionary when its effectiveness drops. Dictionary effectiveness drops as the data you are compressing changes. Generally, we do
expect dictionaries to "decay" over time, as your data changes, but the rate at which they decay depends on your use case. Internally, we regularly
retrain dictionaries, and if the new dictionary performs significantly better than the old dictionary, we will ship the new dictionary.
<h4>I have a raw content dictionary, how do I turn it into a zstd dictionary?</h4>
If you have a raw content dictionary, e.g. by manually constructing it, or using a third-party dictionary builder, you can turn it into a zstd
dictionary by using #finalizeDictionary(). You'll also have to provide some samples of the data. It will add the zstd header to the raw content, which
contains a dictionary ID and entropy tables, which will improve compression ratio, and allow zstd to write the dictionary ID into the frame, if you so
choose.
<h4>Do I have to use zstd's dictionary builder?</h4>
No! You can construct dictionary content however you please, it is just bytes. It will always be valid as a raw content dictionary. If you want a zstd
dictionary, which can improve compression ratio, use #finalizeDictionary().
<h4>What is the attack surface of a zstd dictionary?</h4>
Zstd is heavily fuzz tested, including loading fuzzed dictionaries, so zstd should never crash, or access out-of-bounds memory no matter what the
dictionary is. However, if an attacker can control the dictionary during decompression, they can cause zstd to generate arbitrary bytes, just like if
they controlled the compressed data.
"""
IntConstant(
"",
"CONTENTSIZE_MIN".."128",
"DICTSIZE_MIN".."256"
)
customMethod("""
private static long getSamplesBufferSize(PointerBuffer samplesSizes) {
long bytes = 0L;
for (int i = 0; i < samplesSizes.remaining(); i++) {
bytes += samplesSizes.get(i);
}
return bytes;
}""")
size_t(
"trainFromBuffer",
"""
Train a dictionary from an array of samples.
Redirect towards #optimizeTrainFromBuffer_fastCover() single-threaded, with {@code d=8}, {@code steps=4}, {@code f=20}, and {@code accel=1}.
Samples must be stored concatenated in a single flat buffer {@code samplesBuffer}, supplied with an array of sizes {@code samplesSizes}, providing the
size of each sample, in order.
The resulting dictionary will be saved into {@code dictBuffer}.
Note: {@code ZDICT_trainFromBuffer()} requires about 9 bytes of memory for each input byte.
Tips:
${ul(
"In general, a reasonable dictionary has a size of ~ 100 KB.",
"It's possible to select smaller or larger size, just by specifying {@code dictBufferCapacity}.",
"In general, it's recommended to provide a few thousands samples, though this can vary a lot.",
"It's recommended that total size of all samples be about ~x100 times the target size of dictionary."
)}
""",
void.p("dictBuffer", ""),
AutoSize("dictBuffer")..size_t("dictBufferCapacity", ""),
Check(
"getSamplesBufferSize(samplesSizes)", debug = true
)..void.const.p("samplesBuffer", ""),
size_t.const.p("samplesSizes", ""),
AutoSize("samplesSizes")..unsigned_int("nbSamples", ""),
returnDoc = "size of dictionary stored into {@code dictBuffer} (≤ {@code dictBufferCapacity}) or an error code, which can be tested with #isError()."
)
unsigned_int(
"getDictID",
"Extracts {@code dictID}.",
void.const.p("dictBuffer", ""),
AutoSize("dictBuffer")..size_t("dictSize", ""),
returnDoc = "zero if error (not a valid dictionary)"
)
unsigned_intb(
"isError",
"",
size_t("errorCode", "")
)
charASCII.const.p(
"getErrorName",
"",
size_t("errorCode", "")
)
// EXPERIMENTAL
size_t(
"trainFromBuffer_cover",
"""
Train a dictionary from an array of samples using the COVER algorithm.
Samples must be stored concatenated in a single flat buffer {@code samplesBuffer}, supplied with an array of sizes {@code samplesSizes}, providing the
size of each sample, in order.
The resulting dictionary will be saved into {@code dictBuffer}.
Note: {@code ZDICT_trainFromBuffer_cover()} requires about 9 bytes of memory for each input byte.
Tips:
${ul(
"In general, a reasonable dictionary has a size of ~ 100 KB.",
"It's possible to select smaller or larger szie, just by specifying {@code dictBufferCapacity}.",
"In general, it's recommended to provide a few thousands samples, though this can vary a lot.",
"It's recommended that total size of all samples be about ~x100 times the target size of dictionary."
)}
""",
void.p("dictBuffer", ""),
AutoSize("dictBuffer")..size_t("dictBufferCapacity", ""),
Check(
"getSamplesBufferSize(samplesSizes)", debug = true
)..void.const.p("samplesBuffer", ""),
size_t.const.p("samplesSizes", ""),
AutoSize("samplesSizes")..unsigned_int("nbSamples", ""),
ZDICT_cover_params_t("parameters", ""),
returnDoc = "size of dictionary stored into {@code dictBuffer} (≤ {@code dictBufferCapacity}) or an error code, which can be tested with #isError()."
)
size_t(
"optimizeTrainFromBuffer_cover",
"""
The same requirements as #trainFromBuffer_cover() hold for all the parameters except {@code parameters}.
This function tries many parameter combinations and picks the best parameters. {@code *parameters} is filled with the best parameters found, dictionary
constructed with those parameters is stored in {@code dictBuffer}.
${ul(
"All of the parameters {@code d}, {@code k}, {@code steps} are optional.",
"If {@code d} is non-zero then we don't check multiple values of {@code }d, otherwise we check {@code d = {6, 8}}.",
"If {@code steps} is zero it defaults to its default value.",
"If {@code k} is non-zero then we don't check multiple values of {@code k}, otherwise we check steps values in {@code [50, 2000]}."
)}
Note: {@code ZDICT_optimizeTrainFromBuffer_cover()} requires about 8 bytes of memory for each input byte and additionally another 5 bytes of memory for
each byte of memory for each thread.
""",
void.p("dictBuffer", ""),
AutoSize("dictBuffer")..size_t("dictBufferCapacity", ""),
Check(
"getSamplesBufferSize(samplesSizes)", debug = true
)..void.const.p("samplesBuffer", ""),
size_t.const.p("samplesSizes", ""),
AutoSize("samplesSizes")..unsigned_int("nbSamples", ""),
ZDICT_cover_params_t.p("parameters", ""),
returnDoc =
"""
size of dictionary stored into {@code dictBuffer} (≤ {@code dictBufferCapacity}) or an error code, which can be tested with #isError(). On success
{@code *parameters} contains the parameters selected.
"""
)
size_t(
"trainFromBuffer_fastCover",
"""
Train a dictionary from an array of samples using a modified version of COVER algorithm.
Samples must be stored concatenated in a single flat buffer {@code samplesBuffer}, supplied with an array of sizes {@code samplesSizes}, providing the
size of each sample, in order. {@code d} and {@code k} are required. All other parameters are optional, will use default values if not provided. The
resulting dictionary will be saved into {@code dictBuffer}.
Note: {@code ZDICT_trainFromBuffer_fastCover()} requires about 1 bytes of memory for each input byte and additionally another {@code 6 * 2^f} bytes of
memory.
Tips: In general, a reasonable dictionary has a size of {@code ~100 KB}. It's possible to select smaller or larger size, just by specifying
{@code dictBufferCapacity}. In general, it's recommended to provide a few thousands samples, though this can vary a lot. It's recommended that total
size of all samples be about {@code ~x100} times the target size of dictionary.
""",
void.p("dictBuffer", ""),
AutoSize("dictBuffer")..size_t("dictBufferCapacity", ""),
Check(
"getSamplesBufferSize(samplesSizes)", debug = true
)..void.const.p("samplesBuffer", ""),
size_t.const.p("samplesSizes", ""),
AutoSize("samplesSizes")..unsigned("nbSamples", ""),
ZDICT_fastCover_params_t("parameters", ""),
returnDoc = "size of dictionary stored into {@code dictBuffer} (≤ {@code dictBufferCapacity}) or an error code, which can be tested with #isError()."
)
size_t(
"optimizeTrainFromBuffer_fastCover",
"""
The same requirements as #trainFromBuffer_fastCover() hold for all the parameters except {@code parameters}.
This function tries many parameter combinations (specifically, {@code k} and {@code d} combinations) and picks the best parameters. {@code *parameters}
is filled with the best parameters found, dictionary constructed with those parameters is stored in {@code dictBuffer}.
${ul(
"All of the parameters {@code d}, {@code k}, {@code steps}, {@code f}, and {@code accel} are optional.",
"If {@code d} is non-zero then we don't check multiple values of {@code d}, otherwise we check {@code d = {6, 8}}.",
"If {@code steps} is zero it defaults to its default value.",
"If {@code k} is non-zero then we don't check multiple values of {@code k}, otherwise we check steps values in {@code [50, 2000]}.",
"If {@code f} is zero, default value of 20 is used.",
"If {@code accel} is zero, default value of 1 is used."
)}
Note: {@code ZDICT_optimizeTrainFromBuffer_fastCover()} requires about 1 byte of memory for each input byte and additionally another {@code 6 * 2^f}
bytes of memory for each thread.
""",
void.p("dictBuffer", ""),
AutoSize("dictBuffer")..size_t("dictBufferCapacity", ""),
Check(
"getSamplesBufferSize(samplesSizes)", debug = true
)..void.const.p("samplesBuffer", ""),
size_t.const.p("samplesSizes", ""),
AutoSize("samplesSizes")..unsigned_int("nbSamples", ""),
ZDICT_fastCover_params_t.p("parameters", ""),
returnDoc =
"""
size of dictionary stored into {@code dictBuffer} (≤ {@code dictBufferCapacity}) or an error code, which can be tested with #isError(). On success
{@code *parameters} contains the parameters selected.
"""
)
size_t(
"finalizeDictionary",
"""
Given a custom content as a basis for dictionary, and a set of samples, finalize dictionary by adding headers and statistics.
Samples must be stored concatenated in a flat buffer {@code samplesBuffer}, supplied with an array of sizes {@code samplesSizes}, providing the size of
each sample in order.
Notes:
${ul(
"{@code maxDictSize} must be ≥ {@code dictContentSize}, and must be ≥ #DICTSIZE_MIN bytes.",
"{@code ZDICT_finalizeDictionary()} will push notifications into {@code stderr} if instructed to, using {@code notificationLevel>0}.",
"{@code dictBuffer} and {@code dictContent} can overlap."
)}
""",
void.p("dictBuffer", ""),
AutoSize("dictBuffer")..size_t("dictBufferCapacity", ""),
void.const.p("dictContent", ""),
AutoSize("dictContent")..size_t("dictContentSize", ""),
Check(
"getSamplesBufferSize(samplesSizes)", debug = true
)..void.const.p("samplesBuffer", ""),
size_t.const.p("samplesSizes", ""),
AutoSize("samplesSizes")..unsigned_int("nbSamples", ""),
ZDICT_params_t("parameters", ""),
returnDoc = "size of dictionary stored into {@code dictBuffer} (≤ {@code dictBufferCapacity}) or an error code, which can be tested with #isError()."
)
}
|
bsd-3-clause
|
3f5ca99c2d2ed86989585b702f576ac8
| 49.126801 | 160 | 0.660611 | 4.512974 | false | false | false | false |
code-disaster/lwjgl3
|
modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/GL44Core.kt
|
4
|
25428
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengl.templates
import org.lwjgl.generator.*
import opengl.*
val GL44C = "GL44C".nativeClassGL("GL44C") {
extends = GL43C
documentation =
"""
The OpenGL functionality up to version 4.4. Includes only Core Profile symbols.
OpenGL 4.4 implementations support revision 4.40 of the OpenGL Shading Language.
Extensions promoted to core in this release:
${ul(
registryLinkTo("ARB", "buffer_storage"),
registryLinkTo("ARB", "clear_texture"),
registryLinkTo("ARB", "enhanced_layouts"),
registryLinkTo("ARB", "multi_bind"),
registryLinkTo("ARB", "query_buffer_object"),
registryLinkTo("ARB", "texture_mirror_clamp_to_edge"),
registryLinkTo("ARB", "texture_stencil8"),
registryLinkTo("ARB", "vertex_type_10f_11f_11f_rev")
)}
"""
IntConstant(
"Implementation-dependent state which constrains the maximum value of stride parameters to vertex array pointer-setting commands.",
"MAX_VERTEX_ATTRIB_STRIDE"..0x82E5
)
IntConstant(
"""
Implementations are not required to support primitive restart for separate patch primitives (primitive type PATCHES). Support can be queried by calling
GetBooleanv with the symbolic constant PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED. A value of FALSE indicates that primitive restart is treated as
disabled when drawing patches, no matter the value of the enables. A value of TRUE indicates that primitive restart behaves normally for patches.
""",
"PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED"..0x8221
)
IntConstant(
"Equivalent to #TEXTURE_BUFFER_ARB query, but named more consistently.",
"TEXTURE_BUFFER_BINDING"..0x8C2A
)
// ARB_buffer_storage
IntConstant(
"Accepted in the {@code flags} parameter of #BufferStorage() and #NamedBufferStorageEXT().",
"MAP_PERSISTENT_BIT"..0x0040,
"MAP_COHERENT_BIT"..0x0080,
"DYNAMIC_STORAGE_BIT"..0x0100,
"CLIENT_STORAGE_BIT"..0x0200
)
IntConstant(
"Accepted by the {@code pname} parameter of {@code GetBufferParameter{i|i64}v}.",
"BUFFER_IMMUTABLE_STORAGE"..0x821F,
"BUFFER_STORAGE_FLAGS"..0x8220
)
IntConstant(
"Accepted by the {@code barriers} parameter of #MemoryBarrier().",
"CLIENT_MAPPED_BUFFER_BARRIER_BIT"..0x00004000
)
void(
"BufferStorage",
"""
Creates the data store of a buffer object.
The data store of the buffer object bound to {@code target} is allocated as a result of a call to this function and cannot be de-allocated until the
buffer is deleted with a call to #DeleteBuffers(). Such a store may not be re-allocated through further calls to {@code BufferStorage}
or #BufferData().
{@code BufferStorage} deletes any existing data store. If any portion of the buffer object is mapped in the current context or any context current to
another thread, it is as though #UnmapBuffer() is executed in each such context prior to deleting the existing data store.
""",
GLenum("target", "the buffer object target", BUFFER_OBJECT_TARGETS),
AutoSize("data")..GLsizeiptr("size", "the size of the data store in basic machine units"),
optional..MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_FLOAT,
PointerMapping.DATA_DOUBLE
)..void.const.p(
"data",
"""
the address in client memory of the data that should be used to initialize the buffer's data store. If {@code data} is #NULL, the data store of the
buffer is created, but contains undefined data. Otherwise, {@code data} should point to an array of at least {@code size} basic machine units.
"""
),
GLbitfield(
"flags",
"""
the bitwise {@code OR} of flags describing the intended usage of the buffer object's data store by the application. Valid flags and their meanings
are as follows:
${ul(
"""
#DYNAMIC_STORAGE_BIT – The contents of the data store may be updated after creation through calls to
#BufferSubData(). If this bit is not set, the buffer content may not be directly updated by the client. The {@code data}
argument may be used to specify the initial content of the buffer's data store regardless of the presence of the #DYNAMIC_STORAGE_BIT.
Regardless of the presence of this bit, buffers may always be updated with server-side calls such as #CopyBufferSubData() and
#ClearBufferSubData().
""",
"""
#MAP_READ_BIT – The buffer's data store may be mapped by the client for read access and a pointer in the client's address space
obtained that may be read from.
""",
"""
#MAP_WRITE_BIT – The buffer's data store may be mapped by the client for write access and a pointer in the client's address
space obtained that may be written to.
""",
"""
#MAP_PERSISTENT_BIT – The client may request that the server read from or write to the buffer while it is mapped. The client's
pointer to the data store remains valid so long as the data store is mapped, even during execution of drawing or dispatch commands.
""",
"""
#MAP_COHERENT_BIT – Shared access to buffers that are simultaneously mapped for client access and are used by the server will be
coherent, so long as that mapping is performed using MapBufferRange. That is, data written to the store by either the client or server will be
immediately visible to the other with no further action taken by the application. In particular:
${ul(
"""
If {@code MAP_COHERENT_BIT} is not set and the client performs a write followed by a call to the #MemoryBarrier() command with
the #CLIENT_MAPPED_BUFFER_BARRIER_BIT set, then in subsequent commands the server will see the writes.
""",
"If {@code MAP_COHERENT_BIT} is set and the client performs a write, then in subsequent commands the server will see the writes.",
"""
If {@code MAP_COHERENT_BIT} is not set and the server performs a write, the application must call #MemoryBarrier() with the
#CLIENT_MAPPED_BUFFER_BARRIER_BIT set and then call #FenceSync() with #SYNC_GPU_COMMANDS_COMPLETE (or
#Finish()). Then the CPU will see the writes after the sync is complete.
""",
"""
If {@code MAP_COHERENT_BIT} is set and the server does a write, the app must call #FenceSync() with
#SYNC_GPU_COMMANDS_COMPLETE (or #Finish()). Then the CPU will see the writes after the sync is complete.
"""
)}
""",
"""
#CLIENT_STORAGE_BIT – When all other criteria for the buffer storage allocation are met, this bit may be used by an
implementation to determine whether to use storage that is local to the server or to the client to serve as the backing store for the buffer.
"""
)}
If {@code flags} contains #MAP_PERSISTENT_BIT, it must also contain at least one of #MAP_READ_BIT or #MAP_WRITE_BIT.
It is an error to specify #MAP_COHERENT_BIT without also specifying #MAP_PERSISTENT_BIT.
"""
)
)
// ARB_clear_texture
IntConstant(
"Accepted by the {@code pname} parameter for #GetInternalformativ() and #GetInternalformati64v().",
"CLEAR_TEXTURE"..0x9365
)
void(
"ClearTexSubImage",
"""
Fills all or part of a texture image with a constant value.
Arguments {@code xoffset}, {@code yoffset}, and {@code zoffset} specify the lower left texel coordinates of a {@code width}-wide by {@code height}-high
by {@code depth}-deep rectangular subregion of the texel array and are interpreted as they are in #TexSubImage3D().
For 1D array textures, {@code yoffset} is interpreted as the first layer to be cleared and {@code height} is the number of layers to clear. For 2D array
textures, {@code zoffset} is interpreted as the first layer to be cleared and {@code depth} is the number of layers to clear. Cube map textures are
treated as an array of six slices in the z-dimension, where the value of {@code zoffset} is interpreted as specifying the cube map face for the
corresponding {@code layer} and {@code depth} is the number of faces to clear. For cube map array textures, {@code zoffset} is the first layer-face to
clear, and {@code depth} is the number of layer-faces to clear. Each layer-face is translated into an array layer and a cube map face.
Negative values of {@code xoffset}, {@code yoffset}, and {@code zoffset} correspond to the coordinates of border texels.
""",
GLuint(
"texture",
"""
the texture to clear. It is an error if {@code texture} is zero or not the name of a texture object, if {@code texture} is a buffer texture, or if
the texture image has a compressed internal format
"""
),
GLint("level", "the texture level to clear"),
GLint("xoffset", "the x coordinate of the texel subregion"),
GLint("yoffset", "the y coordinate of the texel subregion"),
GLint("zoffset", "the z coordinate of the texel subregion"),
GLsizei("width", "the subregion width"),
GLsizei("height", "the subregion height"),
GLsizei("depth", "the subregion depth"),
GLenum("format", "the format of the source data", PIXEL_DATA_FORMATS),
GLenum("type", "the type of the source data", PIXEL_DATA_TYPES),
MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE
)..Unsafe..nullable..void.const.p(
"data",
"""
an array of between one and four components of texel data that will be used as the source for the constant fill value. If {@code data} is #NULL,
then the pointer is ignored and the sub-range of the texture image is filled with zeros.
"""
)
)
void(
"ClearTexImage",
"""
Is equivalent to calling #ClearTexSubImage() with {@code xoffset}, {@code yoffset}, and {@code zoffset} equal to -{@code b} and {@code width},
{@code height}, and {@code depth} equal to the dimensions of the texture image plus {@code 2xb} (or zero and one for dimensions the texture doesn't
have).
""",
GLuint(
"texture",
"""
the texture to clear. It is an error if {@code texture} is zero or not the name of a texture object, if {@code texture} is a buffer texture, or if
the texture image has a compressed internal format
"""
),
GLint("level", "the texture level to clear"),
GLenum("format", "the format of the source data", PIXEL_DATA_FORMATS),
GLenum("type", "the type of the source data", PIXEL_DATA_TYPES),
MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE
)..Unsafe..nullable..void.const.p(
"data",
"""
an array of between one and four components of texel data that will be used as the source for the constant fill value. If {@code data} is #NULL,
then the pointer is ignored and the sub-range of the texture image is filled with zeros.
"""
)
)
// ARB_enhanced_layouts
IntConstant(
"Accepted in the {@code props} array of #GetProgramResourceiv().",
"LOCATION_COMPONENT"..0x934A,
"TRANSFORM_FEEDBACK_BUFFER_INDEX"..0x934B,
"TRANSFORM_FEEDBACK_BUFFER_STRIDE"..0x934C
)
// ARB_multi_bind
void(
"BindBuffersBase",
"""
Binds {@code count} existing buffer objects to bindings numbered {@code first} through {@code first+count-1} in the array of buffer binding points
corresponding to {@code target}. If {@code buffers} is not #NULL, it specifies an array of {@code count} values, each of which must be zero or the name
of an existing buffer object. It is equivalent to:
${codeBlock("""
for ( i = 0; i < count; i++ ) {
if ( buffers == NULL ) {
glBindBufferBase(target, first + i, 0);
} else {
glBindBufferBase(target, first + i, buffers[i]);
}
}
""")}
except that the single general buffer binding corresponding to {@code target} is unmodified, and that buffers will not be created if they do not exist.
""",
GLenum("target", "the buffer object target", BUFFER_OBJECT_TARGETS),
GLuint("first", "the first binding"),
AutoSize("buffers")..GLsizei("count", "the number of bindings"),
nullable..GLuint.const.p("buffers", "an array of zeros or names of existing buffers objects")
)
void(
"BindBuffersRange",
"""
Binds {@code count} existing buffer objects to bindings numbered {@code first} through {@code first+count-1} in the array of buffer binding points
corresponding to {@code target}. {@code offsets} and {@code sizes} specify arrays of {@code count} values indicating the range of each buffer to bind.
If {@code buffers} is #NULL, all bindings from {@code first} through {@code first+count-1} are reset to their unbound (zero) state. In this
case, the offsets and sizes associated with the binding points are set to default values, ignoring {@code offsets} and {@code sizes}. It is equivalent
to:
${codeBlock("""
for ( i = 0; i < count; i++ ) {
if ( buffers == NULL ) {
glBindBufferRange(target, first + i, 0, 0, 0);
} else {
glBindBufferRange(target, first + i, buffers[i], offsets[i], sizes[i]);
}
}
""")}
except that the single general buffer binding corresponding to {@code target} is unmodified, and that buffers will not be created if they do not exist.
The values specified in {@code buffers}, {@code offsets}, and {@code sizes} will be checked separately for each binding point. When values for a
specific binding point are invalid, the state for that binding point will be unchanged and an error will be generated. However, state for other binding
points will still be changed if their corresponding values are valid.
""",
GLenum("target", "the buffer object target", BUFFER_OBJECT_TARGETS),
GLuint("first", "the first binding"),
AutoSize("buffers", "offsets", "sizes")..GLsizei("count", "the number of bindings"),
nullable..GLuint.const.p("buffers", "an array of names of existing buffers objects"),
nullable..GLintptr.const.p("offsets", "an array of offsets"),
nullable..GLsizeiptr.const.p("sizes", "an array of sizes")
)
void(
"BindTextures",
"""
Binds {@code count} existing texture objects to texture image units numbered {@code first} through {@code first+count-1}. If {@code textures} is not
#NULL, it specifies an array of {@code count} values, each of which must be zero or the name of an existing texture object. When an entry in
{@code textures} is the name of an existing texture object, that object is bound to corresponding texture unit for the target specified when the texture
object was created. When an entry in {@code textures} is zero, each of the targets enumerated at the beginning of this section is reset to its default
texture for the corresponding texture image unit. If {@code textures} is #NULL, each target of each affected texture image unit from {@code first}
through {@code first+count-1} is reset to its default texture.
{@code BindTextures} is equivalent to:
${codeBlock("""
for ( i = 0; i < count; i++ ) {
uint texture;
if ( textures == NULL ) {
texture = 0;
} else {
texture = textures[i];
}
ActiveTexture(TEXTURE0 + first + i);
if ( texture != 0 ) {
enum target; // target of texture object textures[i]
BindTexture(target, textures[i]);
} else {
for ( target in all supported targets ) {
BindTexture(target, 0);
}
}
}
""")}
except that the active texture selector retains its original value upon completion of the command, and that textures will not be created if they do not
exist.
The values specified in {@code textures} will be checked separately for each texture image unit. When a value for a specific texture image unit is
invalid, the state for that texture image unit will be unchanged and an error will be generated. However, state for other texture image units will still
be changed if their corresponding values are valid.
""",
GLuint("first", "the first texture objects"),
AutoSize("textures")..GLsizei("count", "the number of texture objects"),
nullable..GLuint.const.p("textures", "an array of zeros or names of existing texture objects")
)
void(
"BindSamplers",
"""
Binds {@code count} existing sampler objects to texture image units numbered {@code first} through {@code first+count-1}. If {@code samplers} is not
#NULL, it specifies an array of {@code count} values, each of which must be zero or the name of an existing sampler object. If {@code samplers} is #NULL,
each affected texture image unit from {@code first} through {@code first+count-1} will be reset to have no bound sampler object.
{@code BindSamplers} is equivalent to:
${codeBlock("""
for ( i = 0; i < count; i++ ) {
if ( samplers == NULL ) {
glBindSampler(first + i, 0);
} else {
glBindSampler(first + i, samplers[i]);
}
}
""")}
The values specified in {@code samplers} will be checked separately for each texture image unit. When a value for a specific texture image unit is
invalid, the state for that texture image unit will be unchanged and an error will be generated. However, state for other texture image units will still
be changed if their corresponding values are valid.
""",
GLuint("first", "the first sampler object"),
AutoSize("samplers")..GLsizei("count", "the number of sampler objects"),
nullable..GLuint.const.p("samplers", "an array of zeros or names of existing sampler objects")
)
void(
"BindImageTextures",
"""
Binds {@code count} existing texture objects to image units numbered {@code first} through {@code first+count-1}. If {@code textures} is not #NULL, it
specifies an array of {@code count} values, each of which must be zero or the name of an existing texture object. If {@code textures} is #NULL, each
affected image unit from {@code first} through {@code first+count-1} will be reset to have no bound texture object.
When binding a non-zero texture object to an image unit, the image unit {@code level}, {@code layered}, {@code layer}, and {@code access} parameters are
set to zero, #TRUE, zero, and #READ_WRITE, respectively. The image unit {@code format} parameter is taken from the internal
format of the texture image at level zero of the texture object identified by {@code textures}. For cube map textures, the internal format of the
#TEXTURE_CUBE_MAP_POSITIVE_X image of level zero is used. For multisample, multisample array, buffer, and rectangle textures, the internal
format of the single texture level is used.
When unbinding a texture object from an image unit, the image unit parameters {@code level}, {@code layered}, {@code layer}, and {@code format} will be
reset to their default values of zero, #FALSE, 0, and #R8, respectively.
{@code BindImageTextures} is equivalent to:
${codeBlock("""
for ( i = 0; i < count; i++ ) {
if ( textures == NULL || textures[i] = 0 ) {
glBindImageTexture(first + i, 0, 0, FALSE, 0, READ_ONLY, R8);
} else {
glBindImageTexture(first + i, textures[i], 0, TRUE, 0, READ_WRITE, lookupInternalFormat(textures[i]));
}
}
""")}
where {@code lookupInternalFormat} returns the internal format of the specified texture object.
The values specified in {@code textures} will be checked separately for each image unit. When a value for a specific image unit is invalid, the state
for that image unit will be unchanged and an error will be generated. However, state for other image units will still be changed if their corresponding
values are valid.
""",
GLuint("first", "the first image unit"),
AutoSize("textures")..GLsizei("count", "the number of image units"),
nullable..GLuint.const.p("textures", "an array of zeros or names of existing texture objects")
)
void(
"BindVertexBuffers",
"""
Binds {@code count} existing buffer objects to vertex buffer binding points numbered {@code first} through {@code first+count-1}. If {@code buffers} is
not #NULL, it specifies an array of {@code count} values, each of which must be zero or the name of an existing buffer object. {@code offsets} and
{@code strides} specify arrays of {@code count} values indicating the offset of the first element and stride between elements in each buffer,
respectively. If {@code buffers} is #NULL, each affected vertex buffer binding point from {@code first} through {@code first+count-1} will be reset to
have no bound buffer object. In this case, the offsets and strides associated with the binding points are set to default values, ignoring
{@code offsets} and {@code strides}.
{@code BindVertexBuffers} is equivalent to:
${codeBlock("""
for ( i = 0; i < count; i++ ) {
if ( buffers == NULL ) {
glBindVertexBuffer(first + i, 0, 0, 16);
} else {
glBindVertexBuffer(first + i, buffers[i], offsets[i], strides[i]);
}
}
""")}
except that buffers will not be created if they do not exist.
The values specified in {@code buffers}, {@code offsets}, and {@code strides} will be checked separately for each vertex buffer binding point. When a
value for a specific binding point is invalid, the state for that binding point will be unchanged and an error will be generated. However, state for
other binding points will still be changed if their corresponding values are valid.
""",
GLuint("first", "the first vertex buffer binding point"),
AutoSize("buffers", "offsets", "strides")..GLsizei("count", "the number of vertex buffer binding points"),
nullable..GLuint.const.p("buffers", "an array of zeros or names of existing buffers objects"),
nullable..GLintptr.const.p("offsets", "an array of offses"),
nullable..GLsizei.const.p("strides", "an array of stride values")
)
// ARB_query_buffer_object
IntConstant(
"Accepted by the {@code pname} parameter of #GetQueryObjectiv(), #GetQueryObjectuiv(), #GetQueryObjecti64v() and #GetQueryObjectui64v().",
"QUERY_RESULT_NO_WAIT"..0x9194
)
IntConstant(
"""
Accepted by the {@code target} parameter of #BindBuffer(), #BufferData(), #BufferSubData(),
#MapBuffer(), #UnmapBuffer(), #MapBufferRange(), #GetBufferSubData(),
#GetBufferParameteriv(), #GetBufferParameteri64v(), #GetBufferPointerv(),
#ClearBufferSubData(), and the {@code readtarget} and {@code writetarget} parameters of #CopyBufferSubData().
""",
"QUERY_BUFFER"..0x9192
)
IntConstant(
"""
Accepted by the {@code pname} parameter of #GetBooleanv(), #GetIntegerv(), #GetFloatv(),
and #GetDoublev().
""",
"QUERY_BUFFER_BINDING"..0x9193
)
IntConstant(
"Accepted in the {@code barriers} bitfield in #MemoryBarrier().",
"QUERY_BUFFER_BARRIER_BIT"..0x00008000
)
// ARB_texture_mirror_clamp_to_edge
IntConstant(
"""
Accepted by the {@code param} parameter of TexParameter{if}, SamplerParameter{if} and SamplerParameter{if}v, and by the {@code params} parameter of
TexParameter{if}v, TexParameterI{i ui}v and SamplerParameterI{i ui}v when their {@code pname} parameter is #TEXTURE_WRAP_S, #TEXTURE_WRAP_T, or
#TEXTURE_WRAP_R,
""",
"MIRROR_CLAMP_TO_EDGE"..0x8743
)
}
|
bsd-3-clause
|
7cf9bc9156ec4e957e699e2bfc70732a
| 50.062249 | 161 | 0.641104 | 4.63085 | false | false | false | false |
jguerinet/MyMartlet-Android
|
app/src/main/java/ui/transcript/TranscriptActivity.kt
|
2
|
3181
|
/*
* Copyright 2014-2019 Julien Guerinet
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.guerinet.mymartlet.ui.transcript
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.guerinet.mymartlet.R
import com.guerinet.mymartlet.ui.DrawerActivity
import com.guerinet.mymartlet.util.manager.HomepageManager
import com.guerinet.mymartlet.viewmodel.TranscriptViewModel
import com.guerinet.suitcase.coroutines.uiDispatcher
import com.guerinet.suitcase.lifecycle.observe
import com.guerinet.suitcase.log.TimberTag
import kotlinx.android.synthetic.main.activity_transcript.*
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.viewModel
/**
* Shows the user's transcript
* @author Julien Guerinet
* @since 1.0.0
*/
class TranscriptActivity : DrawerActivity(), TimberTag {
override val tag: String = "TranscriptActivity"
override val currentPage = HomepageManager.HomePage.TRANSCRIPT
private val transcriptViewModel by viewModel<TranscriptViewModel>()
private val adapter by lazy { TranscriptAdapter() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_transcript)
list.layoutManager = LinearLayoutManager(this)
list.adapter = adapter
observe(transcriptViewModel.transcript) {
if (it != null) {
cgpa.text = getString(R.string.transcript_CGPA, it.cgpa.toString())
credits.text = getString(R.string.transcript_credits, it.totalCredits.toString())
}
}
observe(transcriptViewModel.semesters) {
adapter.update(it)
}
observe(transcriptViewModel.isToolbarProgressVisible) {
if (it != null) {
toolbarProgress.isVisible = it
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.refresh, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_refresh -> {
refresh()
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun refresh() {
if (!canRefresh()) {
return
}
launch(uiDispatcher) {
val e = transcriptViewModel.refresh()
handleError("Transcript Refresh", e)
}
}
}
|
apache-2.0
|
8928cb69536b271f82dd16e4fafa042f
| 30.49505 | 97 | 0.685948 | 4.616836 | false | false | false | false |
mdanielwork/intellij-community
|
python/python-terminal/src/com/jetbrains/python/sdk/PyVirtualEnvTerminalCustomizer.kt
|
1
|
4850
|
// 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.jetbrains.python.sdk
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.options.UnnamedConfigurable
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.EnvironmentUtil
import com.jetbrains.python.run.PyVirtualEnvReader
import com.jetbrains.python.run.findActivateScript
import org.jetbrains.plugins.terminal.LocalTerminalCustomizer
import java.io.File
import javax.swing.JCheckBox
/**
* @author traff
*/
class PyVirtualEnvTerminalCustomizer : LocalTerminalCustomizer() {
override fun customizeCommandAndEnvironment(project: Project,
command: Array<out String>,
envs: MutableMap<String, String>): Array<out String> {
val sdk: Sdk? = findSdk(project)
if (sdk != null && (PythonSdkType.isVirtualEnv(sdk) || PythonSdkType.isCondaVirtualEnv(
sdk)) && PyVirtualEnvTerminalSettings.getInstance(project).virtualEnvActivate) {
// in case of virtualenv sdk on unix we activate virtualenv
val path = sdk.homePath
if (path != null) {
val shellPath = command[0]
val shellName = File(shellPath).name
if (shellName == "bash" || (SystemInfo.isMac && shellName == "sh") || (shellName == "zsh") ||
((shellName == "fish"))) { //fish shell works only for virtualenv and not for conda
//for bash we pass activate script to jediterm shell integration (see jediterm-bash.in) to source it there
//TODO: fix conda for fish
findActivateScript(path, shellPath)?.let { activate ->
val pathEnv = EnvironmentUtil.getEnvironmentMap().get("PATH")
if (pathEnv != null) {
envs.put("PATH", pathEnv)
}
envs.put("JEDITERM_SOURCE", activate.first)
envs.put("JEDITERM_SOURCE_ARGS", activate.second?:"")
}
}
else {
//for other shells we read envs from activate script by the default shell and pass them to the process
val reader = PyVirtualEnvReader(path)
reader.activate?.let {
// we add only envs that are setup by the activate script, because adding other variables from the different shell
// can break the actual shell
envs.putAll(reader.readPythonEnv().mapKeys { k -> k.key.toUpperCase() }.filterKeys { k ->
k in PyVirtualEnvReader.virtualEnvVars
})
}
}
}
}
// for some reason virtualenv isn't activated in the rcfile for the login shell, so we make it non-login
return command.filter { arg -> arg != "--login" && arg != "-l" }.toTypedArray()
}
private fun findSdk(project: Project): Sdk? {
for (m in ModuleManager.getInstance(project).modules) {
val sdk: Sdk? = PythonSdkType.findPythonSdk(m)
if (sdk != null && !PythonSdkType.isRemote(sdk)) {
return sdk
}
}
return null
}
override fun getDefaultFolder(project: Project): String? {
return null
}
override fun getConfigurable(project: Project): UnnamedConfigurable = object : UnnamedConfigurable {
val settings = PyVirtualEnvTerminalSettings.getInstance(project)
var myCheckbox: JCheckBox = JCheckBox("Activate virtualenv")
override fun createComponent() = myCheckbox
override fun isModified() = myCheckbox.isSelected != settings.virtualEnvActivate
override fun apply() {
settings.virtualEnvActivate = myCheckbox.isSelected
}
override fun reset() {
myCheckbox.isSelected = settings.virtualEnvActivate
}
}
}
class SettingsState {
var virtualEnvActivate: Boolean = true
}
@State(name = "PyVirtualEnvTerminalCustomizer", storages = [(Storage("python-terminal.xml"))])
class PyVirtualEnvTerminalSettings : PersistentStateComponent<SettingsState> {
var myState: SettingsState = SettingsState()
var virtualEnvActivate: Boolean
get() = myState.virtualEnvActivate
set(value) {
myState.virtualEnvActivate = value
}
override fun getState(): SettingsState = myState
override fun loadState(state: SettingsState) {
myState.virtualEnvActivate = state.virtualEnvActivate
}
companion object {
fun getInstance(project: Project): PyVirtualEnvTerminalSettings {
return ServiceManager.getService(project, PyVirtualEnvTerminalSettings::class.java)
}
}
}
|
apache-2.0
|
9e0fe4e69c8b3eb1e855745e1ee68358
| 34.144928 | 140 | 0.687216 | 4.787759 | false | false | false | false |
tateisu/SubwayTooter
|
app/src/main/java/jp/juggler/subwaytooter/actmain/TabletColumnPagerAdapter.kt
|
1
|
1242
|
package jp.juggler.subwaytooter.actmain
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import jp.juggler.subwaytooter.ActMain
import jp.juggler.subwaytooter.columnviewholder.TabletColumnViewHolder
internal class TabletColumnPagerAdapter(
private val activity: ActMain,
) : RecyclerView.Adapter<TabletColumnViewHolder>() {
var columnWidth: Int = 0 // dividerの幅を含まない
private val appState = activity.appState
override fun getItemCount(): Int = appState.columnCount
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TabletColumnViewHolder =
TabletColumnViewHolder(activity, parent)
override fun onBindViewHolder(holder: TabletColumnViewHolder, position: Int) {
val columnWidth = this.columnWidth
if (columnWidth > 0) {
val lp = holder.itemView.layoutParams
lp.width = columnWidth
holder.itemView.layoutParams = lp
}
holder.bind(appState.column(position)!!, position, appState.columnCount)
}
override fun onViewRecycled(holder: TabletColumnViewHolder) {
super.onViewRecycled(holder)
holder.onViewRecycled()
}
}
|
apache-2.0
|
feb3536d49a8460711395679500ad9a2
| 32.111111 | 95 | 0.711726 | 5.159664 | false | false | false | false |
DreierF/MyTargets
|
app/src/main/java/de/dreier/mytargets/base/db/migrations/Migration24.kt
|
1
|
5425
|
/*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.base.db.migrations
import androidx.sqlite.db.SupportSQLiteDatabase
import androidx.room.migration.Migration
object Migration24 : Migration(23, 24) {
override fun migrate(database: SupportSQLiteDatabase) {
// Add signature table
database.execSQL(
"CREATE TABLE IF NOT EXISTS `Signature`( " +
"`_id` INTEGER PRIMARY KEY AUTOINCREMENT, " +
"`name` TEXT, " +
"`bitmap` BLOB" +
")"
)
// Rename existing tables
database.execSQL("ALTER TABLE `Shot` RENAME TO SHOT_OLD")
database.execSQL("ALTER TABLE `End` RENAME TO END_OLD")
database.execSQL("ALTER TABLE `Training` RENAME TO TRAINING_OLD")
// Training migration
database.execSQL(
"CREATE TABLE IF NOT EXISTS `Training`( " +
"`_id` INTEGER PRIMARY KEY AUTOINCREMENT, " +
"`title` TEXT, " +
"`date` TEXT, " +
"`standardRound` INTEGER, " +
"`bow` INTEGER, " +
"`arrow` INTEGER, " +
"`arrowNumbering` INTEGER, " +
"`indoor` INTEGER, " +
"`weather` INTEGER, " +
"`windDirection` INTEGER, " +
"`windSpeed` INTEGER, " +
"`location` TEXT, " +
"`comment` TEXT, " +
"`archerSignature` INTEGER, " +
"`witnessSignature` INTEGER, " +
"FOREIGN KEY(`standardRound`) REFERENCES StandardRound(`_id`) ON UPDATE NO ACTION ON DELETE SET NULL, " +
"FOREIGN KEY(`bow`) REFERENCES Bow(`_id`) ON UPDATE NO ACTION ON DELETE SET NULL, " +
"FOREIGN KEY(`arrow`) REFERENCES Arrow(`_id`) ON UPDATE NO ACTION ON DELETE SET NULL, " +
"FOREIGN KEY(`archerSignature`) REFERENCES Signature(`_id`) ON UPDATE NO ACTION ON DELETE SET NULL, " +
"FOREIGN KEY(`witnessSignature`) REFERENCES Signature(`_id`) ON UPDATE NO ACTION ON DELETE SET NULL " +
")"
)
database.execSQL(
"INSERT INTO `Training` " +
"SELECT `_id`, `title`, date(`date`/1000, 'unixepoch', 'localtime'), " +
"`standardRound`, `bow`, `arrow`, " +
"`arrowNumbering`, `indoor`, " +
"`weather`, `windDirection`, `windSpeed`, `location`, '', NULL, NULL " +
"FROM TRAINING_OLD"
)
database.execSQL("UPDATE Round SET comment = \"\" WHERE comment = NULL")
database.execSQL("UPDATE Round SET targetDiameter = \"-1 m\" WHERE targetDiameter = NULL")
database.execSQL("UPDATE RoundTemplate SET targetDiameter = \"-1 m\" WHERE targetDiameter = NULL")
// End migration
database.execSQL(
"CREATE TABLE IF NOT EXISTS `End`( " +
"`_id` INTEGER PRIMARY KEY AUTOINCREMENT, " +
"`index` INTEGER, " +
"`round` INTEGER, " +
"`exact` INTEGER, " +
"`saveTime` TEXT, " +
"`comment` TEXT, " +
"FOREIGN KEY(`round`) REFERENCES Round(`_id`) ON UPDATE NO ACTION ON DELETE CASCADE " +
")"
)
database.execSQL(
"INSERT INTO `End` " +
"SELECT e.`_id`, e.`index`, e.`round`, e.`exact`, time(e.`saveTime`/1000, 'unixepoch', 'localtime'), " +
"TRIM(GROUP_CONCAT(s.`comment`, x'0a'), x'0a' || \" \") " +
"FROM END_OLD e LEFT OUTER JOIN SHOT_OLD s ON s.`end`=e._id " +
"GROUP BY e._id"
)
database.execSQL(
"CREATE TABLE IF NOT EXISTS `Shot`( " +
"`_id` INTEGER PRIMARY KEY AUTOINCREMENT, " +
"`index` INTEGER, " +
"`end` INTEGER, " +
"`x` REAL, " +
"`y` REAL, " +
"`scoringRing` INTEGER, " +
"`arrowNumber` TEXT, " +
"FOREIGN KEY(`end`) REFERENCES End(`_id`) ON UPDATE NO ACTION ON DELETE CASCADE " +
")"
)
database.execSQL(
"INSERT INTO `Shot` " +
"SELECT `_id`,`index`,`end`,`x`,`y`,`scoringRing`,`arrowNumber` " +
"FROM SHOT_OLD"
)
// Remove old tables
database.execSQL("DROP TABLE SHOT_OLD")
database.execSQL("DROP TABLE END_OLD")
database.execSQL("DROP TABLE TRAINING_OLD")
// Add max arrow number
database.execSQL("ALTER TABLE `Arrow` ADD COLUMN maxArrowNumber INTEGER")
database.execSQL("UPDATE `Arrow` SET maxArrowNumber = 12")
}
}
|
gpl-2.0
|
8f971b0458196abcdb3481a9e79d2748
| 44.208333 | 125 | 0.510783 | 4.68885 | false | false | false | false |
paplorinc/intellij-community
|
plugins/stats-collector/src/com/intellij/stats/personalization/impl/UserFactorsManagerImpl.kt
|
1
|
4087
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.stats.personalization.impl
import com.intellij.codeInsight.completion.CompletionType
import com.intellij.completion.FeatureManagerImpl
import com.intellij.openapi.components.ProjectComponent
import com.intellij.openapi.diagnostic.Logger
import com.intellij.stats.personalization.UserFactor
import com.intellij.stats.personalization.UserFactorsManager
import com.jetbrains.completion.feature.BinaryFeature
import com.jetbrains.completion.feature.CategoricalFeature
import com.jetbrains.completion.feature.DoubleFeature
/**
* @author Vitaliy.Bibaev
*/
class UserFactorsManagerImpl : UserFactorsManager, ProjectComponent {
private companion object {
val LOG = Logger.getInstance(UserFactorsManagerImpl::class.java)
}
private val userFactors = mutableMapOf<String, UserFactor>()
init {
if (UserFactorsManager.ENABLE_USER_FACTORS) {
registerAllFactors()
}
}
private fun registerAllFactors() {
// user factors
register(TypedSelectRatio())
register(ExplicitSelectRatio())
register(LookupCancelledRatio())
register(CompletionTypeRatio(CompletionType.BASIC))
register(CompletionTypeRatio(CompletionType.SMART))
register(CompletionTypeRatio(CompletionType.CLASS_NAME))
register(TodayCompletionUsageCount())
register(TotalUsageCount())
register(WeekAverageUsageCount())
register(MostFrequentPrefixLength())
register(AveragePrefixLength())
register(AverageSelectedItemPosition())
register(MaxSelectedItemPosition())
register(MostFrequentSelectedItemPosition())
register(AverageTimeBetweenTyping())
register(MnemonicsRatio())
// feature-derived factors
val featureManager = FeatureManagerImpl.getInstance()
featureManager.binaryFactors.forEach(this::registerBinaryFeatureDerivedFactors)
featureManager.doubleFactors.forEach(this::registerDoubleFeatureDerivedFactors)
featureManager.categoricalFactors.forEach(this::registerCategoricalFeatureDerivedFactors)
}
private fun registerBinaryFeatureDerivedFactors(feature: BinaryFeature) {
register(BinaryValueRatio(feature, feature.availableValues.first))
register(BinaryValueRatio(feature, feature.availableValues.second))
}
private fun registerDoubleFeatureDerivedFactors(feature: DoubleFeature) {
register(MaxDoubleFeatureValue(feature))
register(MinDoubleFeatureValue(feature))
register(AverageDoubleFeatureValue(feature))
register(UndefinedDoubleFeatureValueRatio(feature))
register(VarianceDoubleFeatureValue(feature))
}
private fun registerCategoricalFeatureDerivedFactors(feature: CategoricalFeature) {
feature.categories.forEach { register(CategoryRatio(feature, it)) }
register(MostFrequentCategory(feature))
}
override fun getAllFactors(): List<UserFactor> = userFactors.values.toList()
private fun register(factor: UserFactor) {
val old = userFactors.put(factor.id, factor)
if (old != null) {
if (old === factor) {
LOG.warn("The same factor was registered twice")
} else {
LOG.warn("Two different factors with the same id found: id = ${old.id}, " +
"classes = ${listOf(factor.javaClass.canonicalName, old.javaClass.canonicalName)}")
}
}
}
}
|
apache-2.0
|
05a35c0d487c818cf1d2da9399b8de58
| 37.566038 | 107 | 0.726205 | 4.90048 | false | false | false | false |
akhbulatov/wordkeeper
|
app/src/main/java/com/akhbulatov/wordkeeper/presentation/ui/words/WordsViewModel.kt
|
1
|
3966
|
package com.akhbulatov.wordkeeper.presentation.ui.words
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.akhbulatov.wordkeeper.domain.global.models.Word
import com.akhbulatov.wordkeeper.domain.word.WordInteractor
import com.akhbulatov.wordkeeper.presentation.global.mvvm.BaseViewModel
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch
import javax.inject.Inject
class WordsViewModel @Inject constructor(
private val wordInteractor: WordInteractor
) : BaseViewModel() {
private val _viewState = MutableLiveData<ViewState>()
val viewState: LiveData<ViewState> get() = _viewState
private val currentViewState: ViewState
get() = _viewState.value!!
private var loadedWords = listOf<Word>()
init {
_viewState.value = ViewState()
}
fun loadWords() {
viewModelScope.launch {
wordInteractor.getWords()
.onStart { _viewState.value = currentViewState.copy(emptyProgress = true) }
.onEach { _viewState.value = currentViewState.copy(emptyProgress = false) }
.catch {
_viewState.value = currentViewState.copy(
emptyProgress = false,
emptyError = Pair(true, it.message)
)
}
.collect {
loadedWords = it
if (it.isNotEmpty()) {
_viewState.value = currentViewState.copy(
emptyData = false,
emptyError = Pair(false, null),
words = Pair(true, it)
)
} else {
_viewState.value = currentViewState.copy(
emptyData = true,
emptyError = Pair(false, null),
words = Pair(false, it)
)
}
}
}
}
fun onSelectWordCatalogClicked(words: MutableList<Word>, category: String) {
val newWords = words.map { it.copy(category = category) }
viewModelScope.launch {
newWords.forEach { wordInteractor.editWord(it) }
}
}
fun onDeleteWordsClicked(words: List<Word>) {
viewModelScope.launch {
wordInteractor.deleteWords(words)
}
}
fun onSearchWordChanged(query: String) {
viewModelScope.launch {
if (query.isNotBlank()) {
val foundWords = wordInteractor.searchWords(query, loadedWords)
_viewState.value = currentViewState.copy(
emptySearchResult = Pair(foundWords.isEmpty(), query),
words = Pair(true, foundWords)
)
} else {
_viewState.value = currentViewState.copy(
emptySearchResult = Pair(false, null),
words = Pair(true, loadedWords)
)
}
}
}
fun onCloseSearchWordClicked() {
_viewState.value = currentViewState.copy(
emptySearchResult = Pair(false, null),
words = Pair(true, loadedWords)
)
}
fun getWordSortMode(): Word.SortMode = wordInteractor.wordSortMode
fun onSortWordSelected(sortMode: Word.SortMode) {
wordInteractor.wordSortMode = sortMode
loadWords()
}
data class ViewState(
val emptyProgress: Boolean = false,
val emptyData: Boolean = false,
val emptyError: Pair<Boolean, String?> = Pair(false, null),
val emptySearchResult: Pair<Boolean, String?> = Pair(false, null),
val words: Pair<Boolean, List<Word>> = Pair(false, emptyList())
)
}
|
apache-2.0
|
67df6cc2efcb0e3bdd034a074c4c08b6
| 33.789474 | 91 | 0.575139 | 5.065134 | false | false | false | false |
StephenVinouze/AdvancedRecyclerView
|
pagination/src/main/kotlin/com/github/stephenvinouze/advancedrecyclerview/pagination/extensions/Pagination.kt
|
1
|
4309
|
package com.github.stephenvinouze.advancedrecyclerview.pagination.extensions
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.github.stephenvinouze.advancedrecyclerview.core.adapters.RecyclerAdapter
/**
* Created by stephenvinouze on 26/04/16.
*/
/**
* Enable your list to be paginable. Trigger an event to let the user fetch the next page
* Note that pagination will be ignore whether you are using sections. Same if you are using a LayoutManager that does not extend LinearLayoutManager.
* @param threshold The threshold indicating when the pagination is triggered. If 0, will trigger when reaching the bottom of the list. Default is 5. This parameter is optional.
* @param isLoading Indicate in this block whether a pagination is already ongoing. The application should retain a state and apply it in this block.
* @param hasAllItems Indicate in this block if all items has been loaded.
* @param onLoad The pagination has been triggered. You should handle the logic in this block.
*/
fun RecyclerView.enablePagination(
threshold: Int = 5,
isLoading: () -> Boolean,
hasAllItems: () -> Boolean,
onLoad: () -> Unit
) {
layoutManager?.let {
addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val totalCount = it.itemCount
val firstVisible = when (it) {
is LinearLayoutManager -> it.findFirstVisibleItemPosition()
is StaggeredGridLayoutManager -> {
if (it.childCount > 0) it.findFirstVisibleItemPositions(null)[0] else 0
}
else -> throw IllegalStateException("LayourManager should derived either from LinearLayoutManager or StaggeredGridLayoutManager")
}
if (totalCount - childCount <= firstVisible + threshold) {
if (!isLoading() && !hasAllItems()) {
onLoad()
}
}
}
})
}
}
/**
* [JAVA VERSION with abstract class as callback instead of lambdas]
* Enable your list to be paginable. Trigger an event to let the user fetch the next page
* Note that pagination will be ignore whether you are using sections. Same if you are using a LayoutManager that does not extend LinearLayoutManager.
* @param threshold The threshold indicating when the pagination is triggered. If 0, will trigger when reaching the bottom of the list. Default is 5. This parameter is optional.
* @param callback The pagination callback that let you fetch your pages
*/
fun RecyclerView.enablePagination(threshold: Int = 5, callback: PaginationCallback) {
layoutManager?.let {
addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val totalCount = it.itemCount
val firstVisible = when (it) {
is LinearLayoutManager -> it.findFirstVisibleItemPosition()
is StaggeredGridLayoutManager -> {
if (it.childCount > 0) it.findFirstVisibleItemPositions(null)[0] else 0
}
else -> throw IllegalStateException("LayourManager should derived either from LinearLayoutManager or StaggeredGridLayoutManager")
}
if (totalCount - childCount <= firstVisible + threshold) {
if (!callback.isLoading() && !callback.hasAllItems()) {
callback.onLoad()
}
}
}
})
}
}
/**
* Append your items at the end of your list
* @param itemsToAdd The items to be added in your list
*/
fun <T> RecyclerAdapter<T>.appendItems(itemsToAdd: List<T>) {
addItems(itemsToAdd.toMutableList(), items.size)
}
abstract class PaginationCallback {
abstract fun isLoading(): Boolean
abstract fun hasAllItems(): Boolean
abstract fun onLoad()
}
|
apache-2.0
|
2b06bc7c12cbd07360dab1b69cd40f23
| 44.851064 | 177 | 0.660246 | 5.326329 | false | false | false | false |
apoi/quickbeer-next
|
app/src/main/java/quickbeer/android/feature/barcode/BarcodeScannerFragment.kt
|
2
|
8083
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package quickbeer.android.feature.barcode
import android.Manifest.permission.CAMERA
import android.animation.AnimatorInflater
import android.animation.AnimatorSet
import android.content.pm.PackageManager.PERMISSION_GRANTED
import android.hardware.Camera
import android.os.Bundle
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import dagger.hilt.android.AndroidEntryPoint
import java.io.IOException
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import quickbeer.android.R
import quickbeer.android.databinding.BarcodeScannerFragmentBinding
import quickbeer.android.feature.barcode.camera.CameraSource
import quickbeer.android.feature.barcode.detection.BarcodeProcessor
import quickbeer.android.navigation.Destination
import quickbeer.android.ui.base.BaseFragment
import quickbeer.android.util.ktx.setNegativeAction
import quickbeer.android.util.ktx.setPositiveAction
import quickbeer.android.util.ktx.viewBinding
import timber.log.Timber
@AndroidEntryPoint
class BarcodeScannerFragment : BaseFragment(R.layout.barcode_scanner_fragment) {
private val binding by viewBinding(BarcodeScannerFragmentBinding::bind)
private val viewModel by viewModels<BarcodeScannerViewModel>()
private var cameraSource: CameraSource? = null
private lateinit var promptChipAnimator: AnimatorSet
private var scanJob: Job? = null
private val permissionHandler = registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted ->
if (isGranted) setupCamera()
else showRationale()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.toolbar.setNavigationOnClickListener {
closeScanner()
}
binding.graphicOverlay.setOnClickListener {
if (!viewModel.isCameraLive) startCamera()
}
binding.flashButton.setOnClickListener { onFlashPressed() }
}
override fun onStart() {
super.onStart()
if (ContextCompat.checkSelfPermission(requireContext(), CAMERA) != PERMISSION_GRANTED) {
requestPermission()
} else {
setupCamera()
}
}
override fun onPause() {
super.onPause()
viewModel.setScannerState(ScannerState.NotStarted)
stopCameraPreview()
}
override fun onDestroyView() {
super.onDestroyView()
scanJob?.cancel()
scanJob = null
cameraSource?.release()
cameraSource = null
}
private fun requestPermission() {
permissionHandler.launch(CAMERA)
}
private fun showRationale() {
if (ActivityCompat.shouldShowRequestPermissionRationale(requireActivity(), CAMERA)) {
MaterialAlertDialogBuilder(requireActivity())
.setMessage(R.string.permission_explanation)
.setPositiveAction(R.string.action_yes, ::requestPermission)
.setNegativeAction(R.string.action_no) { closeScanner() }
.show()
} else {
MaterialAlertDialogBuilder(requireContext())
.setMessage(R.string.permission_missing)
.setPositiveAction(R.string.action_ok, ::closeScanner)
.show()
}
}
private fun setupCamera() {
val animatorSource = R.animator.bottom_prompt_chip_enter
val animatorSet =
(AnimatorInflater.loadAnimator(requireContext(), animatorSource) as AnimatorSet)
promptChipAnimator = animatorSet.apply { setTarget(binding.bottomPromptChip) }
cameraSource = CameraSource(binding.graphicOverlay)
showPrompt(getString(R.string.prompt_loading_camera))
startCamera()
}
private fun startCamera() {
viewModel.markCameraFrozen()
cameraSource?.setFrameProcessor(BarcodeProcessor(binding.graphicOverlay, viewModel))
viewModel.setScannerState(ScannerState.Detecting)
scanJob?.cancel()
scanJob = lifecycleScope.launch {
viewModel.scan().collect(::handleScannerState)
}
requireView().postDelayed(Runnable(::startCameraPreview), 150)
}
private fun closeScanner() {
requireMainActivity().selectMainTab()
}
private fun onFlashPressed() {
val selected = !binding.flashButton.isSelected
val mode = if (selected) {
Camera.Parameters.FLASH_MODE_TORCH
} else Camera.Parameters.FLASH_MODE_OFF
binding.flashButton.isSelected = selected
cameraSource?.updateFlashMode(mode)
}
private fun startCameraPreview() {
val cameraSource = cameraSource ?: return
if (!viewModel.isCameraLive) {
try {
viewModel.markCameraLive()
binding.cameraPreview.start(cameraSource)
} catch (e: IOException) {
Timber.e(e, "Failed to start camera preview!")
cameraSource.release()
this.cameraSource = null
}
}
}
private fun stopCameraPreview() {
if (viewModel.isCameraLive) {
viewModel.markCameraFrozen()
binding.flashButton.isSelected = false
binding.cameraPreview.stop()
}
}
private fun handleScannerState(state: ScannerState) {
when (state) {
is ScannerState.NotStarted -> Unit
is ScannerState.Detecting -> {
showPrompt(getString(R.string.prompt_point_at_a_barcode))
startCameraPreview()
}
is ScannerState.Confirming -> {
showPrompt(getString(R.string.prompt_move_camera_closer))
startCameraPreview()
}
is ScannerState.Detected -> {
showPrompt(null)
stopCameraPreview()
}
is ScannerState.Searching -> {
showPrompt(getString(R.string.prompt_searching))
stopCameraPreview()
}
is ScannerState.Found -> {
val scanDestination = Destination.Beer(state.beers.first().id)
requireMainActivity().setPendingDestination(scanDestination)
closeScanner()
}
is ScannerState.NotFound -> {
showPrompt(getString(R.string.prompt_no_results).format(state.barcode))
stopCameraPreview()
}
is ScannerState.Error -> {
showPrompt(getString(R.string.prompt_error).format(state.barcode))
stopCameraPreview()
}
}
}
private fun showPrompt(message: String?) {
val promptChip = binding.bottomPromptChip
val wasPromptChipGone = !promptChip.isVisible
message?.let(promptChip::setText)
promptChip.isVisible = message != null
val shouldAnimateChip = wasPromptChipGone && promptChip.isVisible
if (shouldAnimateChip && !promptChipAnimator.isRunning) promptChipAnimator.start()
}
companion object {
private const val PERMISSION_RESULT = 0x500
}
}
|
gpl-3.0
|
59990fd272915337138f45cc64325b08
| 33.25 | 96 | 0.668316 | 5.083648 | false | false | false | false |
JetBrains/intellij-community
|
plugins/kotlin/maven/tests/test/org/jetbrains/kotlin/idea/maven/AbstractKotlinMavenImporterTest.kt
|
1
|
139438
|
// 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.maven
import com.intellij.application.options.CodeStyle
import com.intellij.notification.Notification
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkUtil
import com.intellij.openapi.projectRoots.JavaSdk
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.roots.CompilerModuleExtension
import com.intellij.openapi.roots.LibraryOrderEntry
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.packaging.impl.artifacts.ArtifactUtil
import com.intellij.testFramework.IdeaTestUtil
import com.intellij.util.PathUtil
import com.intellij.util.ThrowableRunnable
import junit.framework.TestCase
import org.jetbrains.idea.maven.execution.MavenRunner
import org.jetbrains.idea.maven.project.MavenWorkspaceSettingsComponent
import org.jetbrains.kotlin.caches.resolve.KotlinCacheService
import org.jetbrains.kotlin.cli.common.arguments.K2JSCompilerArguments
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.config.KotlinFacetSettings
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.config.additionalArgumentsAsList
import org.jetbrains.kotlin.idea.base.platforms.KotlinCommonLibraryKind
import org.jetbrains.kotlin.idea.base.platforms.KotlinJavaScriptLibraryKind
import org.jetbrains.kotlin.idea.base.plugin.artifacts.KotlinArtifacts
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.base.projectStructure.productionSourceInfo
import org.jetbrains.kotlin.idea.base.projectStructure.testSourceInfo
import org.jetbrains.kotlin.idea.caches.resolve.analyzeAndGetResult
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinJpsPluginSettings
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout
import org.jetbrains.kotlin.idea.core.util.toPsiFile
import org.jetbrains.kotlin.idea.facet.KotlinFacet
import org.jetbrains.kotlin.idea.formatter.KotlinObsoleteCodeStyle
import org.jetbrains.kotlin.idea.formatter.KotlinStyleGuideCodeStyle
import org.jetbrains.kotlin.idea.formatter.kotlinCodeStyleDefaults
import org.jetbrains.kotlin.idea.framework.KotlinSdkType
import org.jetbrains.kotlin.idea.macros.KOTLIN_BUNDLED
import org.jetbrains.kotlin.idea.notification.asText
import org.jetbrains.kotlin.idea.notification.catchNotificationText
import org.jetbrains.kotlin.idea.notification.catchNotifications
import org.jetbrains.kotlin.idea.test.resetCodeStyle
import org.jetbrains.kotlin.idea.test.runAll
import org.jetbrains.kotlin.idea.test.waitIndexingComplete
import org.jetbrains.kotlin.platform.*
import org.jetbrains.kotlin.platform.js.JsPlatforms
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.psi.KtFile
import org.junit.Assert
import org.junit.Assert.assertNotEquals
import org.junit.Test
import java.io.File
abstract class AbstractKotlinMavenImporterTest : KotlinMavenImportingTestCase() {
protected val kotlinVersion = "1.1.3"
override fun setUp() {
super.setUp()
createStdProjectFolders()
}
override fun tearDown() = runAll(
ThrowableRunnable { resetCodeStyle(myProject) },
ThrowableRunnable { super.tearDown() },
)
protected fun checkStableModuleName(projectName: String, expectedName: String, platform: TargetPlatform, isProduction: Boolean) {
val module = getModule(projectName)
val moduleInfo = if (isProduction) module.productionSourceInfo else module.testSourceInfo
val resolutionFacade = KotlinCacheService.getInstance(myProject).getResolutionFacadeByModuleInfo(moduleInfo!!, platform)!!
val moduleDescriptor = resolutionFacade.moduleDescriptor
Assert.assertEquals("<$expectedName>", moduleDescriptor.stableName?.asString())
}
protected fun facetSettings(moduleName: String) = KotlinFacet.get(getModule(moduleName))!!.configuration.settings
protected val facetSettings: KotlinFacetSettings
get() = facetSettings("project")
protected fun assertImporterStatePresent() {
assertNotNull("Kotlin importer component is not present", myTestFixture.module.getService(KotlinImporterComponent::class.java))
}
class SimpleKotlinProject5 : AbstractKotlinMavenImporterTest() {
@Test
fun testSimpleKotlinProject() {
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
"""
)
assertModules("project")
assertImporterStatePresent()
assertSources("project", "src/main/java")
assertFalse(ArtifactUtil.areResourceFilesFromSourceRootsCopiedToOutput(getModule("project")))
}
}
class WithSpecifiedSourceRoot : AbstractKotlinMavenImporterTest() {
@Test
fun testWithSpecifiedSourceRoot() {
createProjectSubDir("src/main/kotlin")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
assertSources("project", "src/main/kotlin")
}
}
class WithCustomSourceDirs12 : AbstractKotlinMavenImporterTest() {
@Test
fun testWithCustomSourceDirs() {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<sourceDirs>
<dir>src/main/kotlin</dir>
<dir>src/main/kotlin.jvm</dir>
</sourceDirs>
</configuration>
</execution>
<execution>
<id>test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>test-compile</goal>
</goals>
<configuration>
<sourceDirs>
<dir>src/test/kotlin</dir>
<dir>src/test/kotlin.jvm</dir>
</sourceDirs>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
assertSources("project", "src/main/kotlin", "src/main/kotlin.jvm")
assertTestSources("project", "src/test/java", "src/test/kotlin", "src/test/kotlin.jvm")
}
}
class WithKapt : AbstractKotlinMavenImporterTest() {
@Test
fun testWithKapt() {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>kapt</id>
<goals>
<goal>kapt</goal>
</goals>
<configuration>
<sourceDirs>
<sourceDir>src/main/kotlin</sourceDir>
<sourceDir>src/main/java</sourceDir>
</sourceDirs>
</configuration>
</execution>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<sourceDirs>
<sourceDir>src/main/kotlin</sourceDir>
<sourceDir>src/main/java</sourceDir>
</sourceDirs>
</configuration>
</execution>
<execution>
<id>test-kapt</id>
<goals>
<goal>test-kapt</goal>
</goals>
<configuration>
<sourceDirs>
<sourceDir>src/test/kotlin</sourceDir>
<sourceDir>src/test/java</sourceDir>
</sourceDirs>
</configuration>
</execution>
<execution>
<id>test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>test-compile</goal>
</goals>
<configuration>
<sourceDirs>
<sourceDir>src/test/kotlin</sourceDir>
<sourceDir>src/test/java</sourceDir>
<sourceDir>target/generated-sources/kapt/test</sourceDir>
</sourceDirs>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
assertSources("project", "src/main/java", "src/main/kotlin")
assertTestSources("project", "src/test/java", "src/test/kotlin")
}
}
class ImportOfficialCodeStyle8 : AbstractKotlinMavenImporterTest() {
@Test
fun testImportOfficialCodeStyle() {
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<properties>
<kotlin.code.style>official</kotlin.code.style>
</properties>
"""
)
Assert.assertEquals(
KotlinStyleGuideCodeStyle.CODE_STYLE_ID,
CodeStyle.getSettings(myProject).kotlinCodeStyleDefaults()
)
}
}
class ReImportRemoveDir : AbstractKotlinMavenImporterTest() {
@Test
fun testReImportRemoveDir() {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<sourceDirs>
<dir>src/main/kotlin</dir>
<dir>src/main/kotlin.jvm</dir>
</sourceDirs>
</configuration>
</execution>
<execution>
<id>test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>test-compile</goal>
</goals>
<configuration>
<sourceDirs>
<dir>src/test/kotlin</dir>
<dir>src/test/kotlin.jvm</dir>
</sourceDirs>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
assertSources("project", "src/main/kotlin", "src/main/kotlin.jvm")
assertTestSources("project", "src/test/java", "src/test/kotlin", "src/test/kotlin.jvm")
// reimport
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<sourceDirs>
<dir>src/main/kotlin</dir>
</sourceDirs>
</configuration>
</execution>
<execution>
<id>test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>test-compile</goal>
</goals>
<configuration>
<sourceDirs>
<dir>src/test/kotlin</dir>
<dir>src/test/kotlin.jvm</dir>
</sourceDirs>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
"""
)
assertSources("project", "src/main/kotlin")
assertTestSources("project", "src/test/java", "src/test/kotlin", "src/test/kotlin.jvm")
}
}
class ReImportAddDir : AbstractKotlinMavenImporterTest() {
@Test
fun testReImportAddDir() {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<sourceDirs>
<dir>src/main/kotlin</dir>
</sourceDirs>
</configuration>
</execution>
<execution>
<id>test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>test-compile</goal>
</goals>
<configuration>
<sourceDirs>
<dir>src/test/kotlin</dir>
<dir>src/test/kotlin.jvm</dir>
</sourceDirs>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
assertSources("project", "src/main/kotlin")
assertTestSources("project", "src/test/java", "src/test/kotlin", "src/test/kotlin.jvm")
// reimport
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<sourceDirs>
<dir>src/main/kotlin</dir>
<dir>src/main/kotlin.jvm</dir>
</sourceDirs>
</configuration>
</execution>
<execution>
<id>test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>test-compile</goal>
</goals>
<configuration>
<sourceDirs>
<dir>src/test/kotlin</dir>
<dir>src/test/kotlin.jvm</dir>
</sourceDirs>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
"""
)
assertSources("project", "src/main/kotlin", "src/main/kotlin.jvm")
assertTestSources("project", "src/test/java", "src/test/kotlin", "src/test/kotlin.jvm")
}
}
class JvmFacetConfiguration : AbstractKotlinMavenImporterTest() {
@Test
fun testJvmFacetConfiguration() {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
val kotlinMavenPluginVersion = "1.6.20"
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>$kotlinMavenPluginVersion</version>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
<configuration>
<languageVersion>1.1</languageVersion>
<apiVersion>1.0</apiVersion>
<multiPlatform>true</multiPlatform>
<nowarn>true</nowarn>
<args>
<arg>-Xcoroutines=enable</arg>
</args>
<jvmTarget>1.8</jvmTarget>
<classpath>foobar.jar</classpath>
</configuration>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
with(facetSettings) {
Assert.assertEquals("1.1", languageLevel!!.versionString)
Assert.assertEquals("1.1", compilerArguments!!.languageVersion)
Assert.assertEquals("1.0", apiLevel!!.versionString)
Assert.assertEquals("1.0", compilerArguments!!.apiVersion)
Assert.assertFalse(compilerArguments!!.autoAdvanceLanguageVersion)
Assert.assertFalse(compilerArguments!!.autoAdvanceApiVersion)
Assert.assertEquals(true, compilerArguments!!.suppressWarnings)
Assert.assertEquals("JVM 1.8", targetPlatform!!.oldFashionedDescription)
Assert.assertEquals("1.8", (compilerArguments as K2JVMCompilerArguments).jvmTarget)
Assert.assertEquals("foobar.jar", (compilerArguments as K2JVMCompilerArguments).classpath)
Assert.assertEquals(
"",
compilerSettings!!.additionalArguments
)
}
Assert.assertEquals(kotlinMavenPluginVersion, KotlinJpsPluginSettings.jpsVersion(myProject))
assertSources("project", "src/main/kotlin")
assertTestSources("project", "src/test/java")
assertResources("project", "src/main/resources")
assertTestResources("project", "src/test/resources")
}
}
class JvmFacetConfigurationFromProperties : AbstractKotlinMavenImporterTest() {
@Test
fun testJvmFacetConfigurationFromProperties() {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<properties>
<kotlin.compiler.languageVersion>1.0</kotlin.compiler.languageVersion>
<kotlin.compiler.apiVersion>1.0</kotlin.compiler.apiVersion>
<kotlin.compiler.jvmTarget>1.8</kotlin.compiler.jvmTarget>
</properties>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
with(facetSettings) {
Assert.assertEquals("1.0", languageLevel!!.versionString)
Assert.assertEquals("1.0", compilerArguments!!.languageVersion)
Assert.assertEquals("1.0", apiLevel!!.versionString)
Assert.assertEquals("1.0", compilerArguments!!.apiVersion)
Assert.assertEquals("JVM 1.8", targetPlatform!!.oldFashionedDescription)
Assert.assertEquals("1.8", (compilerArguments as K2JVMCompilerArguments).jvmTarget)
}
assertSources("project", "src/main/kotlin")
assertTestSources("project", "src/test/java")
assertResources("project", "src/main/resources")
assertTestResources("project", "src/test/resources")
}
}
class JsFacetConfiguration : AbstractKotlinMavenImporterTest() {
@Test
fun testJsFacetConfiguration() {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-js</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>js</goal>
</goals>
</execution>
</executions>
<configuration>
<languageVersion>1.1</languageVersion>
<apiVersion>1.0</apiVersion>
<multiPlatform>true</multiPlatform>
<nowarn>true</nowarn>
<args>
<arg>-Xcoroutines=enable</arg>
</args>
<sourceMap>true</sourceMap>
<outputFile>test.js</outputFile>
<metaInfo>true</metaInfo>
<moduleKind>commonjs</moduleKind>
</configuration>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
with(facetSettings) {
Assert.assertEquals("1.1", languageLevel!!.versionString)
Assert.assertEquals("1.1", compilerArguments!!.languageVersion)
Assert.assertEquals("1.0", apiLevel!!.versionString)
Assert.assertEquals("1.0", compilerArguments!!.apiVersion)
Assert.assertFalse(compilerArguments!!.autoAdvanceLanguageVersion)
Assert.assertFalse(compilerArguments!!.autoAdvanceApiVersion)
Assert.assertEquals(true, compilerArguments!!.suppressWarnings)
Assert.assertTrue(targetPlatform.isJs())
with(compilerArguments as K2JSCompilerArguments) {
Assert.assertEquals(true, sourceMap)
Assert.assertEquals("commonjs", moduleKind)
}
Assert.assertEquals(
"-meta-info -output test.js",
compilerSettings!!.additionalArguments
)
}
val rootManager = ModuleRootManager.getInstance(getModule("project"))
val stdlib = rootManager.orderEntries.filterIsInstance<LibraryOrderEntry>().single().library
assertEquals(KotlinJavaScriptLibraryKind, (stdlib as LibraryEx).kind)
Assert.assertTrue(ModuleRootManager.getInstance(getModule("project")).sdk!!.sdkType is KotlinSdkType)
assertKotlinSources("project", "src/main/kotlin")
assertKotlinTestSources("project", "src/test/java")
assertKotlinResources("project", "src/main/resources")
assertKotlinTestResources("project", "src/test/resources")
}
}
class JsCustomOutputPaths : AbstractKotlinMavenImporterTest() {
@Test
fun testJsCustomOutputPaths() {
createProjectSubDirs("src/main/kotlin", "src/test/kotlin")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-js</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>$kotlinVersion</version>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>js</goal>
</goals>
<configuration>
<outputFile>${'$'}{project.basedir}/prod/main.js</outputFile>
</configuration>
</execution>
<execution>
<id>test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>test-js</goal>
</goals>
<configuration>
<outputFile>${'$'}{project.basedir}/test/test.js</outputFile>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
"""
)
assertNotEquals(kotlinVersion, KotlinJpsPluginSettings.jpsVersion(myProject))
Assert.assertEquals(KotlinJpsPluginSettings.fallbackVersionForOutdatedCompiler, KotlinJpsPluginSettings.jpsVersion(myProject))
assertModules("project")
assertImporterStatePresent()
val projectBasePath = myProjectsManager.projects.first().file.parent.path
with(facetSettings) {
Assert.assertEquals(
"$projectBasePath/prod/main.js",
PathUtil.toSystemIndependentName(productionOutputPath)
)
Assert.assertEquals(
"$projectBasePath/test/test.js",
PathUtil.toSystemIndependentName(testOutputPath)
)
}
with(CompilerModuleExtension.getInstance(getModule("project"))!!) {
Assert.assertEquals("$projectBasePath/prod", PathUtil.toSystemIndependentName(compilerOutputUrl))
Assert.assertEquals("$projectBasePath/test", PathUtil.toSystemIndependentName(compilerOutputUrlForTests))
}
}
}
class FacetSplitConfiguration : AbstractKotlinMavenImporterTest() {
@Test
fun testFacetSplitConfiguration() {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<languageVersion>1.1</languageVersion>
<multiPlatform>true</multiPlatform>
<args>
<arg>-Xcoroutines=enable</arg>
</args>
<classpath>foobar.jar</classpath>
</configuration>
</execution>
</executions>
<configuration>
<apiVersion>1.0</apiVersion>
<nowarn>true</nowarn>
<jvmTarget>1.8</jvmTarget>
</configuration>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
with(facetSettings) {
Assert.assertEquals("1.1", languageLevel!!.versionString)
Assert.assertEquals("1.1", compilerArguments!!.languageVersion)
Assert.assertEquals("1.0", apiLevel!!.versionString)
Assert.assertEquals("1.0", compilerArguments!!.apiVersion)
Assert.assertEquals(true, compilerArguments!!.suppressWarnings)
Assert.assertEquals("JVM 1.8", targetPlatform!!.oldFashionedDescription)
Assert.assertEquals("1.8", (compilerArguments as K2JVMCompilerArguments).jvmTarget)
Assert.assertEquals("foobar.jar", (compilerArguments as K2JVMCompilerArguments).classpath)
Assert.assertEquals("", compilerSettings!!.additionalArguments)
}
}
}
class ArgsInFacetInSingleElement : AbstractKotlinMavenImporterTest() {
@Test
fun testArgsInFacetInSingleElement() {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
<configuration>
<args>
-jvm-target 1.8 -Xcoroutines=enable -classpath "c:\program files\jdk1.8"
</args>
</configuration>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
with(facetSettings) {
Assert.assertEquals("JVM 1.8", targetPlatform!!.oldFashionedDescription)
Assert.assertEquals("1.8", (compilerArguments as K2JVMCompilerArguments).jvmTarget)
Assert.assertEquals("c:/program files/jdk1.8", (compilerArguments as K2JVMCompilerArguments).classpath)
}
}
}
class JvmDetectionByGoalWithJvmStdlib6 : AbstractKotlinMavenImporterTest() {
@Test
fun testJvmDetectionByGoalWithJvmStdlib() {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
Assert.assertEquals(JvmPlatforms.jvm6, facetSettings.targetPlatform)
assertSources("project", "src/main/kotlin")
assertTestSources("project", "src/test/java")
assertResources("project", "src/main/resources")
assertTestResources("project", "src/test/resources")
}
}
class JvmDetectionByGoalWithJsStdlib15 : AbstractKotlinMavenImporterTest() {
@Test
fun testJvmDetectionByGoalWithJsStdlib() {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-js</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
Assert.assertEquals(JvmPlatforms.jvm6, facetSettings.targetPlatform)
}
}
class JvmDetectionByGoalWithCommonStdlib : AbstractKotlinMavenImporterTest() {
@Test
fun testJvmDetectionByGoalWithCommonStdlib() {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-common</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
Assert.assertEquals(JvmPlatforms.jvm6, facetSettings.targetPlatform)
assertSources("project", "src/main/kotlin")
assertTestSources("project", "src/test/java")
assertResources("project", "src/main/resources")
assertTestResources("project", "src/test/resources")
}
}
class JsDetectionByGoalWithJsStdlib : AbstractKotlinMavenImporterTest() {
@Test
fun testJsDetectionByGoalWithJsStdlib() {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-js</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<goals>
<goal>js</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<goals>
<goal>test-js</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
Assert.assertTrue(facetSettings.targetPlatform.isJs())
Assert.assertTrue(ModuleRootManager.getInstance(getModule("project")).sdk!!.sdkType is KotlinSdkType)
assertKotlinSources("project", "src/main/kotlin")
assertKotlinTestSources("project", "src/test/java")
assertKotlinResources("project", "src/main/resources")
assertKotlinTestResources("project", "src/test/resources")
}
}
class JsDetectionByGoalWithCommonStdlib15 : AbstractKotlinMavenImporterTest() {
@Test
fun testJsDetectionByGoalWithCommonStdlib() {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-common</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<goals>
<goal>js</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<goals>
<goal>test-js</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
Assert.assertTrue(facetSettings.targetPlatform.isJs())
Assert.assertTrue(ModuleRootManager.getInstance(getModule("project")).sdk!!.sdkType is KotlinSdkType)
assertKotlinSources("project", "src/main/kotlin")
assertKotlinTestSources("project", "src/test/java")
assertKotlinResources("project", "src/main/resources")
assertKotlinTestResources("project", "src/test/resources")
}
}
class JsAndCommonStdlibKinds : AbstractKotlinMavenImporterTest() {
@Test
fun testJsAndCommonStdlibKinds() {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-common</artifactId>
<version>$kotlinVersion</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-js</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<goals>
<goal>js</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<goals>
<goal>test-js</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
Assert.assertTrue(facetSettings.targetPlatform.isJs())
val rootManager = ModuleRootManager.getInstance(getModule("project"))
val libraries = rootManager.orderEntries.filterIsInstance<LibraryOrderEntry>().map { it.library as LibraryEx }
assertEquals(KotlinJavaScriptLibraryKind, libraries.single { it.name?.contains("kotlin-stdlib-js") == true }.kind)
assertEquals(KotlinCommonLibraryKind, libraries.single { it.name?.contains("kotlin-stdlib-common") == true }.kind)
assertKotlinSources("project", "src/main/kotlin")
assertKotlinTestSources("project", "src/test/java")
assertKotlinResources("project", "src/main/resources")
assertKotlinTestResources("project", "src/test/resources")
}
}
class CommonDetectionByGoalWithJvmStdlib1164 : AbstractKotlinMavenImporterTest() {
@Test
fun testCommonDetectionByGoalWithJvmStdlib() {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<goals>
<goal>metadata</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
Assert.assertTrue(facetSettings.targetPlatform.isCommon())
Assert.assertTrue(ModuleRootManager.getInstance(getModule("project")).sdk!!.sdkType is KotlinSdkType)
assertKotlinSources("project", "src/main/kotlin")
assertKotlinTestSources("project", "src/test/java")
assertKotlinResources("project", "src/main/resources")
assertKotlinTestResources("project", "src/test/resources")
}
}
class CommonDetectionByGoalWithCommonStdlib : AbstractKotlinMavenImporterTest() {
@Test
fun testCommonDetectionByGoalWithCommonStdlib() {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
importProject(
"""
<groupId>test</groupId>0
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-common</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<goals>
<goal>metadata</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
Assert.assertTrue(facetSettings.targetPlatform.isCommon())
val rootManager = ModuleRootManager.getInstance(getModule("project"))
val stdlib = rootManager.orderEntries.filterIsInstance<LibraryOrderEntry>().single().library
assertEquals(KotlinCommonLibraryKind, (stdlib as LibraryEx).kind)
Assert.assertTrue(ModuleRootManager.getInstance(getModule("project")).sdk!!.sdkType is KotlinSdkType)
assertKotlinSources("project", "src/main/kotlin")
assertKotlinTestSources("project", "src/test/java")
assertKotlinResources("project", "src/main/resources")
assertKotlinTestResources("project", "src/test/resources")
}
}
class JvmDetectionByConflictingGoalsAndJvmStdlib : AbstractKotlinMavenImporterTest() {
@Test
fun testJvmDetectionByConflictingGoalsAndJvmStdlib() {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<goals>
<goal>js</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
Assert.assertEquals(JvmPlatforms.jvm6, facetSettings.targetPlatform)
assertKotlinSources("project", "src/main/kotlin")
assertKotlinTestSources("project", "src/test/java")
assertKotlinResources("project", "src/main/resources")
assertKotlinTestResources("project", "src/test/resources")
}
}
class JsDetectionByConflictingGoalsAndJsStdlib : AbstractKotlinMavenImporterTest() {
@Test
fun testJsDetectionByConflictingGoalsAndJsStdlib() {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-js</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<goals>
<goal>js</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
Assert.assertTrue(facetSettings.targetPlatform.isJs())
assertKotlinSources("project", "src/main/kotlin")
assertKotlinTestSources("project", "src/test/java")
assertKotlinResources("project", "src/main/resources")
assertKotlinTestResources("project", "src/test/resources")
}
}
class CommonDetectionByConflictingGoalsAndCommonStdlib : AbstractKotlinMavenImporterTest() {
@Test
fun testCommonDetectionByConflictingGoalsAndCommonStdlib() {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-common</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<goals>
<goal>js</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
Assert.assertTrue(facetSettings.targetPlatform.isCommon())
assertKotlinSources("project", "src/main/kotlin")
assertKotlinTestSources("project", "src/test/java")
assertKotlinResources("project", "src/main/resources")
assertKotlinTestResources("project", "src/test/resources")
}
}
class NoArgInvokeInitializers : AbstractKotlinMavenImporterTest() {
@Test
fun testNoArgInvokeInitializers() {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<goals>
<goal>js</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-noarg</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<configuration>
<compilerPlugins>
<plugin>no-arg</plugin>
</compilerPlugins>
<pluginOptions>
<option>no-arg:annotation=NoArg</option>
<option>no-arg:invokeInitializers=true</option>
</pluginOptions>
</configuration>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
with(facetSettings) {
Assert.assertEquals(
"",
compilerSettings!!.additionalArguments
)
Assert.assertEquals(
listOf(
"plugin:org.jetbrains.kotlin.noarg:annotation=NoArg",
"plugin:org.jetbrains.kotlin.noarg:invokeInitializers=true"
),
compilerArguments!!.pluginOptions!!.toList()
)
}
}
}
class ArgsOverridingInFacet : AbstractKotlinMavenImporterTest() {
@Test
fun testArgsOverridingInFacet() {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
<configuration>
<jvmTarget>1.8</jvmTarget>
<languageVersion>1.0</languageVersion>
<apiVersion>1.0</apiVersion>
<args>
<arg>-jvm-target</arg>
<arg>11</arg>
<arg>-language-version</arg>
<arg>1.1</arg>
<arg>-api-version</arg>
<arg>1.1</arg>
</args>
</configuration>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
with(facetSettings) {
Assert.assertEquals("JVM 11", targetPlatform!!.oldFashionedDescription)
Assert.assertEquals(LanguageVersion.KOTLIN_1_1.description, languageLevel!!.description)
Assert.assertEquals(LanguageVersion.KOTLIN_1_1.description, apiLevel!!.description)
Assert.assertEquals("11", (compilerArguments as K2JVMCompilerArguments).jvmTarget)
}
}
}
class SubmoduleArgsInheritance : AbstractKotlinMavenImporterTest() {
@Test
fun testSubmoduleArgsInheritance() {
createProjectSubDirs("src/main/kotlin", "myModule1/src/main/kotlin", "myModule2/src/main/kotlin", "myModule3/src/main/kotlin")
val mainPom = createProjectPom(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<packaging>pom</packaging>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
<configuration>
<jvmTarget>1.7</jvmTarget>
<languageVersion>1.1</languageVersion>
<apiVersion>1.0</apiVersion>
<args>
<arg>-java-parameters</arg>
<arg>-Xdump-declarations-to=dumpDir</arg>
<arg>-kotlin-home</arg>
<arg>temp</arg>
</args>
</configuration>
</plugin>
</plugins>
</build>
"""
)
val modulePom1 = createModulePom(
"myModule1",
"""
<parent>
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
</parent>
<groupId>test</groupId>
<artifactId>myModule1</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>myModule1/src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
<configuration>
<jvmTarget>1.8</jvmTarget>
<args>
<arg>-Xdump-declarations-to=dumpDir2</arg>
</args>
</configuration>
</plugin>
</plugins>
</build>
"""
)
val modulePom2 = createModulePom(
"myModule2",
"""
<parent>
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
</parent>
<groupId>test</groupId>
<artifactId>myModule2</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>myModule2/src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
<configuration>
<jvmTarget>1.8</jvmTarget>
<args combine.children="append">
<arg>-kotlin-home</arg>
<arg>temp2</arg>
</args>
</configuration>
</plugin>
</plugins>
</build>
"""
)
val modulePom3 = createModulePom(
"myModule3",
"""
<parent>
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
</parent>
<groupId>test</groupId>
<artifactId>myModule3</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>myModule3/src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
<configuration combine.self="override">
<jvmTarget>1.8</jvmTarget>
<args>
<arg>-kotlin-home</arg>
<arg>temp2</arg>
</args>
</configuration>
</plugin>
</plugins>
</build>
"""
)
importProjects(mainPom, modulePom1, modulePom2, modulePom3)
assertModules("project", "myModule1", "myModule2", "myModule3")
assertImporterStatePresent()
with(facetSettings("myModule1")) {
Assert.assertEquals("JVM 1.8", targetPlatform!!.oldFashionedDescription)
Assert.assertEquals(LanguageVersion.KOTLIN_1_1, languageLevel!!)
Assert.assertEquals(LanguageVersion.KOTLIN_1_0, apiLevel!!)
Assert.assertEquals("1.8", (compilerArguments as K2JVMCompilerArguments).jvmTarget)
Assert.assertEquals(
listOf("-Xdump-declarations-to=dumpDir2"),
compilerSettings!!.additionalArgumentsAsList
)
}
with(facetSettings("myModule2")) {
Assert.assertEquals("JVM 1.8", targetPlatform!!.oldFashionedDescription)
Assert.assertEquals(LanguageVersion.KOTLIN_1_1, languageLevel!!)
Assert.assertEquals(LanguageVersion.KOTLIN_1_0, apiLevel!!)
Assert.assertEquals("1.8", (compilerArguments as K2JVMCompilerArguments).jvmTarget)
Assert.assertEquals(
listOf("-Xdump-declarations-to=dumpDir", "-java-parameters", "-kotlin-home", "temp2"),
compilerSettings!!.additionalArgumentsAsList
)
}
with(facetSettings("myModule3")) {
Assert.assertEquals("JVM 1.8", targetPlatform!!.oldFashionedDescription)
Assert.assertEquals(KotlinPluginLayout.standaloneCompilerVersion.languageVersion, languageLevel)
Assert.assertEquals(LanguageVersion.KOTLIN_1_1, apiLevel)
Assert.assertEquals("1.8", (compilerArguments as K2JVMCompilerArguments).jvmTarget)
Assert.assertEquals(
listOf("-kotlin-home", "temp2"),
compilerSettings!!.additionalArgumentsAsList
)
}
}
}
class JpsCompilerMultiModule : AbstractKotlinMavenImporterTest() {
override fun runInDispatchThread(): Boolean {
return false
}
@Test
fun testJpsCompilerMultiModule() {
createProjectSubDirs(
"src/main/kotlin",
"module1/src/main/kotlin",
"module2/src/main/kotlin",
)
val kotlinMainPluginVersion = "1.5.10"
val kotlinMavenPluginVersion1 = "1.6.21"
val kotlinMavenPluginVersion2 = "1.5.31"
val notifications = catchNotifications(myProject) {
val mainPom = createProjectPom(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<packaging>pom</packaging>
<modules>
<module>module1</module>
<module>module2</module>
</modules>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>$kotlinMainPluginVersion</version>
</plugin>
</plugins>
</build>
"""
)
val module1 = createModulePom(
"module1",
"""
<parent>
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
</parent>
<groupId>test</groupId>
<artifactId>module1</artifactId>
<version>1.0.0</version>
<build>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>$kotlinMavenPluginVersion1</version>
</plugin>
</plugins>
</build>
"""
)
val module2 = createModulePom(
"module2",
"""
<parent>
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
</parent>
<groupId>test</groupId>
<artifactId>module2</artifactId>
<version>1.0.0</version>
<build>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>$kotlinMavenPluginVersion2</version>
</plugin>
</plugins>
</build>
"""
)
importProjects(mainPom, module1, module2)
}
assertModules("project", "module1", "module2")
assertImporterStatePresent()
assertEquals("", notifications.asText())
// The highest of available versions should be picked
assertEquals(kotlinMavenPluginVersion1, KotlinJpsPluginSettings.jpsVersion(myProject))
}
}
class JpsCompiler : AbstractKotlinMavenImporterTest() {
@Test
fun testJpsCompilerUnsupportedVersionDown() {
val version = "1.1.0"
val notifications = catchNotifications(myProject) {
doUnsupportedVersionTest(version, KotlinJpsPluginSettings.fallbackVersionForOutdatedCompiler)
}
val notification = notifications.find { it.title == "Unsupported Kotlin JPS plugin version" }
assertNotNull(notifications.asText(), notification)
assertEquals(
notification?.content,
"Version (${KotlinJpsPluginSettings.fallbackVersionForOutdatedCompiler}) of the Kotlin JPS plugin will be used<br>" +
"The reason: Kotlin JPS compiler minimum supported version is '${KotlinJpsPluginSettings.jpsMinimumSupportedVersion}' but '$version' is specified",
)
}
@Test
fun testJpsCompilerUnsupportedVersionUp() {
val maxVersion = KotlinJpsPluginSettings.jpsMaximumSupportedVersion
val versionToImport = KotlinVersion(maxVersion.major, maxVersion.minor, maxVersion.minor + 1)
val text = catchNotificationText(myProject) {
doUnsupportedVersionTest(versionToImport.toString())
}
assertEquals(
"Version (${KotlinJpsPluginSettings.rawBundledVersion}) of the Kotlin JPS plugin will be used<br>" +
"The reason: Kotlin JPS compiler maximum supported version is '$maxVersion' but '$versionToImport' is specified",
text
)
}
private fun doUnsupportedVersionTest(version: String, expectedFallbackVersion: String = KotlinJpsPluginSettings.rawBundledVersion) {
createProjectSubDirs("src/main/kotlin")
val mainPom = createProjectPom(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<packaging>pom</packaging>
<modules>
<module>module1</module>
<module>module2</module>
</modules>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>$version</version>
</plugin>
</plugins>
</build>
"""
)
importProjects(mainPom)
assertModules("project")
assertImporterStatePresent()
// Fallback to bundled to unsupported version
assertNotEquals(version, KotlinJpsPluginSettings.jpsVersion(myProject))
assertEquals(expectedFallbackVersion, KotlinJpsPluginSettings.jpsVersion(myProject))
}
@Test
fun testDontShowNotificationWhenBuildIsDelegatedToMaven() {
val isBuildDelegatedToMaven = MavenRunner.getInstance(myProject).settings.isDelegateBuildToMaven
MavenRunner.getInstance(myProject).settings.isDelegateBuildToMaven = true
try {
val version = "1.1.0"
val notifications = catchNotifications(myProject) {
doUnsupportedVersionTest(version, KotlinJpsPluginSettings.fallbackVersionForOutdatedCompiler)
}
assertNull(notifications.find { it.title == "Unsupported Kotlin JPS plugin version" })
} finally {
MavenRunner.getInstance(myProject).settings.isDelegateBuildToMaven = isBuildDelegatedToMaven
}
}
}
class MultiModuleImport : AbstractKotlinMavenImporterTest() {
@Test
fun testMultiModuleImport() {
createProjectSubDirs(
"src/main/kotlin",
"my-common-module/src/main/kotlin",
"my-jvm-module/src/main/kotlin",
"my-js-module/src/main/kotlin"
)
val mainPom = createProjectPom(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<packaging>pom</packaging>
<modules>
<module>my-common-module</module>
<module>my-jvm-module</module>
<module>my-js-module</module>
</modules>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>$kotlinVersion</version>
</plugin>
</plugins>
</build>
"""
)
val commonModule1 = createModulePom(
"my-common-module1",
"""
<parent>
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
</parent>
<groupId>test</groupId>
<artifactId>my-common-module1</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-common</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>meta</id>
<phase>compile</phase>
<goals>
<goal>metadata</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
"""
)
val commonModule2 = createModulePom(
"my-common-module2",
"""
<parent>
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
</parent>
<groupId>test</groupId>
<artifactId>my-common-module2</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-common</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>meta</id>
<phase>compile</phase>
<goals>
<goal>metadata</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
"""
)
val jvmModule = createModulePom(
"my-jvm-module",
"""
<parent>
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
</parent>
<groupId>test</groupId>
<artifactId>my-jvm-module</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
<dependency>
<groupId>test</groupId>
<artifactId>my-common-module1</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>test</groupId>
<artifactId>my-common-module2</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
"""
)
val jsModule = createModulePom(
"my-js-module",
"""
<parent>
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
</parent>
<groupId>test</groupId>
<artifactId>my-js-module</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-js</artifactId>
<version>$kotlinVersion</version>
</dependency>
<dependency>
<groupId>test</groupId>
<artifactId>my-common-module1</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>js</id>
<phase>compile</phase>
<goals>
<goal>js</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
"""
)
importProjects(mainPom, commonModule1, commonModule2, jvmModule, jsModule)
assertModules("project", "my-common-module1", "my-common-module2", "my-jvm-module", "my-js-module")
assertImporterStatePresent()
with(facetSettings("my-common-module1")) {
Assert.assertEquals(CommonPlatforms.defaultCommonPlatform, targetPlatform)
}
with(facetSettings("my-common-module2")) {
Assert.assertEquals(CommonPlatforms.defaultCommonPlatform, targetPlatform)
}
with(facetSettings("my-jvm-module")) {
Assert.assertEquals(JvmPlatforms.jvm6, targetPlatform)
Assert.assertEquals(listOf("my-common-module1", "my-common-module2"), implementedModuleNames)
}
with(facetSettings("my-js-module")) {
Assert.assertEquals(JsPlatforms.defaultJsPlatform, targetPlatform)
Assert.assertEquals(listOf("my-common-module1"), implementedModuleNames)
}
}
}
class ProductionOnTestDependency : AbstractKotlinMavenImporterTest() {
@Test
fun testProductionOnTestDependency() {
createProjectSubDirs(
"module-with-java/src/main/java",
"module-with-java/src/test/java",
"module-with-kotlin/src/main/kotlin",
"module-with-kotlin/src/test/kotlin"
)
val dummyFile = createProjectSubFile(
"module-with-kotlin/src/main/kotlin/foo/dummy.kt",
"""
package foo
fun dummy() {
}
""".trimIndent()
)
val pomA = createModulePom(
"module-with-java",
"""
<parent>
<groupId>test-group</groupId>
<artifactId>mvnktest</artifactId>
<version>0.0.0.0-SNAPSHOT</version>
</parent>
<artifactId>module-with-java</artifactId>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
""".trimIndent()
)
val pomB = createModulePom(
"module-with-kotlin",
"""
<parent>
<groupId>test-group</groupId>
<artifactId>mvnktest</artifactId>
<version>0.0.0.0-SNAPSHOT</version>
</parent>
<artifactId>module-with-kotlin</artifactId>
<properties>
<kotlin.version>1.1.4</kotlin.version>
<kotlin.compiler.jvmTarget>1.8</kotlin.compiler.jvmTarget>
<kotlin.compiler.incremental>true</kotlin.compiler.incremental>
</properties>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>${"$"}{kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-runtime</artifactId>
<version>${"$"}{kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
<version>${"$"}{kotlin.version}</version>
</dependency>
<dependency>
<groupId>test-group</groupId>
<artifactId>module-with-java</artifactId>
</dependency>
<dependency>
<groupId>test-group</groupId>
<artifactId>module-with-java</artifactId>
<type>test-jar</type>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${"$"}{kotlin.version}</version>
<executions>
<execution>
<id>compile</id>
<goals> <goal>compile</goal> </goals>
<configuration>
<sourceDirs>
<sourceDir>${"$"}{project.basedir}/src/main/kotlin</sourceDir>
<sourceDir>${"$"}{project.basedir}/src/main/java</sourceDir>
</sourceDirs>
</configuration>
</execution>
<execution>
<id>test-compile</id>
<goals> <goal>test-compile</goal> </goals>
<configuration>
<sourceDirs>
<sourceDir>${"$"}{project.basedir}/src/test/kotlin</sourceDir>
<sourceDir>${"$"}{project.basedir}/src/test/java</sourceDir>
</sourceDirs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<executions>
<!-- Replacing default-compile as it is treated specially by maven -->
<execution>
<id>default-compile</id>
<phase>none</phase>
</execution>
<!-- Replacing default-testCompile as it is treated specially by maven -->
<execution>
<id>default-testCompile</id>
<phase>none</phase>
</execution>
<execution>
<id>java-compile</id>
<phase>compile</phase>
<goals> <goal>compile</goal> </goals>
</execution>
<execution>
<id>java-test-compile</id>
<phase>test-compile</phase>
<goals> <goal>testCompile</goal> </goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
""".trimIndent()
)
val pomMain = createModulePom(
"",
"""
<groupId>test-group</groupId>
<artifactId>mvnktest</artifactId>
<version>0.0.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<kotlin.version>1.1.4</kotlin.version>
<kotlin.compiler.jvmTarget>1.8</kotlin.compiler.jvmTarget>
<kotlin.compiler.incremental>true</kotlin.compiler.incremental>
</properties>
<modules>
<module>module-with-java</module>
<module>module-with-kotlin</module>
</modules>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>test-group</groupId>
<artifactId>module-with-kotlin</artifactId>
<version>${"$"}{project.version}</version>
</dependency>
<dependency>
<groupId>test-group</groupId>
<artifactId>module-with-java</artifactId>
<version>${"$"}{project.version}</version>
</dependency>
<dependency>
<groupId>test-group</groupId>
<artifactId>module-with-java</artifactId>
<version>${"$"}{project.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
</dependencies>
</dependencyManagement>
""".trimIndent()
)
importProjects(pomMain, pomA, pomB)
myProject.waitIndexingComplete()
assertModules("module-with-kotlin", "module-with-java", "mvnktest")
val dependencies = (dummyFile.toPsiFile(myProject) as KtFile).analyzeAndGetResult().moduleDescriptor.allDependencyModules
TestCase.assertTrue(dependencies.any { it.name.asString() == "<production sources for module module-with-java>" })
TestCase.assertTrue(dependencies.any { it.name.asString() == "<test sources for module module-with-java>" })
}
}
class NoArgDuplication6 : AbstractKotlinMavenImporterTest() {
@Test
fun testNoArgDuplication() {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
<configuration>
<args>
<arg>-Xjsr305=strict</arg>
</args>
</configuration>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
with(facetSettings) {
Assert.assertEquals("-Xjsr305=strict", compilerSettings!!.additionalArguments)
}
}
}
class InternalArgumentsFacetImporting8 : AbstractKotlinMavenImporterTest() {
@Test
fun testInternalArgumentsFacetImporting() {
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
<configuration>
<languageVersion>1.2</languageVersion>
<args>
<arg>-XXLanguage:+InlineClasses</arg>
</args>
<jvmTarget>1.8</jvmTarget>
</configuration>
</plugin>
</plugins>
</build>
"""
)
assertImporterStatePresent()
// Check that we haven't lost internal argument during importing to facet
Assert.assertEquals("-XXLanguage:+InlineClasses", facetSettings.compilerSettings?.additionalArguments)
// Check that internal argument influenced LanguageVersionSettings correctly
Assert.assertEquals(
LanguageFeature.State.ENABLED,
getModule("project").languageVersionSettings.getFeatureSupport(LanguageFeature.InlineClasses)
)
}
}
class StableModuleNameWhileUsingMavenJVM : AbstractKotlinMavenImporterTest() {
@Test
fun testStableModuleNameWhileUsingMaven_JVM() {
createProjectSubDirs("src/main/kotlin")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
<configuration>
<languageVersion>1.2</languageVersion>
<jvmTarget>1.8</jvmTarget>
</configuration>
</plugin>
</plugins>
</build>
"""
)
assertImporterStatePresent()
checkStableModuleName("project", "project", JvmPlatforms.unspecifiedJvmPlatform, isProduction = true)
checkStableModuleName("project", "project", JvmPlatforms.unspecifiedJvmPlatform, isProduction = false)
}
}
class ImportObsoleteCodeStyle : AbstractKotlinMavenImporterTest() {
@Test
fun testImportObsoleteCodeStyle() {
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<properties>
<kotlin.code.style>obsolete</kotlin.code.style>
</properties>
"""
)
Assert.assertEquals(
KotlinObsoleteCodeStyle.CODE_STYLE_ID,
CodeStyle.getSettings(myProject).kotlinCodeStyleDefaults()
)
}
}
class JavaParameters20 : AbstractKotlinMavenImporterTest() {
@Test
fun testJavaParameters() {
createProjectSubDirs("src/main/kotlin")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
<configuration>
<javaParameters>true</javaParameters>
</configuration>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
with(facetSettings) {
Assert.assertEquals("-java-parameters", compilerSettings!!.additionalArguments)
Assert.assertTrue((mergedCompilerArguments as K2JVMCompilerArguments).javaParameters)
}
}
}
class ArgsInFacet : AbstractKotlinMavenImporterTest() {
@Test
fun testArgsInFacet() {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
<configuration>
<args>
<arg>-jvm-target</arg>
<arg>1.8</arg>
<arg>-Xcoroutines=enable</arg>
<arg>-classpath</arg>
<arg>c:\program files\jdk1.8</arg>
</args>
</configuration>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
with(facetSettings) {
Assert.assertEquals("JVM 1.8", targetPlatform!!.oldFashionedDescription)
Assert.assertEquals("1.8", (compilerArguments as K2JVMCompilerArguments).jvmTarget)
Assert.assertEquals("c:/program files/jdk1.8", (compilerArguments as K2JVMCompilerArguments).classpath)
}
}
}
class JsDetectionByGoalWithJvmStdlib : AbstractKotlinMavenImporterTest() {
@Test
fun testJsDetectionByGoalWithJvmStdlib() {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<goals>
<goal>js</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<goals>
<goal>test-js</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
Assert.assertTrue(facetSettings.targetPlatform.isJs())
Assert.assertTrue(ModuleRootManager.getInstance(getModule("project")).sdk!!.sdkType is KotlinSdkType)
assertKotlinSources("project", "src/main/kotlin")
assertKotlinTestSources("project", "src/test/java")
assertKotlinResources("project", "src/main/resources")
assertKotlinTestResources("project", "src/test/resources")
}
}
class CommonDetectionByGoalWithJsStdlib24 : AbstractKotlinMavenImporterTest() {
@Test
fun testCommonDetectionByGoalWithJsStdlib() {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-js</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<goals>
<goal>metadata</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
Assert.assertTrue(facetSettings.targetPlatform.isCommon())
Assert.assertTrue(ModuleRootManager.getInstance(getModule("project")).sdk!!.sdkType is KotlinSdkType)
assertKotlinSources("project", "src/main/kotlin")
assertKotlinTestSources("project", "src/test/java")
assertKotlinResources("project", "src/main/resources")
assertKotlinTestResources("project", "src/test/resources")
}
}
class NoPluginsInAdditionalArgs : AbstractKotlinMavenImporterTest() {
@Test
fun testNoPluginsInAdditionalArgs() {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<goals>
<goal>js</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-allopen</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<configuration>
<compilerPlugins>
<plugin>spring</plugin>
</compilerPlugins>
</configuration>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
with(facetSettings) {
Assert.assertEquals(
"",
compilerSettings!!.additionalArguments
)
Assert.assertEquals(
listOf(
"plugin:org.jetbrains.kotlin.allopen:annotation=org.springframework.stereotype.Component",
"plugin:org.jetbrains.kotlin.allopen:annotation=org.springframework.transaction.annotation.Transactional",
"plugin:org.jetbrains.kotlin.allopen:annotation=org.springframework.scheduling.annotation.Async",
"plugin:org.jetbrains.kotlin.allopen:annotation=org.springframework.cache.annotation.Cacheable",
"plugin:org.jetbrains.kotlin.allopen:annotation=org.springframework.boot.test.context.SpringBootTest",
"plugin:org.jetbrains.kotlin.allopen:annotation=org.springframework.validation.annotation.Validated"
),
compilerArguments!!.pluginOptions!!.toList()
)
}
}
}
class JDKImport : AbstractKotlinMavenImporterTest() {
@Test
fun testJDKImport() {
val mockJdk = IdeaTestUtil.getMockJdk18()
runWriteAction(ThrowableRunnable {
ProjectJdkTable.getInstance().addJdk(mockJdk, myTestFixture.testRootDisposable)
ProjectRootManager.getInstance(myProject).projectSdk = mockJdk
})
try {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
MavenWorkspaceSettingsComponent.getInstance(myProject).settings.getImportingSettings().jdkForImporter =
ExternalSystemJdkUtil.USE_INTERNAL_JAVA
val jdkHomePath = mockJdk.homePath
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
<configuration>
<jdkHome>$jdkHomePath</jdkHome>
</configuration>
</plugin>
</plugins>
</build>
"""
)
assertModules("project")
assertImporterStatePresent()
val moduleSDK = ModuleRootManager.getInstance(getModule("project")).sdk!!
Assert.assertTrue(moduleSDK.sdkType is JavaSdk)
Assert.assertEquals("java 1.8", moduleSDK.name)
Assert.assertEquals(jdkHomePath, moduleSDK.homePath)
} finally {
runWriteAction(ThrowableRunnable { ProjectRootManager.getInstance(myProject).projectSdk = null })
}
}
}
class StableModuleNameWhileUsngMavenJS : AbstractKotlinMavenImporterTest() {
@Test
fun testStableModuleNameWhileUsngMaven_JS() {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-js</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>js</goal>
</goals>
</execution>
</executions>
<configuration>
<languageVersion>1.1</languageVersion>
<apiVersion>1.0</apiVersion>
<multiPlatform>true</multiPlatform>
<nowarn>true</nowarn>
<args>
<arg>-Xcoroutines=enable</arg>
</args>
<sourceMap>true</sourceMap>
<outputFile>test.js</outputFile>
<metaInfo>true</metaInfo>
<moduleKind>commonjs</moduleKind>
</configuration>
</plugin>
</plugins>
</build>
"""
)
assertImporterStatePresent()
// Note that we check name induced by '-output-file' -- may be it's not the best
// decision, but we don't have a better one
checkStableModuleName("project", "test", JsPlatforms.defaultJsPlatform, isProduction = true)
checkStableModuleName("project", "test", JsPlatforms.defaultJsPlatform, isProduction = false)
}
}
class JvmTarget6IsImportedAsIs : AbstractKotlinMavenImporterTest() {
@Test
fun testJvmTargetIsImportedAsIs() {
// If version isn't specified then we will fall back to bundled frontend which is already downloaded => Unbundled JPS can be used
val (facet, notifications) = doJvmTarget6Test(version = null)
Assert.assertEquals("JVM 1.6", facet.targetPlatform!!.oldFashionedDescription)
Assert.assertEquals("1.6", (facet.compilerArguments as K2JVMCompilerArguments).jvmTarget)
Assert.assertEquals("", notifications.asText())
}
}
class JvmTarget6IsImported8 : AbstractKotlinMavenImporterTest() {
@Test
fun testJvmTarget6IsImported8() {
// Some version won't be imported into JPS (because it's some milestone version which wasn't published to MC) => explicit
// JPS version during import will be dropped => we will fall back to the bundled JPS =>
// we have to load 1.6 jvmTarget as 1.8 KTIJ-21515
val (facet, notifications) = doJvmTarget6Test("1.6.20-RC")
Assert.assertEquals("JVM 1.8", facet.targetPlatform!!.oldFashionedDescription)
Assert.assertEquals("1.8", (facet.compilerArguments as K2JVMCompilerArguments).jvmTarget)
Assert.assertEquals(
"""
Title: 'Unsupported JVM target 1.6'
Content: 'Maven project uses JVM target 1.6 for Kotlin compilation, which is no longer supported. It has been imported as JVM target 1.8. Consider migrating the project to JVM 1.8.'
""".trimIndent(),
notifications.asText(),
)
}
}
protected fun doJvmTarget6Test(version: String?): Pair<KotlinFacetSettings, List<Notification>> {
createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm")
val notifications = catchNotifications(myProject) {
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>$kotlinVersion</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
${version?.let { "<version>$it</version>" }}
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
<configuration>
<jvmTarget>1.6</jvmTarget>
</configuration>
</plugin>
</plugins>
</build>
"""
)
}
assertModules("project")
assertImporterStatePresent()
return facetSettings to notifications
}
class CompilerPlugins : AbstractKotlinMavenImporterTest() {
@Test
fun testCompilerPlugins() {
importProject(
"""
<groupId>test</groupId>
<artifactId>project</artifactId>
<version>1.0.0</version>
<build>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>$kotlinVersion</version>
<configuration>
<compilerPlugins>
<plugin>kotlinx-serialization</plugin>
<plugin>all-open</plugin>
<plugin>lombok</plugin>
<plugin>jpa</plugin>
<plugin>noarg</plugin>
<plugin>sam-with-receiver</plugin>
</compilerPlugins>
</configuration>
</plugin>
</plugins>
</build>
"""
)
Assert.assertEquals(
"",
facetSettings.compilerSettings!!.additionalArguments
)
assertModules("project")
assertImporterStatePresent()
TestCase.assertEquals(
listOf(
KotlinArtifacts.allopenCompilerPlugin,
KotlinArtifacts.kotlinxSerializationCompilerPlugin,
KotlinArtifacts.lombokCompilerPlugin,
KotlinArtifacts.noargCompilerPlugin,
KotlinArtifacts.samWithReceiverCompilerPlugin,
).map { it.toJpsVersionAgnosticKotlinBundledPath() },
facetSettings.compilerArguments?.pluginClasspaths?.sorted()
)
}
}
}
fun File.toJpsVersionAgnosticKotlinBundledPath(): String {
val kotlincDirectory = KotlinPluginLayout.kotlinc
require(this.startsWith(kotlincDirectory)) { "$this should start with ${kotlincDirectory}" }
return "\$$KOTLIN_BUNDLED\$/${this.relativeTo(kotlincDirectory)}"
}
|
apache-2.0
|
9e1a9278a9ef72409066b69fda6cc3bd
| 38.692001 | 201 | 0.449203 | 6.074936 | false | true | false | false |
JetBrains/intellij-community
|
plugins/markdown/core/src/org/intellij/plugins/markdown/lang/parser/MarkdownParserManager.kt
|
1
|
1997
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.lang.parser
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.util.Key
import org.intellij.markdown.MarkdownElementTypes
import org.intellij.markdown.ast.ASTNode
import org.intellij.markdown.flavours.MarkdownFlavourDescriptor
import org.intellij.markdown.parser.MarkdownParser
import java.util.concurrent.atomic.AtomicReference
@Service
class MarkdownParserManager: Disposable {
private class ParsingResult(
val buffer: CharSequence,
val tree: ASTNode,
val bufferHash: Int = buffer.hashCode()
)
private val lastParsingResult = AtomicReference<ParsingResult?>()
@JvmOverloads
fun parse(buffer: CharSequence, flavour: MarkdownFlavourDescriptor = FLAVOUR): ASTNode {
val info = lastParsingResult.get()
if (info != null && info.bufferHash == buffer.hashCode() && info.buffer == buffer) {
return info.tree
}
val parseResult = MarkdownParser(flavour).parse(
MarkdownElementTypes.MARKDOWN_FILE,
buffer.toString(),
parseInlines = false
)
lastParsingResult.set(ParsingResult(buffer, parseResult))
return parseResult
}
override fun dispose() {
lastParsingResult.set(null)
}
companion object {
@JvmField
@Deprecated("Use MarkdownFile.getFlavour() instead")
val FLAVOUR_DESCRIPTION = Key.create<MarkdownFlavourDescriptor>("Markdown.Flavour")
@JvmField
val FLAVOUR: MarkdownFlavourDescriptor = MarkdownDefaultFlavour()
@JvmStatic
fun getInstance(): MarkdownParserManager {
return service()
}
@JvmStatic
@JvmOverloads
fun parseContent(buffer: CharSequence, flavour: MarkdownFlavourDescriptor = FLAVOUR): ASTNode {
return getInstance().parse(buffer, flavour)
}
}
}
|
apache-2.0
|
4f07c73091ae752c3940ff886c5ac2d7
| 31.209677 | 140 | 0.749624 | 4.559361 | false | false | false | false |
Homes-MinecraftServerMod/Homes
|
src/main/kotlin/com/masahirosaito/spigot/homes/nms/HomesEntity.kt
|
1
|
1207
|
package com.masahirosaito.spigot.homes.nms
import com.masahirosaito.spigot.homes.Configs
import com.masahirosaito.spigot.homes.NMSManager
import com.masahirosaito.spigot.homes.homedata.HomeData
import com.masahirosaito.spigot.homes.toData
import org.bukkit.Chunk
import org.bukkit.Location
import org.bukkit.OfflinePlayer
data class HomesEntity(
val offlinePlayer: OfflinePlayer,
val location: Location,
var homeName: String? = null,
var isPrivate: Boolean = false
) {
var entities: List<NMSEntityArmorStand> = emptyList()
fun isOwner(offlinePlayer: OfflinePlayer): Boolean {
return this.offlinePlayer.uniqueId == offlinePlayer.uniqueId
}
fun toHomeData(): HomeData {
return HomeData(homeName, location.toData(), isPrivate)
}
fun despawnEntities() {
entities.forEach { it.dead() }
}
fun reSpawnEntities() {
despawnEntities()
spawnEntities()
}
fun spawnEntities() {
if (Configs.onHomeDisplay) {
entities = NMSManager.spawn(this)
}
}
fun inChunk(chunk: Chunk): Boolean {
return chunk.x == location.chunk.x && chunk.z == location.chunk.z
}
}
|
apache-2.0
|
fb04fe875889ee4d1fee5b60064e8f13
| 25.822222 | 73 | 0.678542 | 4.119454 | false | false | false | false |
allotria/intellij-community
|
java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/LightJava11HighlightingTest.kt
|
1
|
2126
|
// 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.java.codeInsight.daemon
import com.intellij.JavaTestUtil
import com.intellij.codeInsight.daemon.impl.analysis.HighlightClassUtil
import com.intellij.codeInsight.navigation.actions.GotoDeclarationAction
import com.intellij.psi.CommonClassNames
import com.intellij.psi.PsiClass
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase
import org.assertj.core.api.Assertions.assertThat
import org.junit.Assert
class LightJava11HighlightingTest : LightJavaCodeInsightFixtureTestCase() {
override fun getProjectDescriptor() = JAVA_11
override fun getBasePath() = JavaTestUtil.getRelativeJavaTestDataPath() + "/codeInsight/daemonCodeAnalyzer/advHighlighting11"
fun testMixedVarAndExplicitTypesInLambdaDeclaration() = doTest()
fun testGotoDeclarationOnLambdaVarParameter() {
myFixture.configureByFile(getTestName(false) + ".java")
val offset = myFixture.editor.caretModel.offset
val elements = GotoDeclarationAction.findAllTargetElements(myFixture.project, myFixture.editor, offset)
assertThat(elements).hasSize(1)
val element = elements[0]
assertThat(element).isInstanceOf(PsiClass::class.java)
assertEquals(CommonClassNames.JAVA_LANG_STRING, (element as PsiClass).qualifiedName)
}
fun testShebangInJavaFile() {
doTest()
}
fun testJavaShebang() {
val file = myFixture.configureByText("hello",
"""#!/path/to/java
|class Main {{
|int i = 0;
|i*<error descr="';' expected"><error descr="Expression expected"><error descr="Unexpected token">*</error></error></error>;
|}}""".trimMargin())
myFixture.checkHighlighting()
Assert.assertTrue(HighlightClassUtil.isJavaHashBangScript(file))
}
private fun doTest() {
myFixture.configureByFile(getTestName(false) + ".java")
myFixture.checkHighlighting()
}
}
|
apache-2.0
|
c35ff0ef5866cee87b5a334efd5a7d25
| 43.3125 | 157 | 0.71825 | 4.96729 | false | true | false | false |
allotria/intellij-community
|
platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/entities/Abstraction.kt
|
3
|
3439
|
// 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.workspaceModel.storage.entities
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.WorkspaceEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder
import com.intellij.workspaceModel.storage.impl.EntityDataDelegation
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.references.MutableOneToAbstractMany
import com.intellij.workspaceModel.storage.impl.references.OneToAbstractMany
// ---------------------------
internal abstract class BaseEntity : WorkspaceEntityBase()
internal abstract class ModifiableBaseEntity<T : BaseEntity> : ModifiableWorkspaceEntityBase<T>()
// ---------------------------
internal abstract class CompositeBaseEntity : BaseEntity() {
val children: Sequence<BaseEntity> by OneToAbstractMany(BaseEntity::class.java)
}
internal abstract class ModifiableCompositeBaseEntity<T : CompositeBaseEntity>(clazz: Class<T>) : ModifiableWorkspaceEntityBase<T>() {
var children: Sequence<BaseEntity> by MutableOneToAbstractMany(clazz, BaseEntity::class.java)
}
// ---------------------------
internal class MiddleEntityData : WorkspaceEntityData<MiddleEntity>() {
lateinit var property: String
override fun createEntity(snapshot: WorkspaceEntityStorage): MiddleEntity {
return MiddleEntity(property).also { addMetaData(it, snapshot) }
}
}
internal class MiddleEntity(val property: String) : BaseEntity()
internal class ModifiableMiddleEntity : ModifiableBaseEntity<MiddleEntity>() {
var property: String by EntityDataDelegation()
}
internal fun WorkspaceEntityStorageBuilder.addMiddleEntity(property: String = "prop", source: EntitySource = MySource): MiddleEntity {
return addEntity(ModifiableMiddleEntity::class.java, source) {
this.property = property
}
}
// ---------------------------
internal class LeftEntityData : WorkspaceEntityData<LeftEntity>() {
override fun createEntity(snapshot: WorkspaceEntityStorage): LeftEntity {
return LeftEntity().also { addMetaData(it, snapshot) }
}
}
internal class LeftEntity : CompositeBaseEntity()
internal class ModifiableLeftEntity : ModifiableCompositeBaseEntity<LeftEntity>(LeftEntity::class.java)
internal fun WorkspaceEntityStorageBuilder.addLeftEntity(children: Sequence<BaseEntity>, source: EntitySource = MySource): LeftEntity {
return addEntity(ModifiableLeftEntity::class.java, source) {
this.children = children
}
}
// ---------------------------
internal class RightEntityData : WorkspaceEntityData<RightEntity>() {
override fun createEntity(snapshot: WorkspaceEntityStorage): RightEntity {
return RightEntity().also { addMetaData(it, snapshot) }
}
}
internal class RightEntity : CompositeBaseEntity()
internal class ModifiableRightEntity : ModifiableCompositeBaseEntity<RightEntity>(RightEntity::class.java)
internal fun WorkspaceEntityStorageBuilder.addRightEntity(children: Sequence<BaseEntity>, source: EntitySource = MySource): RightEntity {
return addEntity(ModifiableRightEntity::class.java, source) {
this.children = children
}
}
|
apache-2.0
|
6604f9ea223be41d2606f51eaebdd4ee
| 38.528736 | 140 | 0.779296 | 5.218513 | false | false | false | false |
Kotlin/kotlinx.coroutines
|
kotlinx-coroutines-core/nativeOther/src/Dispatchers.kt
|
1
|
1446
|
/*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines
import kotlin.coroutines.*
internal actual fun createMainDispatcher(default: CoroutineDispatcher): MainCoroutineDispatcher =
MissingMainDispatcher
internal actual fun createDefaultDispatcher(): CoroutineDispatcher = DefaultDispatcher
private object DefaultDispatcher : CoroutineDispatcher() {
// Delegated, so users won't be able to downcast and call 'close'
// The precise number of threads cannot be obtained until KT-48179 is implemented, 4 is just "good enough" number.
private val ctx = newFixedThreadPoolContext(4, "Dispatchers.Default")
override fun dispatch(context: CoroutineContext, block: Runnable) {
ctx.dispatch(context, block)
}
}
private object MissingMainDispatcher : MainCoroutineDispatcher() {
override val immediate: MainCoroutineDispatcher
get() = notImplemented()
override fun dispatch(context: CoroutineContext, block: Runnable) = notImplemented()
override fun isDispatchNeeded(context: CoroutineContext): Boolean = notImplemented()
override fun dispatchYield(context: CoroutineContext, block: Runnable) = notImplemented()
private fun notImplemented(): Nothing = TODO("Dispatchers.Main is missing on the current platform")
}
internal actual inline fun platformAutoreleasePool(crossinline block: () -> Unit) = block()
|
apache-2.0
|
1a4e8aa4bc3ad6bfdecb26855ae22533
| 40.314286 | 118 | 0.766943 | 4.952055 | false | false | false | false |
DeflatedPickle/Quiver
|
core/src/main/kotlin/com/deflatedpickle/quiver/frontend/dialog/UsagesDialog.kt
|
1
|
6287
|
/* Copyright (c) 2021 DeflatedPickle under the MIT license */
package com.deflatedpickle.quiver.frontend.dialog
import com.deflatedpickle.haruhi.util.PluginUtil
import com.deflatedpickle.monocons.MonoIcon
import com.deflatedpickle.quiver.Quiver
import com.deflatedpickle.quiver.backend.event.EventSearchFile
import com.deflatedpickle.quiver.backend.event.EventSelectFile
import com.deflatedpickle.quiver.backend.event.EventSelectFolder
import com.deflatedpickle.quiver.backend.extension.toAsset
import com.deflatedpickle.quiver.backend.extension.toSyntaxEditingStyle
import com.deflatedpickle.quiver.backend.util.DotMinecraft
import com.deflatedpickle.quiver.frontend.widget.editButton
import com.deflatedpickle.quiver.frontend.widget.openButton
import com.deflatedpickle.undulation.constraints.FillBothFinishLine
import com.jidesoft.swing.DefaultOverlayable
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea
import org.fife.ui.rtextarea.RTextScrollPane
import org.fife.ui.rtextarea.SearchContext
import org.fife.ui.rtextarea.SearchEngine
import org.jdesktop.swingx.JXButton
import org.jdesktop.swingx.JXPanel
import org.oxbow.swingbits.dialog.task.TaskDialog
import java.awt.BorderLayout
import java.awt.Component
import java.awt.Desktop
import java.awt.Dimension
import java.awt.GridBagLayout
import java.io.File
import javax.swing.BorderFactory
import javax.swing.DefaultListCellRenderer
import javax.swing.DefaultListModel
import javax.swing.JList
import javax.swing.JPanel
import javax.swing.JProgressBar
import javax.swing.JScrollPane
import javax.swing.JSplitPane
import javax.swing.JToolBar
// TODO: Add a context menu to select items in the file table
class UsagesDialog : TaskDialog(PluginUtil.window, "Find Usages") {
private var lookFor: String = ""
private val textArea = RSyntaxTextArea().apply {
this.isEditable = false
this.antiAliasingEnabled = true
this.isWhitespaceVisible = true
this.paintTabLines = true
this.isCodeFoldingEnabled = true
}
private val listModel = DefaultListModel<File>()
private val list = JList(this.listModel).apply {
cellRenderer = object : DefaultListCellRenderer() {
override fun getListCellRendererComponent(
list: JList<*>?,
value: Any?,
index: Int,
isSelected: Boolean,
cellHasFocus: Boolean
): Component = super.getListCellRendererComponent(
list,
(value as File).absolutePath.removePrefix("${DotMinecraft.resourcePacks.absolutePath}/"),
index,
isSelected,
cellHasFocus
)
}
addListSelectionListener {
if (!this.valueIsAdjusting && this.model.size > 0) {
textArea.syntaxEditingStyle = this.selectedValue.extension.toSyntaxEditingStyle()
textArea.text = this.selectedValue.readText()
val context = SearchContext().apply {
matchCase = false
markAll = true
wholeWord = true
searchForward = false
searchFor = lookFor
}
SearchEngine.find(textArea, context)
}
}
}
private val showButton = JXButton(MonoIcon.SHOW).apply {
addActionListener {
// println(list.selectedValue.parentFile)
EventSelectFolder.trigger(list.selectedValue.parentFile)
EventSelectFile.trigger(list.selectedValue)
EventSearchFile.trigger(list.selectedValue)
[email protected] = false
}
}
private val openButton = openButton(
true,
{ Desktop.getDesktop().open(list.selectedValue) },
{ Desktop.getDesktop().open(list.selectedValue.parentFile) }
)
private val editButton = editButton(true) { Desktop.getDesktop().edit(list.selectedValue) }
private val progressBar = JProgressBar().apply {
isIndeterminate = true
}
init {
setCommands(
StandardCommand.OK
)
this.fixedComponent = JScrollPane(
JPanel().apply {
isOpaque = false
layout = GridBagLayout()
add(
JSplitPane(
JSplitPane.HORIZONTAL_SPLIT,
DefaultOverlayable(
JScrollPane(list),
progressBar
),
JXPanel(BorderLayout()).apply {
add(
JToolBar().apply {
add(showButton)
add(openButton)
add(editButton)
},
BorderLayout.NORTH
)
add(RTextScrollPane(textArea), BorderLayout.CENTER)
}
).apply {
isContinuousLayout = true
resizeWeight = 0.4
},
FillBothFinishLine
)
}
).apply {
isOpaque = false
viewport.isOpaque = false
border = BorderFactory.createEmptyBorder()
preferredSize = Dimension(600, 400)
}
}
fun refreshAll(lookFor: File) {
this.lookFor = lookFor.nameWithoutExtension
this.listModel.removeAllElements()
this.refresh(Quiver.packDirectory!!, lookFor)
progressBar.isVisible = false
}
fun refresh(file: File, lookFor: File) {
file.listFiles()?.forEach {
if (it.isDirectory) {
refresh(it, lookFor)
} else if (it.isFile) {
val text = it.readText()
if (text.contains(lookFor.nameWithoutExtension) ||
text.contains(lookFor.toAsset())
) {
// println(it)
this.listModel.addElement(it)
}
}
}
this.list.setSelectionInterval(0, 0)
}
}
|
mit
|
07424a770a806a6a38bab3ba36531e4b
| 33.355191 | 105 | 0.592652 | 5.221761 | false | false | false | false |
stevesea/RPGpad
|
adventuresmith-core/src/main/kotlin/org/stevesea/adventuresmith/core/dice_roller/MYZDiceGenerator.kt
|
2
|
6199
|
/*
* Copyright (c) 2017 Steve Christensen
*
* This file is part of Adventuresmith.
*
* Adventuresmith is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Adventuresmith is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Adventuresmith. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.stevesea.adventuresmith.core.dice_roller
import mu.KLoggable
import org.stevesea.adventuresmith.core.Generator
import org.stevesea.adventuresmith.core.GeneratorInputDto
import org.stevesea.adventuresmith.core.GeneratorMetaDto
import org.stevesea.adventuresmith.core.InputParamDto
import org.stevesea.adventuresmith.core.RangeMap
import org.stevesea.adventuresmith.core.Shuffler
import org.stevesea.adventuresmith.core.titleCase
import java.util.Locale
class MYZDiceGenerator(
val myid: String,
val myname: String,
val shuffler: Shuffler) : Generator, KLoggable {
override val logger = logger()
override fun getId(): String {
return myid
}
companion object {
val BASE = "base"
val SKILL = "skill"
val GEAR = "gear"
val RADIOACTIVE = "{cmd_radioactive}"
val BIOHAZARD = "{cmd_biohazard}"
val GEAR_BREAK = "{cmd_flash_outline}" // cmd-fire, cmd-flash-outline?
val MYZ_DIE_MAP = linkedMapOf (
BASE to RangeMap()
.with(1, BIOHAZARD)
.with(2, "{cmd_dice_2}")
.with(3, "{cmd_dice_3}")
.with(4, "{cmd_dice_4}")
.with(5, "{cmd_dice_5}")
.with(6, RADIOACTIVE),
SKILL to RangeMap()
.with(1, "{cmd_dice_1}")
.with(2, "{cmd_dice_2}")
.with(3, "{cmd_dice_3}")
.with(4, "{cmd_dice_4}")
.with(5, "{cmd_dice_5}")
.with(6, RADIOACTIVE),
GEAR to RangeMap()
.with(1, GEAR_BREAK)
.with(2, "{cmd_dice_2}")
.with(3, "{cmd_dice_3}")
.with(4, "{cmd_dice_4}")
.with(5, "{cmd_dice_5}")
.with(6, RADIOACTIVE)
)
val MYZ_DIE_COLOR = linkedMapOf(
BASE to "ff8f00",
SKILL to "2e7d32",
GEAR to "424242"
)
}
override fun generate(locale: Locale, input: Map<String, String>?): String {
val inputMapForContext = getMetadata(locale).mergeInputWithDefaults(input)
val resultLines = mutableListOf<String>()
var totalRadioactive = 0
var totalBiohazard = 0
var totalGear = 0
// iterate over each type of die
MYZ_DIE_MAP.forEach {
val n = inputMapForContext.getOrElse(it.key) { "0" }.toString().toInt()
if (n > 0) {
val sb = StringBuilder()
// TODO: font doesn't work in IconicsTextView. How to have both icons and color?!?!?
sb.append("<font color=\"#${MYZ_DIE_COLOR[it.key]}\">")
sb.append("${it.key.titleCase()}: ")
for (i in 1..n) {
val roll = shuffler.pick(it.value)
if (RADIOACTIVE == roll) {
totalRadioactive++
}
if (BIOHAZARD == roll) {
totalBiohazard++
}
if (GEAR_BREAK == roll) {
totalGear++
}
sb.append(roll)
}
sb.append("</font>")
resultLines.add(sb.toString())
}
}
if (resultLines.isEmpty()) {
return "You must configure your dice pool."
}
if (totalRadioactive > 0 || totalBiohazard > 0 || totalGear > 0) {
val sb = StringBuilder()
sb.append("Totals:")
if (totalRadioactive > 0) {
sb.append(" $RADIOACTIVE : $totalRadioactive")
}
if (totalBiohazard > 0) {
sb.append(" $BIOHAZARD : $totalBiohazard")
}
if (totalGear > 0) {
sb.append(" $GEAR_BREAK : $totalGear")
}
resultLines.add(sb.toString())
}
return resultLines.joinToString("<br/><br/>")
}
override fun getMetadata(locale: Locale): GeneratorMetaDto {
return GeneratorMetaDto(name = myname,
useIconicsTextView = true,
input = GeneratorInputDto(
displayTemplate = """
<big>
{{#$BASE}}{{$BASE}}base{{/$BASE}}{{#$SKILL}} {{$SKILL}}skill{{/$SKILL}}{{#$GEAR}} {{$GEAR}}gear{{/$GEAR}}
""",
useWizard = false,
params = listOf(
InputParamDto(name = BASE, uiName = "# of $BASE die (yellow)", numbersOnly = true, isInt = true,
maxVal = 10, nullIfZero = true, defaultValue = "",
helpText = "$BASE (yellow), $SKILL (green), $GEAR (black):"),
InputParamDto(name = SKILL, uiName = "# of $SKILL die (green)", numbersOnly = true, isInt = true,
maxVal = 10, nullIfZero = true, defaultValue = ""),
InputParamDto(name = GEAR, uiName = "# of $GEAR die (black)", numbersOnly = true, isInt = true,
maxVal = 10, nullIfZero = true, defaultValue = "")
)
))
}
}
|
gpl-3.0
|
e168fa709eab486acfd3a62f44a11a79
| 37.75 | 133 | 0.502662 | 4.205563 | false | false | false | false |
leafclick/intellij-community
|
platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapImpl.kt
|
1
|
30827
|
// 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.keymap.impl
import com.intellij.configurationStore.SchemeDataHolder
import com.intellij.configurationStore.SerializableScheme
import com.intellij.ide.plugins.PluginManagerConfigurable
import com.intellij.internal.statistic.collectors.fus.actions.persistence.ActionsCollectorImpl
import com.intellij.notification.*
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionManagerEx
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.keymap.Keymap
import com.intellij.openapi.keymap.KeymapManager
import com.intellij.openapi.keymap.KeymapManagerListener
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.keymap.ex.KeymapManagerEx
import com.intellij.openapi.options.ExternalizableSchemeAdapter
import com.intellij.openapi.options.SchemeState
import com.intellij.openapi.options.ShowSettingsUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ProjectManagerListener
import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.PluginsAdvertiser
import com.intellij.openapi.util.InvalidDataException
import com.intellij.openapi.util.SystemInfo
import com.intellij.ui.KeyStrokeAdapter
import com.intellij.util.ArrayUtilRt
import com.intellij.util.SmartList
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.mapSmart
import com.intellij.util.containers.nullize
import gnu.trove.THashMap
import org.jdom.Element
import java.util.*
import javax.swing.KeyStroke
import kotlin.collections.HashSet
private const val KEY_MAP = "keymap"
private const val KEYBOARD_SHORTCUT = "keyboard-shortcut"
private const val KEYBOARD_GESTURE_SHORTCUT = "keyboard-gesture-shortcut"
private const val KEYBOARD_GESTURE_KEY = "keystroke"
private const val KEYBOARD_GESTURE_MODIFIER = "modifier"
private const val KEYSTROKE_ATTRIBUTE = "keystroke"
private const val FIRST_KEYSTROKE_ATTRIBUTE = "first-keystroke"
private const val SECOND_KEYSTROKE_ATTRIBUTE = "second-keystroke"
private const val ACTION = "action"
private const val VERSION_ATTRIBUTE = "version"
private const val PARENT_ATTRIBUTE = "parent"
private const val NAME_ATTRIBUTE = "name"
private const val ID_ATTRIBUTE = "id"
private const val MOUSE_SHORTCUT = "mouse-shortcut"
private val LOG = logger<KeymapImpl>()
fun KeymapImpl(name: String, dataHolder: SchemeDataHolder<KeymapImpl>): KeymapImpl {
val result = KeymapImpl(dataHolder)
result.name = name
result.schemeState = SchemeState.UNCHANGED
return result
}
private val NOTIFICATION_MANAGER by lazy {
// we use name "Password Safe" instead of "Credentials Store" because it was named so previously (and no much sense to rename it)
SingletonNotificationManager(NotificationGroup("Keymap", NotificationDisplayType.STICKY_BALLOON, true), NotificationType.ERROR)
}
open class KeymapImpl @JvmOverloads constructor(private var dataHolder: SchemeDataHolder<KeymapImpl>? = null) : ExternalizableSchemeAdapter(), Keymap, SerializableScheme {
private var parent: KeymapImpl? = null
private var unknownParentName: String? = null
open var canModify: Boolean = true
@JvmField
internal var schemeState: SchemeState? = null
override fun getSchemeState(): SchemeState? = schemeState
private val actionIdToShortcuts = THashMap<String, MutableList<Shortcut>>()
get() {
val dataHolder = dataHolder
if (dataHolder != null) {
this.dataHolder = null
readExternal(dataHolder.read())
}
return field
}
private val listeners = ContainerUtil.createLockFreeCopyOnWriteList<Keymap.Listener>()
private val keymapManager by lazy { KeymapManagerEx.getInstanceEx()!! }
/**
* @return IDs of the action which are specified in the keymap. It doesn't return IDs of action from parent keymap.
*/
val ownActionIds: Array<String>
get() = actionIdToShortcuts.keys.toTypedArray()
private var _mouseShortcutToListOfIds: Map<MouseShortcut, MutableList<String>>? = null
private val mouseShortcutToActionIds: Map<MouseShortcut, MutableList<String>>
get() {
var result = _mouseShortcutToListOfIds
if (result == null) {
result = fillShortcutToListOfIds(MouseShortcut::class.java)
_mouseShortcutToListOfIds = result
}
return result
}
private var _keystrokeToIds: MutableMap<KeyStroke, MutableList<String>>? = null
private val keystrokeToIds: Map<KeyStroke, MutableList<String>>
get() {
_keystrokeToIds?.let {
return it
}
val result = THashMap<KeyStroke, MutableList<String>>()
fun addKeystrokesMap(actionId: String) {
for (shortcut in getOwnOrBoundShortcuts(actionId)) {
if (shortcut !is KeyboardShortcut) {
continue
}
val idList = result.getOrPut(shortcut.firstKeyStroke) { SmartList() }
// action may have more that 1 shortcut with same first keystroke
if (!idList.contains(actionId)) {
idList.add(actionId)
}
}
}
_keystrokeToIds = result
for (id in actionIdToShortcuts.keys) {
addKeystrokesMap(id)
}
for (id in keymapManager.boundActions) {
addKeystrokesMap(id)
}
return result
}
override fun getPresentableName(): String = name
override fun deriveKeymap(newName: String): KeymapImpl {
if (canModify()) {
val newKeymap = copy()
newKeymap.name = newName
return newKeymap
}
else {
val newKeymap = KeymapImpl()
newKeymap.parent = this
newKeymap.name = newName
return newKeymap
}
}
@Deprecated("Please use {@link #deriveKeymap(String)} instead. " +
"New method was introduced to ensure that you don't forget to set new keymap name.")
fun deriveKeymap(): KeymapImpl {
val name = try {
name
}
catch (e: Exception) {
// avoid possible NPE
"unnamed"
}
return deriveKeymap("$name (copy)")
}
fun copy(): KeymapImpl {
dataHolder?.let {
return KeymapImpl(name, it)
}
return copyTo(KeymapImpl())
}
fun copyTo(otherKeymap: KeymapImpl): KeymapImpl {
otherKeymap.cleanShortcutsCache()
otherKeymap.actionIdToShortcuts.clear()
otherKeymap.actionIdToShortcuts.ensureCapacity(actionIdToShortcuts.size)
actionIdToShortcuts.forEachEntry { actionId, shortcuts ->
otherKeymap.actionIdToShortcuts.put(actionId, SmartList(shortcuts))
true
}
// after actionIdToShortcuts (on first access we lazily read itself)
otherKeymap.parent = parent
otherKeymap.name = name
otherKeymap.canModify = canModify()
return otherKeymap
}
override fun getParent(): KeymapImpl? = parent
final override fun canModify(): Boolean = canModify
override fun addShortcut(actionId: String, shortcut: Shortcut) {
val list = actionIdToShortcuts.getOrPut(actionId) {
val result = SmartList<Shortcut>()
val boundShortcuts = keymapManager.getActionBinding(actionId)?.let { actionIdToShortcuts.get(it) }
if (boundShortcuts != null) {
result.addAll(boundShortcuts)
}
else {
parent?.getMutableShortcutList(actionId)?.mapTo(result) { convertShortcut(it) }
}
result
}
if (!list.contains(shortcut)) {
list.add(shortcut)
}
if (list.areShortcutsEqualToParent(actionId)) {
actionIdToShortcuts.remove(actionId)
}
cleanShortcutsCache()
fireShortcutChanged(actionId)
}
private fun cleanShortcutsCache() {
_keystrokeToIds = null
_mouseShortcutToListOfIds = null
schemeState = SchemeState.POSSIBLY_CHANGED
}
override fun removeAllActionShortcuts(actionId: String) {
for (shortcut in getShortcuts(actionId)) {
removeShortcut(actionId, shortcut)
}
}
override fun removeShortcut(actionId: String, toDelete: Shortcut) {
val list = actionIdToShortcuts.get(actionId)
if (list == null) {
val inherited = keymapManager.getActionBinding(actionId)?.let { actionIdToShortcuts.get(it) }
?: parent?.getMutableShortcutList(actionId)?.mapSmart { convertShortcut(it) }.nullize()
if (inherited != null) {
var newShortcuts: MutableList<Shortcut>? = null
for (itemIndex in 0..inherited.lastIndex) {
val item = inherited.get(itemIndex)
if (toDelete == item) {
if (newShortcuts == null) {
newShortcuts = SmartList()
for (notAddedItemIndex in 0..itemIndex - 1) {
newShortcuts.add(inherited.get(notAddedItemIndex))
}
}
}
else if (newShortcuts != null) {
newShortcuts.add(item)
}
}
newShortcuts?.let {
actionIdToShortcuts.put(actionId, it)
}
}
}
else {
val index = list.indexOf(toDelete)
if (index >= 0) {
if (parent == null) {
if (list.size == 1) {
actionIdToShortcuts.remove(actionId)
}
else {
list.removeAt(index)
}
}
else {
list.removeAt(index)
if (list.areShortcutsEqualToParent(actionId)) {
actionIdToShortcuts.remove(actionId)
}
}
}
}
cleanShortcutsCache()
fireShortcutChanged(actionId)
}
private fun MutableList<Shortcut>.areShortcutsEqualToParent(actionId: String) = parent.let { parent -> parent != null && areShortcutsEqual(this, parent.getMutableShortcutList(actionId).mapSmart { convertShortcut(it) }) }
private val gestureToListOfIds: Map<KeyboardModifierGestureShortcut, List<String>> by lazy { fillShortcutToListOfIds(KeyboardModifierGestureShortcut::class.java) }
private fun <T : Shortcut> fillShortcutToListOfIds(shortcutClass: Class<T>): Map<T, MutableList<String>> {
val map = THashMap<T, MutableList<String>>()
fun addActionToShortcutsMap(actionId: String) {
for (shortcut in getOwnOrBoundShortcuts(actionId)) {
if (!shortcutClass.isAssignableFrom(shortcut.javaClass)) {
continue
}
@Suppress("UNCHECKED_CAST")
val ids = map.getOrPut(shortcut as T) { SmartList() }
// action may have more that 1 shortcut with same first keystroke
if (!ids.contains(actionId)) {
ids.add(actionId)
}
}
}
for (id in actionIdToShortcuts.keys) {
addActionToShortcutsMap(id)
}
for (id in keymapManager.boundActions) {
addActionToShortcutsMap(id)
}
return map
}
private fun getOwnOrBoundShortcuts(actionId: String): List<Shortcut> {
actionIdToShortcuts.get(actionId)?.let {
return it
}
val result = SmartList<Shortcut>()
keymapManager.getActionBinding(actionId)?.let {
result.addAll(getOwnOrBoundShortcuts(it))
}
return result
}
private fun getActionIds(shortcut: KeyboardModifierGestureShortcut): List<String> {
// first, get keystrokes from own map
val list = SmartList<String>()
for ((key, value) in gestureToListOfIds) {
if (shortcut.startsWith(key)) {
list.addAll(value)
}
}
if (parent != null) {
val ids = parent!!.getActionIds(shortcut)
if (ids.isNotEmpty()) {
for (id in ids) {
// add actions from parent keymap only if they are absent in this keymap
if (!actionIdToShortcuts.containsKey(id)) {
list.add(id)
}
}
}
}
sortInRegistrationOrder(list)
return list
}
override fun getActionIds(firstKeyStroke: KeyStroke): Array<String> {
return ArrayUtilRt.toStringArray(getActionIds(firstKeyStroke, { it.keystrokeToIds }, KeymapImpl::convertKeyStroke))
}
override fun getActionIds(firstKeyStroke: KeyStroke, secondKeyStroke: KeyStroke?): Array<String> {
val ids = getActionIds(firstKeyStroke)
var actualBindings: MutableList<String>? = null
for (id in ids) {
val shortcuts = getShortcuts(id)
for (shortcut in shortcuts) {
if (shortcut !is KeyboardShortcut) {
continue
}
if (firstKeyStroke == shortcut.firstKeyStroke && secondKeyStroke == shortcut.secondKeyStroke) {
if (actualBindings == null) {
actualBindings = SmartList<String>()
}
actualBindings.add(id)
break
}
}
}
return ArrayUtilRt.toStringArray(actualBindings)
}
override fun getActionIds(shortcut: Shortcut): Array<String> {
return when (shortcut) {
is KeyboardShortcut -> {
val first = shortcut.firstKeyStroke
val second = shortcut.secondKeyStroke
if (second == null) getActionIds(first) else getActionIds(first, second)
}
is MouseShortcut -> ArrayUtilRt.toStringArray(getActionIds(shortcut))
is KeyboardModifierGestureShortcut -> ArrayUtilRt.toStringArray(getActionIds(shortcut))
else -> ArrayUtilRt.EMPTY_STRING_ARRAY
}
}
override fun hasActionId(actionId: String, shortcut: MouseShortcut): Boolean {
var convertedShortcut = shortcut
var keymap = this
do {
val list = keymap.mouseShortcutToActionIds.get(convertedShortcut)
if (list != null && list.contains(actionId)) {
return true
}
val parent = keymap.parent ?: return false
convertedShortcut = keymap.convertMouseShortcut(shortcut)
keymap = parent
}
while (true)
}
override fun getActionIds(shortcut: MouseShortcut): List<String> {
return getActionIds(shortcut, { it.mouseShortcutToActionIds }, KeymapImpl::convertMouseShortcut)
}
private fun <T> getActionIds(shortcut: T, shortcutToActionIds: (keymap: KeymapImpl) -> Map<T, MutableList<String>>, convertShortcut: (keymap: KeymapImpl, shortcut: T) -> T): List<String> {
// first, get keystrokes from own map
var list = shortcutToActionIds(this).get(shortcut)
val parentIds = parent?.getActionIds(convertShortcut(this, shortcut), shortcutToActionIds, convertShortcut) ?: emptyList()
var isOriginalListInstance = list != null
for (id in parentIds) {
// add actions from parent keymap only if they are absent in this keymap
// do not add parent bind actions, if bind-on action is overwritten in the child
if (actionIdToShortcuts.containsKey(id) || actionIdToShortcuts.containsKey(keymapManager.getActionBinding(id))) {
continue
}
if (list == null) {
list = SmartList()
}
else if (isOriginalListInstance) {
list = SmartList(list)
isOriginalListInstance = false
}
if (!list.contains(id)) {
list.add(id)
}
}
sortInRegistrationOrder(list ?: return emptyList())
return list
}
fun isActionBound(actionId: String): Boolean = keymapManager.boundActions.contains(actionId)
override fun getShortcuts(actionId: String?): Array<Shortcut> = getMutableShortcutList(actionId).let { if (it.isEmpty()) Shortcut.EMPTY_ARRAY else it.toTypedArray() }
private fun getMutableShortcutList(actionId: String?): List<Shortcut> {
if (actionId == null) {
return emptyList()
}
// it is critical to use convertShortcut - otherwise MacOSDefaultKeymap doesn't convert shortcuts
// todo why not convert on add? why we don't need to convert our own shortcuts?
return actionIdToShortcuts.get(actionId) ?: keymapManager.getActionBinding(actionId)?.let { actionIdToShortcuts.get(it) } ?: parent?.getMutableShortcutList(actionId)?.mapSmart { convertShortcut(it) } ?: emptyList()
}
fun getOwnShortcuts(actionId: String): Array<Shortcut> {
val own = actionIdToShortcuts.get(actionId) ?: return Shortcut.EMPTY_ARRAY
return if (own.isEmpty()) Shortcut.EMPTY_ARRAY else own.toTypedArray()
}
// you must clear actionIdToShortcuts before call
protected open fun readExternal(keymapElement: Element) {
if (KEY_MAP != keymapElement.name) {
throw InvalidDataException("unknown element: $keymapElement")
}
if (keymapElement.getAttributeValue(VERSION_ATTRIBUTE) == null) {
Converter01.convert(keymapElement)
}
name = keymapElement.getAttributeValue(NAME_ATTRIBUTE)
unknownParentName = null
keymapElement.getAttributeValue(PARENT_ATTRIBUTE)?.let { parentSchemeName ->
var parentScheme = findParentScheme(parentSchemeName)
if (parentScheme == null && parentSchemeName == "Default for Mac OS X") {
// https://youtrack.jetbrains.com/issue/RUBY-17767#comment=27-1374197
parentScheme = findParentScheme("Mac OS X")
}
if (parentScheme == null) {
LOG.warn("Cannot find parent scheme $parentSchemeName for scheme $name")
unknownParentName = parentSchemeName
notifyAboutMissingKeymap(parentSchemeName, "Cannot find parent keymap \"$parentSchemeName\" for \"$name\"")
}
else {
parent = parentScheme as KeymapImpl
canModify = true
}
}
val actionIds = HashSet<String>()
val skipInserts = SystemInfo.isMac && (ApplicationManager.getApplication() == null || !ApplicationManager.getApplication().isUnitTestMode)
for (actionElement in keymapElement.children) {
if (actionElement.name != ACTION) {
throw InvalidDataException("unknown element: $actionElement; Keymap's name=$name")
}
val id = actionElement.getAttributeValue(ID_ATTRIBUTE) ?: throw InvalidDataException("Attribute 'id' cannot be null; Keymap's name=$name")
actionIds.add(id)
val shortcuts = SmartList<Shortcut>()
// always creates list even if no shortcuts - empty action element means that action overrides parent to denote that no shortcuts
actionIdToShortcuts.put(id, shortcuts)
for (shortcutElement in actionElement.children) {
if (KEYBOARD_SHORTCUT == shortcutElement.name) {
// Parse first keystroke
val firstKeyStrokeStr = shortcutElement.getAttributeValue(FIRST_KEYSTROKE_ATTRIBUTE)
?: throw InvalidDataException("Attribute '$FIRST_KEYSTROKE_ATTRIBUTE' cannot be null; Action's id=$id; Keymap's name=$name")
if (skipInserts && firstKeyStrokeStr.contains("INSERT")) {
continue
}
val firstKeyStroke = KeyStrokeAdapter.getKeyStroke(firstKeyStrokeStr) ?: continue
// Parse second keystroke
var secondKeyStroke: KeyStroke? = null
val secondKeyStrokeStr = shortcutElement.getAttributeValue(SECOND_KEYSTROKE_ATTRIBUTE)
if (secondKeyStrokeStr != null) {
secondKeyStroke = KeyStrokeAdapter.getKeyStroke(secondKeyStrokeStr) ?: continue
}
shortcuts.add(KeyboardShortcut(firstKeyStroke, secondKeyStroke))
}
else if (KEYBOARD_GESTURE_SHORTCUT == shortcutElement.name) {
val strokeText = shortcutElement.getAttributeValue(KEYBOARD_GESTURE_KEY) ?: throw InvalidDataException(
"Attribute '$KEYBOARD_GESTURE_KEY' cannot be null; Action's id=$id; Keymap's name=$name")
val stroke = KeyStrokeAdapter.getKeyStroke(strokeText) ?: continue
val modifierText = shortcutElement.getAttributeValue(KEYBOARD_GESTURE_MODIFIER)
var modifier: KeyboardGestureAction.ModifierType? = null
if (KeyboardGestureAction.ModifierType.dblClick.toString().equals(modifierText, ignoreCase = true)) {
modifier = KeyboardGestureAction.ModifierType.dblClick
}
else if (KeyboardGestureAction.ModifierType.hold.toString().equals(modifierText, ignoreCase = true)) {
modifier = KeyboardGestureAction.ModifierType.hold
}
if (modifier == null) {
throw InvalidDataException("Wrong modifier=$modifierText action id=$id keymap=$name")
}
shortcuts.add(KeyboardModifierGestureShortcut.newInstance(modifier, stroke))
}
else if (MOUSE_SHORTCUT == shortcutElement.name) {
val keystrokeString = shortcutElement.getAttributeValue(KEYSTROKE_ATTRIBUTE) ?: throw InvalidDataException(
"Attribute 'keystroke' cannot be null; Action's id=$id; Keymap's name=$name")
try {
shortcuts.add(KeymapUtil.parseMouseShortcut(keystrokeString))
}
catch (e: InvalidDataException) {
throw InvalidDataException("Wrong mouse-shortcut: '$keystrokeString'; Action's id=$id; Keymap's name=$name")
}
}
else {
throw InvalidDataException("unknown element: $shortcutElement; Keymap's name=$name")
}
}
}
ActionsCollectorImpl.onActionsLoadedFromKeymapXml(this, actionIds)
cleanShortcutsCache()
}
protected open fun findParentScheme(parentSchemeName: String): Keymap? = keymapManager.schemeManager.findSchemeByName(parentSchemeName)
override fun writeScheme(): Element {
dataHolder?.let {
return it.read()
}
val keymapElement = Element(KEY_MAP)
keymapElement.setAttribute(VERSION_ATTRIBUTE, Integer.toString(1))
keymapElement.setAttribute(NAME_ATTRIBUTE, name)
(parent?.name ?: unknownParentName)?.let {
keymapElement.setAttribute(PARENT_ATTRIBUTE, it)
}
writeOwnActionIds(keymapElement)
schemeState = SchemeState.UNCHANGED
return keymapElement
}
private fun writeOwnActionIds(keymapElement: Element) {
val ownActionIds = ownActionIds
Arrays.sort(ownActionIds)
for (actionId in ownActionIds) {
val shortcuts = actionIdToShortcuts.get(actionId) ?: continue
val actionElement = Element(ACTION)
actionElement.setAttribute(ID_ATTRIBUTE, actionId)
for (shortcut in shortcuts) {
when (shortcut) {
is KeyboardShortcut -> {
val element = Element(KEYBOARD_SHORTCUT)
element.setAttribute(FIRST_KEYSTROKE_ATTRIBUTE, KeyStrokeAdapter.toString(shortcut.firstKeyStroke))
shortcut.secondKeyStroke?.let {
element.setAttribute(SECOND_KEYSTROKE_ATTRIBUTE, KeyStrokeAdapter.toString(it))
}
actionElement.addContent(element)
}
is MouseShortcut -> {
val element = Element(MOUSE_SHORTCUT)
element.setAttribute(KEYSTROKE_ATTRIBUTE, KeymapUtil.getMouseShortcutString(shortcut))
actionElement.addContent(element)
}
is KeyboardModifierGestureShortcut -> {
val element = Element(KEYBOARD_GESTURE_SHORTCUT)
element.setAttribute(KEYBOARD_GESTURE_SHORTCUT, KeyStrokeAdapter.toString(shortcut.stroke))
element.setAttribute(KEYBOARD_GESTURE_MODIFIER, shortcut.type.name)
actionElement.addContent(element)
}
else -> throw IllegalStateException("unknown shortcut class: $shortcut")
}
}
keymapElement.addContent(actionElement)
}
}
fun clearOwnActionsIds() {
actionIdToShortcuts.clear()
cleanShortcutsCache()
}
fun hasOwnActionId(actionId: String): Boolean = actionIdToShortcuts.containsKey(actionId)
fun clearOwnActionsId(actionId: String) {
actionIdToShortcuts.remove(actionId)
cleanShortcutsCache()
}
override fun getActionIds(): Array<String> = ArrayUtilRt.toStringArray(actionIdList)
override fun getActionIdList(): Set<String> {
val ids = LinkedHashSet<String>()
ids.addAll(actionIdToShortcuts.keys)
var parent = parent
while (parent != null) {
ids.addAll(parent.actionIdToShortcuts.keys)
parent = parent.parent
}
return ids
}
override fun getConflicts(actionId: String, keyboardShortcut: KeyboardShortcut): Map<String, MutableList<KeyboardShortcut>> {
val result = THashMap<String, MutableList<KeyboardShortcut>>()
for (id in getActionIds(keyboardShortcut.firstKeyStroke)) {
if (id == actionId || (actionId.startsWith("Editor") && id == "$${actionId.substring(6)}")) {
continue
}
val useShortcutOf = keymapManager.getActionBinding(id)
if (useShortcutOf != null && useShortcutOf == actionId) {
continue
}
for (shortcut1 in getMutableShortcutList(id)) {
if (shortcut1 !is KeyboardShortcut || shortcut1.firstKeyStroke != keyboardShortcut.firstKeyStroke) {
continue
}
if (keyboardShortcut.secondKeyStroke != null && shortcut1.secondKeyStroke != null && keyboardShortcut.secondKeyStroke != shortcut1.secondKeyStroke) {
continue
}
result.getOrPut(id) { SmartList() }.add(shortcut1)
}
}
return result
}
protected open fun convertKeyStroke(keyStroke: KeyStroke): KeyStroke = keyStroke
protected open fun convertMouseShortcut(shortcut: MouseShortcut): MouseShortcut = shortcut
protected open fun convertShortcut(shortcut: Shortcut): Shortcut = shortcut
override fun addShortcutChangeListener(listener: Keymap.Listener) {
listeners.add(listener)
}
override fun removeShortcutChangeListener(listener: Keymap.Listener) {
listeners.remove(listener)
}
private fun fireShortcutChanged(actionId: String) {
(KeymapManager.getInstance() as? KeymapManagerImpl)?.fireShortcutChanged(this, actionId)
for (listener in listeners) {
listener.onShortcutChanged(actionId)
}
}
override fun toString(): String = presentableName
override fun equals(other: Any?): Boolean {
if (other !is KeymapImpl) return false
if (name != other.name) return false
if (canModify != other.canModify) return false
if (parent != other.parent) return false
if (actionIdToShortcuts != other.actionIdToShortcuts) return false
return true
}
override fun hashCode(): Int = name.hashCode()
}
private fun sortInRegistrationOrder(ids: MutableList<String>) {
ids.sortWith(ActionManagerEx.getInstanceEx().registrationOrderComparator)
}
// compare two lists in any order
private fun areShortcutsEqual(shortcuts1: List<Shortcut>, shortcuts2: List<Shortcut>): Boolean {
if (shortcuts1.size != shortcuts2.size) {
return false
}
for (shortcut in shortcuts1) {
if (!shortcuts2.contains(shortcut)) {
return false
}
}
return true
}
private val macOSKeymap = "com.intellij.plugins.macoskeymap"
private val gnomeKeymap = "com.intellij.plugins.gnomekeymap"
private val kdeKeymap = "com.intellij.plugins.kdekeymap"
private val xwinKeymap = "com.intellij.plugins.xwinkeymap"
private val eclipseKeymap = "com.intellij.plugins.eclipsekeymap"
private val emacsKeymap = "com.intellij.plugins.emacskeymap"
private val netbeansKeymap = "com.intellij.plugins.netbeanskeymap"
private val resharperKeymap = "com.intellij.plugins.resharperkeymap"
private val sublimeKeymap = "com.intellij.plugins.sublimetextkeymap"
private val visualStudioKeymap = "com.intellij.plugins.visualstudiokeymap"
private val xcodeKeymap = "com.intellij.plugins.xcodekeymap"
internal fun notifyAboutMissingKeymap(keymapName: String, message: String) {
val connection = ApplicationManager.getApplication().messageBus.connect()
connection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener {
override fun projectOpened(project: Project) {
connection.disconnect()
ApplicationManager.getApplication().invokeLater(
{
// TODO remove when PluginAdvertiser implements that
@Suppress("SpellCheckingInspection")
val pluginId = when (keymapName) {
"Mac OS X",
"Mac OS X 10.5+" -> macOSKeymap
"Default for GNOME" -> gnomeKeymap
"Default for KDE" -> kdeKeymap
"Default for XWin" -> xwinKeymap
"Eclipse",
"Eclipse (Mac OS X)" -> eclipseKeymap
"Emacs" -> emacsKeymap
"NetBeans 6.5" -> netbeansKeymap
"ReSharper",
"ReSharper OSX" -> resharperKeymap
"Sublime Text",
"Sublime Text (Mac OS X)" -> sublimeKeymap
"Visual Studio" -> visualStudioKeymap
"Xcode" -> xcodeKeymap
else -> null
}
val action: AnAction? = when (pluginId) {
null -> object : NotificationAction("Search for $keymapName Keymap plugin") {
override fun actionPerformed(e: AnActionEvent, notification: Notification) {
//TODO enableSearch("$keymapName /tag:Keymap")?.run()
ShowSettingsUtil.getInstance().showSettingsDialog(e.project, PluginManagerConfigurable::class.java)
}
}
else -> object : NotificationAction("Install $keymapName Keymap") {
override fun actionPerformed(e: AnActionEvent, notification: Notification) {
val connect = ApplicationManager.getApplication().messageBus.connect()
connect.subscribe(KeymapManagerListener.TOPIC, object: KeymapManagerListener {
override fun keymapAdded(keymap: Keymap) {
ApplicationManager.getApplication().invokeLater {
if (keymap.name == keymapName) {
connect.disconnect()
KeymapManagerEx.getInstanceEx().activeKeymap = keymap
val group = NotificationGroup("Keymap", NotificationDisplayType.BALLOON, true)
val notificationManager = SingletonNotificationManager(group, NotificationType.INFORMATION)
notificationManager.notify("Keymap $keymapName successfully activated", project)
}
}
}
})
PluginsAdvertiser.installAndEnable(project, getPluginIdWithDependencies(pluginId), false) {
}
notification.expire()
}
fun toPluginIds(vararg ids: String) = ids.map { PluginId.getId(it) }.toSet()
private fun getPluginIdWithDependencies(pluginId: String): Set<PluginId> {
return when (pluginId) {
gnomeKeymap -> toPluginIds(gnomeKeymap, xwinKeymap)
kdeKeymap -> toPluginIds(kdeKeymap, xwinKeymap)
resharperKeymap -> toPluginIds(resharperKeymap, visualStudioKeymap)
xcodeKeymap -> toPluginIds(xcodeKeymap, macOSKeymap)
else -> toPluginIds(pluginId)
}
}
}
}
NOTIFICATION_MANAGER.notify("Missing Keymap", message, action = action)
}, ModalityState.NON_MODAL)
}
}
)
}
|
apache-2.0
|
22518e04cf095a34a61ff0ee4e72f972
| 36.639805 | 222 | 0.683297 | 5.119914 | false | false | false | false |
VREMSoftwareDevelopment/WiFiAnalyzer
|
app/src/main/kotlin/com/vrem/wifianalyzer/wifi/band/WiFiChannelCountryGHZ6.kt
|
1
|
1778
|
/*
* WiFiAnalyzer
* Copyright (C) 2015 - 2022 VREM Software Development <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.vrem.wifianalyzer.wifi.band
import java.util.*
internal class WiFiChannelCountryGHZ6 {
private val channelsSet1: Set<Int> = setOf(1, 5, 9, 13, 17, 21, 25, 29)
private val channelsSet2: Set<Int> = setOf(33, 37, 41, 45, 49, 53, 57, 61)
private val channelsSet3: Set<Int> = setOf(65, 69, 73, 77, 81, 85, 89, 93)
private val channelsSet4: Set<Int> = setOf(97, 101, 105, 109, 113, 117, 121, 125)
private val channelsSet5: Set<Int> = setOf(129, 133, 137, 141, 145, 149, 153, 157)
private val channelsSet6: Set<Int> = setOf(161, 165, 169, 173, 177, 181, 185, 189)
private val channelsSet7: Set<Int> = setOf(193, 197, 201, 205, 209, 213, 217, 221, 225, 229)
private val channels: SortedSet<Int> = channelsSet1
.union(channelsSet2)
.union(channelsSet3)
.union(channelsSet4)
.union(channelsSet5)
.union(channelsSet6)
.union(channelsSet7)
.toSortedSet()
fun findChannels(countryCode: String): SortedSet<Int> = channels
}
|
gpl-3.0
|
2b1b4be54786f443644fd9fab695e2fb
| 43.475 | 96 | 0.695726 | 3.570281 | false | false | false | false |
zdary/intellij-community
|
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/PackageSearchToolWindowService.kt
|
1
|
8386
|
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow
import com.intellij.ProjectTopics
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.DumbUnawareHider
import com.intellij.openapi.project.ModuleListener
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootEvent
import com.intellij.openapi.roots.ModuleRootListener
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ex.ToolWindowEx
import com.intellij.ui.content.ContentFactory
import com.intellij.ui.content.ContentManager
import com.intellij.ui.content.ContentManagerEvent
import com.intellij.ui.content.ContentManagerListener
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModuleProvider
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.HasToolWindowActions
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.PackageSearchPanelBase
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.SimpleToolWindowWithToolWindowActionsPanel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.SimpleToolWindowWithTwoToolbarsPanel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.PackageManagementPanel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.repositories.RepositoryManagementPanel
import com.jetbrains.packagesearch.intellij.plugin.util.FeatureFlags
import com.jetbrains.packagesearch.intellij.plugin.util.logDebug
import com.jetbrains.packagesearch.intellij.plugin.util.dataService
import org.jetbrains.annotations.Nls
import javax.swing.JComponent
import javax.swing.JLabel
internal class PackageSearchToolWindowService(val project: Project) : Disposable {
private lateinit var toolWindow: ToolWindow
private var toolWindowContentsCreated = false
private var wasAvailable = false
fun initialize(toolWindow: ToolWindow) {
this.toolWindow = toolWindow
setAvailabilityBasedOnProjectModules(project)
startMonitoring()
}
private fun setAvailabilityBasedOnProjectModules(project: Project) {
if (!::toolWindow.isInitialized) return
val isAvailable = ProjectModuleProvider.obtainAllProjectModulesFor(project).any()
if (wasAvailable != isAvailable || !toolWindowContentsCreated) {
createToolWindowContents(toolWindow, isAvailable)
}
}
private val panels = mutableListOf<PackageSearchPanelBase>()
private fun createToolWindowContents(toolWindow: ToolWindow, isAvailable: Boolean) {
toolWindowContentsCreated = true
wasAvailable = isAvailable
toolWindow.title = PackageSearchBundle.message("packagesearch.ui.toolwindow.title")
val contentFactory = ContentFactory.SERVICE.getInstance()
val contentManager = toolWindow.contentManager
contentManager.removeAllContents(false)
if (!isAvailable) {
renderUnavailableUi(contentManager)
return
}
if (toolWindow is ToolWindowEx) {
registerSelectionChangedListener(contentManager, toolWindow)
}
val rootModel = project.dataService()
panels += PackageManagementPanel(
rootDataModelProvider = rootModel,
selectedPackageSetter = rootModel,
targetModuleSetter = rootModel,
searchClient = rootModel,
operationExecutor = rootModel,
lifetimeProvider = rootModel
)
if (FeatureFlags.showRepositoriesTab) {
panels += RepositoryManagementPanel(
rootDataModelProvider = rootModel,
lifetimeProvider = rootModel
)
}
for (panel in panels) {
initializePanel(panel, contentManager, contentFactory)
}
}
private fun renderUnavailableUi(contentManager: ContentManager) {
contentManager.addContent(
ContentFactory.SERVICE.getInstance().createContent(
DumbUnawareHider(JLabel()).apply {
setContentVisible(false)
emptyText.text = PackageSearchBundle.message("packagesearch.ui.toolwindow.tab.noModules")
},
PackageSearchBundle.message("packagesearch.ui.toolwindow.tab.packages.title"), false
).apply {
isCloseable = false
}
)
}
private fun registerSelectionChangedListener(
contentManager: ContentManager,
toolWindow: ToolWindowEx
) {
contentManager.addContentManagerListener(object : ContentManagerListener {
override fun selectionChanged(event: ContentManagerEvent) {
toolWindow.setAdditionalGearActions(null)
toolWindow.setTitleActions(emptyList())
val panel = event.content.component as? HasToolWindowActions
panel?.gearActions?.let {
toolWindow.setAdditionalGearActions(it)
}
panel?.titleActions?.let {
toolWindow.setTitleActions(it.asList())
}
}
})
}
private fun initializePanel(
panel: PackageSearchPanelBase,
contentManager: ContentManager,
contentFactory: ContentFactory
) {
val panelContent = panel.content // should be executed before toolbars
val toolbar = panel.toolbar
val topToolbar = panel.topToolbar
val gearActions = panel.gearActions
val titleActions = panel.titleActions
if (topToolbar == null) {
contentManager.addTab(panel.title, panelContent, toolbar, gearActions, titleActions)
} else {
val content = contentFactory.createContent(
toolbar?.let {
SimpleToolWindowWithTwoToolbarsPanel(
it,
topToolbar,
gearActions,
titleActions,
panelContent
)
},
panel.title,
false
)
content.isCloseable = false
contentManager.addContent(content)
}
}
private fun ContentManager.addTab(
@Nls title: String,
content: JComponent,
toolbar: JComponent?,
gearActions: ActionGroup?,
titleActions: Array<AnAction>?
) {
addContent(
ContentFactory.SERVICE.getInstance().createContent(null, title, false).apply {
component = SimpleToolWindowWithToolWindowActionsPanel(gearActions, titleActions, false).apply {
setProvideQuickActions(true)
setContent(content)
toolbar?.let { setToolbar(it) }
isCloseable = false
}
}
)
}
private fun startMonitoring() {
project.messageBus.connect(this).subscribe(
ProjectTopics.PROJECT_ROOTS,
object : ModuleRootListener {
override fun rootsChanged(event: ModuleRootEvent) {
setAvailabilityBasedOnProjectModules(project)
}
}
)
project.messageBus.connect(this).subscribe(
ProjectTopics.MODULES,
object : ModuleListener {
override fun moduleAdded(p: Project, module: Module) {
setAvailabilityBasedOnProjectModules(project)
}
override fun moduleRemoved(p: Project, module: Module) {
setAvailabilityBasedOnProjectModules(project)
}
}
)
}
override fun dispose() {
logDebug("PackageSearchToolWindowService#dispose()") { "Disposing PackageSearchToolWindowService..." }
for (panel in panels) {
if (panel is Disposable) Disposer.dispose(panel)
}
if (::toolWindow.isInitialized && !toolWindow.isDisposed) {
toolWindow.remove()
}
}
}
|
apache-2.0
|
78731581fb8feb9f4d3fee6247065648
| 36.774775 | 114 | 0.662652 | 5.628188 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/markdown/core/src/org/intellij/plugins/markdown/ui/actions/styling/MarkdownCreateLinkAction.kt
|
1
|
8249
|
// 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.intellij.plugins.markdown.ui.actions.styling
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.ToggleAction
import com.intellij.openapi.application.ex.ClipboardUtil
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.elementType
import com.intellij.psi.util.elementsAtOffsetUp
import com.intellij.refactoring.suggested.endOffset
import com.intellij.refactoring.suggested.startOffset
import com.intellij.util.LocalFileUrl
import com.intellij.util.Urls
import com.intellij.util.io.exists
import org.intellij.plugins.markdown.MarkdownBundle
import org.intellij.plugins.markdown.lang.MarkdownElementTypes
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile
import org.intellij.plugins.markdown.ui.actions.MarkdownActionPlaces
import org.intellij.plugins.markdown.ui.actions.MarkdownActionUtil
import org.jetbrains.annotations.Nls
import java.nio.file.InvalidPathException
import java.nio.file.Path
internal class MarkdownCreateLinkAction : ToggleAction(), DumbAware {
private val wrapActionBaseName: String
get() = MarkdownBundle.message("action.org.intellij.plugins.markdown.ui.actions.styling.MarkdownCreateLinkAction.text")
private val unwrapActionName: String
get() = MarkdownBundle.message("action.org.intellij.plugins.markdown.ui.actions.styling.MarkdownCreateLinkAction.unwrap.text")
private fun obtainWrapActionName(place: String): @Nls String {
return when (place) {
MarkdownActionPlaces.INSERT_POPUP -> MarkdownBundle.message("action.org.intellij.plugins.markdown.ui.actions.styling.MarkdownCreateLinkAction.insert.popup.text")
else -> wrapActionBaseName
}
}
override fun isSelected(e: AnActionEvent): Boolean {
val editor = MarkdownActionUtil.findMarkdownTextEditor(e)
val file = e.getData(CommonDataKeys.PSI_FILE)
if (editor == null || file !is MarkdownFile) {
e.presentation.isEnabledAndVisible = false
return false
}
e.presentation.isEnabledAndVisible = true
val caretsWithLinks = editor.caretModel.allCarets
.filter { it.getSelectedLinkElement(file) != null }
val caretsWithLinksCount = caretsWithLinks.count()
return when {
caretsWithLinksCount == 0 || e.place == ActionPlaces.EDITOR_POPUP -> {
e.presentation.isEnabled = !editor.isViewer
e.presentation.text = obtainWrapActionName(e.place)
e.presentation.description = MarkdownBundle.message(
"action.org.intellij.plugins.markdown.ui.actions.styling.MarkdownCreateLinkAction.description")
false
}
caretsWithLinksCount == editor.caretModel.caretCount -> {
e.presentation.isEnabled = !editor.isViewer
e.presentation.text = unwrapActionName
e.presentation.description = MarkdownBundle.message(
"action.org.intellij.plugins.markdown.ui.actions.styling.MarkdownCreateLinkAction.unwrap.description")
true
}
else -> { // some carets are located at links, others are not
e.presentation.isEnabled = false
false
}
}
}
override fun setSelected(e: AnActionEvent, state: Boolean) {
val editor = MarkdownActionUtil.findMarkdownTextEditor(e) ?: error("Could not find Markdown editor")
val file = e.getRequiredData(CommonDataKeys.PSI_FILE)
if (state) {
for (caret in editor.caretModel.allCarets) {
wrapSelectionWithLink(caret, editor, file.project)
}
}
else {
editor.caretModel.allCarets
.sortedBy { -it.offset }
.map { caret -> caret to caret.getSelectedLinkElement(file) }
.distinctBy { (_, element) -> element }
.forEach { (caret, element) ->
assert(element != null)
if (element == null) return@forEach
unwrapLink(element, caret, editor, file.project)
}
}
}
override fun update(e: AnActionEvent) {
val originalIcon = e.presentation.icon
super.update(e)
if (ActionPlaces.isPopupPlace(e.place)) {
// Restore original icon, as it will be disabled in popups, and we still want to show in GeneratePopup
e.presentation.icon = originalIcon
}
}
private fun wrapSelectionWithLink(caret: Caret, editor: Editor, project: Project) {
val selected = caret.selectedText ?: ""
val selectionStart = caret.selectionStart
val selectionEnd = caret.selectionEnd
val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.document)
val fileArray = file?.let { arrayOf(it) } ?: emptyArray()
WriteCommandAction.writeCommandAction(project, *fileArray)
.withName(wrapActionBaseName)
.run<Nothing> {
caret.removeSelection()
editor.document.replaceString(selectionStart, selectionEnd, "[$selected]()")
caret.moveToOffset(selectionEnd + 3)
getLinkDestinationInClipboard(editor)?.let { linkDestination ->
val linkStartOffset = caret.offset
editor.document.insertString(linkStartOffset, linkDestination)
caret.setSelection(linkStartOffset, linkStartOffset + linkDestination.length)
}
}
}
private fun getLinkDestinationInClipboard(editor: Editor): String? =
ClipboardUtil.getTextInClipboard()?.takeIf { path ->
when (Urls.parse(path, asLocalIfNoScheme = true)) {
null -> false
is LocalFileUrl -> {
val relativePath = try {
Path.of(path)
}
catch (e: InvalidPathException) {
return@takeIf false
}
val dir = FileDocumentManager.getInstance().getFile(editor.document)?.parent
val absolutePath = dir?.let { Path.of(it.path) }?.resolve(relativePath)
absolutePath?.exists() ?: false
}
else -> true
}
}
private fun unwrapLink(linkElement: PsiElement, caret: Caret, editor: Editor, project: Project) {
val linkText = linkElement.children
.find { it.elementType == MarkdownElementTypes.LINK_TEXT }
?.text?.drop(1)?.dropLast(1) // unwrap []
?: ""
val start = linkElement.startOffset
val newEnd = start + linkText.length
// left braket is deleted, so offsets should be shifted 1 position backwards;
// they should also match the constraint: start <= offset <= newEnd
val selectionStart = maxOf(start, minOf(newEnd, caret.selectionStart - 1))
val selectionEnd = maxOf(start, minOf(newEnd, caret.selectionEnd - 1))
val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.document)
val fileArray = file?.let { arrayOf(it) } ?: emptyArray()
WriteCommandAction.writeCommandAction(project, *fileArray)
.withName(unwrapActionName)
.run<Nothing> {
if (selectionStart == selectionEnd) {
caret.removeSelection() // so that the floating toolbar is hidden; must be done before text replacement
caret.moveCaretRelatively(-1, 0, false, false)
}
editor.document.replaceString(start, linkElement.endOffset, linkText)
if (selectionStart != selectionEnd)
caret.setSelection(selectionStart, selectionEnd)
}
}
private fun Caret.getSelectedLinkElement(file: PsiFile): PsiElement? {
val linkElement = file.elementsAtOffsetUp(selectionStart).asSequence()
.find { (element, _) -> element.elementType == MarkdownElementTypes.INLINE_LINK }
?.first
return linkElement?.takeIf { element ->
if (hasSelection())
selectionEnd <= element.endOffset
else
offset > element.startOffset // caret should be strictly inside
}
}
}
|
apache-2.0
|
3e85a15e68c9b2f1a0737c8e73998bfc
| 40.039801 | 167 | 0.713177 | 4.631668 | false | false | false | false |
smmribeiro/intellij-community
|
platform/object-serializer/src/xml/KotlinxSerializationBinding.kt
|
1
|
2441
|
// 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.serialization.xml
import com.intellij.util.XmlElement
import com.intellij.util.xmlb.NotNullDeserializeBinding
import com.intellij.util.xmlb.SerializationFilter
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.json.Json
import org.jdom.CDATA
import org.jdom.Element
import org.jdom.Text
import java.lang.invoke.MethodHandles
import java.lang.invoke.MethodType
@OptIn(ExperimentalSerializationApi::class)
private val json = Json {
prettyPrint = true
prettyPrintIndent = " "
ignoreUnknownKeys = true
}
private val lookup = MethodHandles.lookup()
private val kotlinMethodType = MethodType.methodType(KSerializer::class.java)
internal class KotlinxSerializationBinding(aClass: Class<*>) : NotNullDeserializeBinding() {
private val serializer: KSerializer<Any>
init {
// don't use official `::kotlin.get().serializer()` API — avoid kotlin refection wrapper creation
// findStaticGetter cannot be used because type of Companion not used
val field = aClass.getDeclaredField("Companion")
field.isAccessible = true
val companion = lookup.unreflectGetter(field).invoke()
@Suppress("UNCHECKED_CAST")
serializer = lookup.findVirtual(companion.javaClass, "serializer", kotlinMethodType).invoke(companion) as KSerializer<Any>
}
override fun serialize(o: Any, context: Any?, filter: SerializationFilter?): Any {
val element = Element("state")
element.addContent(CDATA(json.encodeToString(serializer, o)))
return element
}
override fun isBoundTo(element: Element): Boolean {
throw UnsupportedOperationException("Only root object is supported")
}
override fun isBoundTo(element: XmlElement): Boolean {
throw UnsupportedOperationException("Only root object is supported")
}
override fun deserialize(context: Any?, element: Element): Any {
val cdata = element.content.firstOrNull() as? Text
if (cdata == null) {
LOG.debug("incorrect data (old format?) for $serializer")
return json.decodeFromString(serializer, "{}")
}
return json.decodeFromString(serializer, cdata.text)
}
override fun deserialize(context: Any?, element: XmlElement): Any {
throw UnsupportedOperationException("Only JDOM is supported for now")
}
}
|
apache-2.0
|
c2532bd183b87f15e46229855cfdbe14
| 36.538462 | 126 | 0.762608 | 4.601887 | false | false | false | false |
smmribeiro/intellij-community
|
platform/built-in-server/src/org/jetbrains/builtInWebServer/WebServerPathToFileManager.kt
|
5
|
7731
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.builtInWebServer
import com.github.benmanes.caffeine.cache.CacheLoader
import com.github.benmanes.caffeine.cache.Caffeine
import com.intellij.ProjectTopics
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.components.service
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.rootManager
import com.intellij.openapi.roots.AdditionalLibraryRootsListener
import com.intellij.openapi.roots.ModuleRootEvent
import com.intellij.openapi.roots.ModuleRootListener
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.util.SmartList
import com.intellij.util.io.exists
import java.nio.file.Paths
import java.util.concurrent.TimeUnit
import kotlin.streams.asSequence
private const val cacheSize: Long = 4096 * 4
/**
* Implement [WebServerRootsProvider] to add your provider
*/
class WebServerPathToFileManager(private val project: Project) {
internal val pathToInfoCache = Caffeine.newBuilder().maximumSize(cacheSize).expireAfterAccess(10, TimeUnit.MINUTES).build<String, PathInfo>()
// time to expire should be greater than pathToFileCache
private val virtualFileToPathInfo = Caffeine.newBuilder().maximumSize(cacheSize).expireAfterAccess(11, TimeUnit.MINUTES).build<VirtualFile, PathInfo>()
internal val pathToExistShortTermCache = Caffeine.newBuilder().maximumSize(cacheSize).expireAfterAccess(5, TimeUnit.SECONDS).build<String, Boolean>()
/**
* https://youtrack.jetbrains.com/issue/WEB-25900
*
* Compute suitable roots for oldest parent (web/foo/my/file.dart -> oldest is web and we compute all suitable roots for it in advance) to avoid linear search
* (i.e. to avoid two queries for root if files web/foo and web/bar requested if root doesn't have web dir)
*/
internal val parentToSuitableRoot = Caffeine
.newBuilder()
.maximumSize(cacheSize).expireAfterAccess(10, TimeUnit.MINUTES)
.build<String, List<SuitableRoot>>(CacheLoader { path ->
val suitableRoots = SmartList<SuitableRoot>()
var moduleQualifier: String? = null
val modules = runReadAction { ModuleManager.getInstance(project).modules }
for (rootProvider in RootProvider.values()) {
for (module in modules) {
if (module.isDisposed) {
continue
}
for (root in rootProvider.getRoots(module.rootManager)) {
if (root.findChild(path) != null) {
if (moduleQualifier == null) {
moduleQualifier = getModuleNameQualifier(project, module)
}
suitableRoots.add(SuitableRoot(root, moduleQualifier))
}
}
}
}
suitableRoots
})
init {
ApplicationManager.getApplication().messageBus.connect (project).subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener {
override fun after(events: List<VFileEvent>) {
for (event in events) {
if (event is VFileContentChangeEvent) {
val file = event.file
for (rootsProvider in WebServerRootsProvider.EP_NAME.extensions) {
if (rootsProvider.isClearCacheOnFileContentChanged(file)) {
clearCache()
break
}
}
}
else {
clearCache()
break
}
}
}
})
project.messageBus.connect().subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener {
override fun rootsChanged(event: ModuleRootEvent) {
clearCache()
}
})
project.messageBus.connect().subscribe(AdditionalLibraryRootsListener.TOPIC,
AdditionalLibraryRootsListener { _, _, _, _ ->
clearCache()
})
}
companion object {
@JvmStatic
fun getInstance(project: Project) = project.service<WebServerPathToFileManager>()
}
private fun clearCache() {
pathToInfoCache.invalidateAll()
virtualFileToPathInfo.invalidateAll()
pathToExistShortTermCache.invalidateAll()
parentToSuitableRoot.invalidateAll()
}
@JvmOverloads
fun findVirtualFile(path: String, cacheResult: Boolean = true, pathQuery: PathQuery = defaultPathQuery): VirtualFile? {
return getPathInfo(path, cacheResult, pathQuery)?.getOrResolveVirtualFile()
}
@JvmOverloads
fun getPathInfo(path: String, cacheResult: Boolean = true, pathQuery: PathQuery = defaultPathQuery): PathInfo? {
var pathInfo = pathToInfoCache.getIfPresent(path)
if (pathInfo == null || !pathInfo.isValid) {
if (pathToExistShortTermCache.getIfPresent(path) == false) {
return null
}
pathInfo = doFindByRelativePath(path, pathQuery)
if (cacheResult) {
if (pathInfo != null && pathInfo.isValid) {
pathToInfoCache.put(path, pathInfo)
}
else {
pathToExistShortTermCache.put(path, false)
}
}
}
return pathInfo
}
fun getPath(file: VirtualFile): String? = getPathInfo(file)?.path
fun getPathInfo(child: VirtualFile): PathInfo? {
var result = virtualFileToPathInfo.getIfPresent(child)
if (result == null) {
result = WebServerRootsProvider.EP_NAME.extensions().asSequence().map { it.getPathInfo(child, project) }.find { it != null }
if (result != null) {
virtualFileToPathInfo.put(child, result)
}
}
return result
}
internal fun doFindByRelativePath(path: String, pathQuery: PathQuery): PathInfo? {
val result = WebServerRootsProvider.EP_NAME.extensionList.asSequence().map { it.resolve(path, project, pathQuery) }.find { it != null } ?: return null
result.file?.let {
virtualFileToPathInfo.put(it, result)
}
return result
}
fun getResolver(path: String): FileResolver = if (path.isEmpty()) EMPTY_PATH_RESOLVER else RELATIVE_PATH_RESOLVER
}
interface FileResolver {
fun resolve(path: String, root: VirtualFile, moduleName: String? = null, isLibrary: Boolean = false, pathQuery: PathQuery): PathInfo?
}
private val RELATIVE_PATH_RESOLVER = object : FileResolver {
override fun resolve(path: String, root: VirtualFile, moduleName: String?, isLibrary: Boolean, pathQuery: PathQuery): PathInfo? {
// WEB-17691 built-in server doesn't serve files it doesn't have in the project tree
// temp:// reports isInLocalFileSystem == true, but it is not true
if (pathQuery.useVfs || root.fileSystem != LocalFileSystem.getInstance() || path == ".htaccess" || path == "config.json") {
return root.findFileByRelativePath(path)?.let { PathInfo(null, it, root, moduleName, isLibrary) }
}
val file = Paths.get(root.path, path)
return if (file.exists()) {
PathInfo(file, null, root, moduleName, isLibrary)
}
else {
null
}
}
}
private val EMPTY_PATH_RESOLVER = object : FileResolver {
override fun resolve(path: String, root: VirtualFile, moduleName: String?, isLibrary: Boolean, pathQuery: PathQuery): PathInfo? {
val file = findIndexFile(root) ?: return null
return PathInfo(null, file, root, moduleName, isLibrary)
}
}
internal val defaultPathQuery = PathQuery()
|
apache-2.0
|
6a42e6243db534791f12f24aad7f3aca
| 38.85567 | 160 | 0.696417 | 4.795906 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/tests/testData/compiler/asJava/lightClasses/nullabilityAnnotations/Class.kt
|
7
|
999
|
// Class
import org.jetbrains.annotations.NotNull
import org.jetbrains.annotations.Nullable
class Class {
fun notNull(a: String): String = ""
fun nullable(a: String?): String? = ""
@NotNull fun notNullWithNN(): String = ""
@Nullable fun notNullWithN(): String = ""
@Nullable fun nullableWithN(): String? = ""
@NotNull fun nullableWithNN(): String? = ""
val nullableVal: String? = { "" }()
var nullableVar: String? = { "" }()
val notNullVal: String = { "" }()
var notNullVar: String = { "" }()
val notNullValWithGet: String
@[Nullable] get() = ""
var notNullVarWithGetSet: String
@[Nullable] get() = ""
@[Nullable] set(v) {}
val nullableValWithGet: String?
@[NotNull] get() = ""
var nullableVarWithGetSet: String?
@[NotNull] get() = ""
@[NotNull] set(v) {}
private val privateNN: String = { "" }()
private val privateN: String? = { "" }()
lateinit var lateInitVar: String
}
|
apache-2.0
|
85f31e69fb612e60bcb60f93bf862da8
| 24.641026 | 47 | 0.585586 | 3.933071 | false | false | false | false |
Flank/flank
|
test_runner/src/main/kotlin/ftl/presentation/cli/firebase/test/ios/configuration/IosLocalesDescribeCommand.kt
|
1
|
1529
|
package ftl.presentation.cli.firebase.test.ios.configuration
import ftl.api.Locale
import ftl.config.FtlConstants
import ftl.domain.DescribeIosLocales
import ftl.domain.invoke
import ftl.presentation.cli.firebase.test.locale.prepareDescription
import ftl.presentation.outputLogger
import ftl.presentation.throwUnknownType
import ftl.util.PrintHelpCommand
import picocli.CommandLine
@CommandLine.Command(
name = "describe",
headerHeading = "",
synopsisHeading = "%n",
descriptionHeading = "%n@|bold,underline Description:|@%n%n",
parameterListHeading = "%n@|bold,underline Parameters:|@%n",
optionListHeading = "%n@|bold,underline Options:|@%n",
header = ["Describe a locales "],
usageHelpAutoWidth = true
)
class IosLocalesDescribeCommand :
PrintHelpCommand(),
DescribeIosLocales {
@CommandLine.Parameters(
index = "0",
arity = "1",
paramLabel = "LOCALE",
defaultValue = "",
description = [
"The locale to describe, found" +
" using \$ gcloud firebase test ios locales list\n."
]
)
override var locale: String = ""
@CommandLine.Option(
names = ["-c", "--config"],
description = ["YAML config file path"]
)
override var configPath: String = FtlConstants.defaultIosConfig
override val out = outputLogger {
when (this) {
is Locale -> prepareDescription()
else -> throwUnknownType()
}
}
override fun run() = invoke()
}
|
apache-2.0
|
a10afc0ca3f5e837360a8f2ab3dc029e
| 27.849057 | 68 | 0.654676 | 4.393678 | false | true | false | false |
zdary/intellij-community
|
plugins/maven/src/main/java/org/jetbrains/idea/maven/buildtool/MavenSyncConsole.kt
|
1
|
18752
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.buildtool
import com.intellij.build.BuildProgressListener
import com.intellij.build.DefaultBuildDescriptor
import com.intellij.build.FilePosition
import com.intellij.build.SyncViewManager
import com.intellij.build.events.EventResult
import com.intellij.build.events.MessageEvent
import com.intellij.build.events.MessageEventResult
import com.intellij.build.events.impl.*
import com.intellij.build.issue.BuildIssue
import com.intellij.build.issue.BuildIssueQuickFix
import com.intellij.execution.ExecutionException
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.pom.Navigatable
import com.intellij.util.ExceptionUtil
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.Nls
import org.jetbrains.idea.maven.buildtool.quickfix.OffMavenOfflineModeQuickFix
import org.jetbrains.idea.maven.buildtool.quickfix.OpenMavenSettingsQuickFix
import org.jetbrains.idea.maven.buildtool.quickfix.UseBundledMavenQuickFix
import org.jetbrains.idea.maven.execution.SyncBundle
import org.jetbrains.idea.maven.project.MavenProjectsManager
import org.jetbrains.idea.maven.project.MavenWorkspaceSettingsComponent
import org.jetbrains.idea.maven.server.CannotStartServerException
import org.jetbrains.idea.maven.server.MavenServerManager
import org.jetbrains.idea.maven.server.MavenServerProgressIndicator
import org.jetbrains.idea.maven.utils.MavenLog
import org.jetbrains.idea.maven.utils.MavenUtil
import java.io.File
class MavenSyncConsole(private val myProject: Project) {
@Volatile
private var mySyncView: BuildProgressListener = BuildProgressListener { _, _ -> }
private var mySyncId = ExternalSystemTaskId.create(MavenUtil.SYSTEM_ID, ExternalSystemTaskType.RESOLVE_PROJECT, myProject)
private var finished = false
private var started = false
private var wrapperProgressIndicator: WrapperProgressIndicator? = null
private var hasErrors = false
private var hasUnresolved = false
private val JAVADOC_AND_SOURCE_CLASSIFIERS = setOf("javadoc", "sources", "test-javadoc", "test-sources")
private val shownIssues = HashSet<String>()
private val myPostponed = ArrayList<() -> Unit>()
private var myStartedSet = LinkedHashSet<Pair<Any, String>>()
@Synchronized
fun startImport(syncView: BuildProgressListener) {
if (started) {
return
}
val restartAction: AnAction = object : AnAction() {
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = !started || finished
e.presentation.icon = AllIcons.Actions.Refresh
}
override fun actionPerformed(e: AnActionEvent) {
e.project?.let {
MavenProjectsManager.getInstance(it).forceUpdateAllProjectsOrFindAllAvailablePomFiles()
}
}
}
started = true
finished = false
hasErrors = false
hasUnresolved = false
wrapperProgressIndicator = WrapperProgressIndicator()
mySyncView = syncView
shownIssues.clear()
mySyncId = ExternalSystemTaskId.create(MavenUtil.SYSTEM_ID, ExternalSystemTaskType.RESOLVE_PROJECT, myProject)
val descriptor = DefaultBuildDescriptor(mySyncId, SyncBundle.message("maven.sync.title"), myProject.basePath!!,
System.currentTimeMillis())
.withRestartAction(restartAction)
descriptor.isActivateToolWindowWhenFailed = true
descriptor.isActivateToolWindowWhenAdded = false
mySyncView.onEvent(mySyncId, StartBuildEventImpl(descriptor, SyncBundle.message("maven.sync.project.title", myProject.name)))
debugLog("maven sync: started importing $myProject")
myPostponed.forEach(this::doIfImportInProcess)
myPostponed.clear();
}
fun addText(@Nls text: String) = addText(text, true)
@Synchronized
fun addText(@Nls text: String, stdout: Boolean) = doIfImportInProcess {
addText(mySyncId, text, true)
}
@Synchronized
private fun addText(parentId: Any, @Nls text: String, stdout: Boolean) = doIfImportInProcess {
if (StringUtil.isEmpty(text)) {
return
}
val toPrint = if (text.endsWith('\n')) text else "$text\n"
mySyncView.onEvent(mySyncId, OutputBuildEventImpl(parentId, toPrint, stdout))
}
@Synchronized
fun addWarning(@Nls text: String, @Nls description: String) = addWarning(text, description, null)
fun addBuildIssue(issue: BuildIssue, kind: MessageEvent.Kind) = doIfImportInProcessOrPostpone {
if (!newIssue(issue.title + issue.description)) return@doIfImportInProcessOrPostpone;
mySyncView.onEvent(mySyncId, BuildIssueEventImpl(mySyncId, issue, kind))
hasErrors = hasErrors || kind == MessageEvent.Kind.ERROR;
}
@Synchronized
fun addWarning(@Nls text: String, @Nls description: String, filePosition: FilePosition?) = doIfImportInProcess {
if (!newIssue(text + description + filePosition)) return;
if (filePosition == null) {
mySyncView.onEvent(mySyncId,
MessageEventImpl(mySyncId, MessageEvent.Kind.WARNING, SyncBundle.message("maven.sync.group.compiler"), text,
description))
}
else {
mySyncView.onEvent(mySyncId,
FileMessageEventImpl(mySyncId, MessageEvent.Kind.WARNING, SyncBundle.message("maven.sync.group.compiler"), text,
description, filePosition))
}
}
private fun newIssue(s: String): Boolean {
return shownIssues.add(s)
}
@Synchronized
fun finishImport() {
debugLog("Maven sync: finishImport")
doFinish()
}
@Synchronized
fun terminated(exitCode: Int) = doIfImportInProcess {
val tasks = myStartedSet.toList().asReversed()
debugLog("Tasks $tasks are not completed! Force complete")
tasks.forEach { completeTask(it.first, it.second, FailureResultImpl(SyncBundle.message("maven.sync.failure.terminated", exitCode))) }
mySyncView.onEvent(mySyncId, FinishBuildEventImpl(mySyncId, null, System.currentTimeMillis(), "",
FailureResultImpl(SyncBundle.message("maven.sync.failure.terminated", exitCode))))
finished = true
started = false
}
@Synchronized
fun startWrapperResolving() {
if (!started || finished) {
startImport(myProject.getService(SyncViewManager::class.java))
}
startTask(mySyncId, SyncBundle.message("maven.sync.wrapper"))
}
@Synchronized
fun finishWrapperResolving(e: Throwable? = null) {
if (e != null) {
addWarning(SyncBundle.message("maven.sync.wrapper.failure"), e.localizedMessage)
}
completeTask(mySyncId, SyncBundle.message("maven.sync.wrapper"), SuccessResultImpl())
}
fun progressIndicatorForWrapper(): ProgressIndicator {
return wrapperProgressIndicator ?: EmptyProgressIndicator()
}
inner class WrapperProgressIndicator : EmptyProgressIndicator() {
var myFraction: Long = 0
override fun setText(text: String) = doIfImportInProcess {
addText(SyncBundle.message("maven.sync.wrapper"), text, true)
}
override fun setFraction(fraction: Double) = doIfImportInProcess {
val newFraction = (fraction * 100).toLong()
if (myFraction == newFraction) return@doIfImportInProcess
myFraction = newFraction;
mySyncView.onEvent(mySyncId,
ProgressBuildEventImpl(SyncBundle.message("maven.sync.wrapper"), SyncBundle.message("maven.sync.wrapper"),
System.currentTimeMillis(),
SyncBundle.message("maven.sync.wrapper.dowloading"),
100,
myFraction,
"%"
))
}
}
@Synchronized
fun notifyReadingProblems(file: VirtualFile) = doIfImportInProcess {
debugLog("reading problems in $file")
hasErrors = true
val desc = SyncBundle.message("maven.sync.failure.error.reading.file", file.path)
mySyncView.onEvent(mySyncId,
FileMessageEventImpl(mySyncId, MessageEvent.Kind.ERROR, SyncBundle.message("maven.sync.group.error"), desc, desc,
FilePosition(File(file.path), -1, -1)))
}
@Synchronized
@ApiStatus.Internal
fun addException(e: Throwable, progressListener: BuildProgressListener) {
if (started && !finished) {
MavenLog.LOG.warn(e)
hasErrors = true
@Suppress("HardCodedStringLiteral")
mySyncView.onEvent(mySyncId,
createMessageEvent(e))
}
else {
this.startImport(progressListener)
this.addException(e, progressListener)
this.finishImport()
}
}
private fun createMessageEvent(e: Throwable): MessageEventImpl {
if (e is CannotStartServerException) {
val cause = ExceptionUtil.findCause(e, ExecutionException::class.java)
if (cause != null) {
return MessageEventImpl(mySyncId, MessageEvent.Kind.ERROR, SyncBundle.message("build.event.title.internal.server.error"),
cause.localizedMessage.orEmpty(), ExceptionUtil.getThrowableText(cause))
}
}
return MessageEventImpl(mySyncId, MessageEvent.Kind.ERROR, SyncBundle.message("build.event.title.error"),
e.localizedMessage ?: e.message ?: "Error", ExceptionUtil.getThrowableText(e))
}
fun getListener(type: MavenServerProgressIndicator.ResolveType): ArtifactSyncListener {
return when (type) {
MavenServerProgressIndicator.ResolveType.PLUGIN -> ArtifactSyncListenerImpl("maven.sync.plugins")
MavenServerProgressIndicator.ResolveType.DEPENDENCY -> ArtifactSyncListenerImpl("maven.sync.dependencies")
}
}
@Synchronized
private fun doFinish() {
val tasks = myStartedSet.toList().asReversed()
debugLog("Tasks $tasks are not completed! Force complete")
tasks.forEach { completeTask(it.first, it.second, DerivedResultImpl()) }
mySyncView.onEvent(mySyncId, FinishBuildEventImpl(mySyncId, null, System.currentTimeMillis(), "",
if (hasErrors) FailureResultImpl() else DerivedResultImpl()))
val generalSettings = MavenWorkspaceSettingsComponent.getInstance(myProject).settings.generalSettings
if (hasUnresolved && generalSettings.isWorkOffline) {
mySyncView.onEvent(mySyncId, BuildIssueEventImpl(mySyncId, object : BuildIssue {
override val title: String = "Dependency Resolution Failed"
override val description: String = "<a href=\"${OffMavenOfflineModeQuickFix.ID}\">Switch Off Offline Mode</a>\n"
override val quickFixes: List<BuildIssueQuickFix> = listOf(OffMavenOfflineModeQuickFix())
override fun getNavigatable(project: Project): Navigatable? = null
}, MessageEvent.Kind.ERROR))
}
finished = true
started = false
}
@Synchronized
private fun showError(keyPrefix: String, dependency: String) = doIfImportInProcess {
hasErrors = true
hasUnresolved = true
val umbrellaString = SyncBundle.message("${keyPrefix}.resolve")
val errorString = SyncBundle.message("${keyPrefix}.resolve.error", dependency)
startTask(mySyncId, umbrellaString)
mySyncView.onEvent(mySyncId, MessageEventImpl(umbrellaString, MessageEvent.Kind.ERROR,
SyncBundle.message("maven.sync.group.error"), errorString, errorString))
addText(mySyncId, errorString, false)
}
@Synchronized
private fun startTask(parentId: Any, @NlsSafe taskName: String) = doIfImportInProcess {
debugLog("Maven sync: start $taskName")
if (myStartedSet.add(parentId to taskName)) {
mySyncView.onEvent(mySyncId, StartEventImpl(taskName, parentId, System.currentTimeMillis(), taskName))
}
}
@Synchronized
private fun completeTask(parentId: Any, @NlsSafe taskName: String, result: EventResult) = doIfImportInProcess {
hasErrors = hasErrors || result is FailureResultImpl
debugLog("Maven sync: complete $taskName with $result")
if (myStartedSet.remove(parentId to taskName)) {
mySyncView.onEvent(mySyncId, FinishEventImpl(taskName, parentId, System.currentTimeMillis(), taskName, result))
}
}
private fun debugLog(s: String, exception: Throwable? = null) {
MavenLog.LOG.debug(s, exception)
}
@Synchronized
private fun completeUmbrellaEvents(keyPrefix: String) = doIfImportInProcess {
val taskName = SyncBundle.message("${keyPrefix}.resolve")
completeTask(mySyncId, taskName, DerivedResultImpl())
}
@Synchronized
private fun downloadEventStarted(keyPrefix: String, dependency: String) = doIfImportInProcess {
val downloadString = SyncBundle.message("${keyPrefix}.download")
val downloadArtifactString = SyncBundle.message("${keyPrefix}.artifact.download", dependency)
startTask(mySyncId, downloadString)
startTask(downloadString, downloadArtifactString)
}
@Synchronized
private fun downloadEventCompleted(keyPrefix: String, dependency: String) = doIfImportInProcess {
val downloadString = SyncBundle.message("${keyPrefix}.download")
val downloadArtifactString = SyncBundle.message("${keyPrefix}.artifact.download", dependency)
addText(downloadArtifactString, downloadArtifactString, true)
completeTask(downloadString, downloadArtifactString, SuccessResultImpl(false))
}
@Synchronized
private fun downloadEventFailed(keyPrefix: String,
@NlsSafe dependency: String,
@NlsSafe error: String,
@NlsSafe stackTrace: String?) = doIfImportInProcess {
val downloadString = SyncBundle.message("${keyPrefix}.download")
val downloadArtifactString = SyncBundle.message("${keyPrefix}.artifact.download", dependency)
if (isJavadocOrSource(dependency)) {
addText(downloadArtifactString, SyncBundle.message("maven.sync.failure.dependency.not.found", dependency), true)
completeTask(downloadString, downloadArtifactString, object : MessageEventResult {
override fun getKind(): MessageEvent.Kind {
return MessageEvent.Kind.WARNING
}
override fun getDetails(): String? {
return SyncBundle.message("maven.sync.failure.dependency.not.found", dependency)
}
})
}
else {
if (stackTrace != null && Registry.`is`("maven.spy.events.debug")) {
addText(downloadArtifactString, stackTrace, false)
}
else {
addText(downloadArtifactString, error, true)
}
completeTask(downloadString, downloadArtifactString, FailureResultImpl(error))
}
}
@Synchronized
fun showQuickFixBadMaven(message: String, kind: MessageEvent.Kind) {
val bundledVersion = MavenServerManager.getInstance().getMavenVersion(MavenServerManager.BUNDLED_MAVEN_3)
mySyncView.onEvent(mySyncId, BuildIssueEventImpl(mySyncId, object : BuildIssue {
override val title = SyncBundle.message("maven.sync.version.issue.title")
override val description: String = "${message}\n" +
"- <a href=\"${OpenMavenSettingsQuickFix.ID}\">" +
SyncBundle.message("maven.sync.version.open.settings") + "</a>\n" +
"- <a href=\"${UseBundledMavenQuickFix.ID}\">" +
SyncBundle.message("maven.sync.version.use.bundled", bundledVersion) + "</a>\n"
override val quickFixes: List<BuildIssueQuickFix> = listOf(OpenMavenSettingsQuickFix(), UseBundledMavenQuickFix())
override fun getNavigatable(project: Project): Navigatable? = null
}, kind))
}
@Synchronized
fun showQuickFixJDK(version: String) {
mySyncView.onEvent(mySyncId, BuildIssueEventImpl(mySyncId, object : BuildIssue {
override val title = SyncBundle.message("maven.sync.quickfixes.maven.jdk.version.title")
override val description: String = SyncBundle.message("maven.sync.quickfixes.upgrade.to.jdk7", version) + "\n" +
"- <a href=\"${OpenMavenSettingsQuickFix.ID}\">" +
SyncBundle.message("maven.sync.quickfixes.open.settings") +
"</a>\n"
override val quickFixes: List<BuildIssueQuickFix> = listOf(OpenMavenSettingsQuickFix())
override fun getNavigatable(project: Project): Navigatable? = null
}, MessageEvent.Kind.ERROR))
}
private fun isJavadocOrSource(dependency: String): Boolean {
val split = dependency.split(':')
if (split.size < 4) {
return false
}
val classifier = split.get(2)
return JAVADOC_AND_SOURCE_CLASSIFIERS.contains(classifier)
}
private inline fun doIfImportInProcess(action: () -> Unit) {
if (!started || finished) return
action.invoke()
}
private fun doIfImportInProcessOrPostpone(action: () -> Unit) {
if (!started || finished) {
myPostponed.add(action)
}
else {
action.invoke()
}
}
private inner class ArtifactSyncListenerImpl(val keyPrefix: String) : ArtifactSyncListener {
override fun downloadStarted(dependency: String) {
downloadEventStarted(keyPrefix, dependency)
}
override fun downloadCompleted(dependency: String) {
downloadEventCompleted(keyPrefix, dependency)
}
override fun downloadFailed(dependency: String, error: String, stackTrace: String?) {
downloadEventFailed(keyPrefix, dependency, error, stackTrace)
}
override fun finish() {
completeUmbrellaEvents(keyPrefix)
}
override fun showError(dependency: String) {
showError(keyPrefix, dependency)
}
}
}
interface ArtifactSyncListener {
fun showError(dependency: String)
fun downloadStarted(dependency: String)
fun downloadCompleted(dependency: String)
fun downloadFailed(dependency: String, error: String, stackTrace: String?)
fun finish()
}
|
apache-2.0
|
dc14461bd008810050d6841b4cf9c67b
| 40.578714 | 140 | 0.700779 | 5.013904 | false | false | false | false |
siosio/intellij-community
|
java/java-tests/testSrc/com/intellij/java/propertyBased/ProjectProblemsViewPropertyTest.kt
|
2
|
20905
|
// 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.java.propertyBased
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.codeInsight.daemon.impl.IdentifierHighlighterPassFactory
import com.intellij.codeInsight.daemon.problems.MemberCollector
import com.intellij.codeInsight.daemon.problems.MemberUsageCollector
import com.intellij.codeInsight.daemon.problems.Problem
import com.intellij.codeInsight.daemon.problems.pass.ProjectProblemUtils
import com.intellij.codeInsight.javadoc.JavaDocUtil
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.RecursionManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.*
import com.intellij.psi.impl.search.JavaOverridingMethodsSearcher
import com.intellij.psi.impl.source.resolve.JavaResolveUtil
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.PsiSearchHelper
import com.intellij.psi.search.PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES
import com.intellij.psi.search.SearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtil
import com.intellij.testFramework.SkipSlowTestLocally
import com.intellij.testFramework.TestModeFlags
import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl
import com.intellij.testFramework.propertyBased.MadTestingUtil
import com.intellij.util.ArrayUtilRt
import com.siyeh.ig.psiutils.TypeUtils
import junit.framework.TestCase
import one.util.streamex.StreamEx
import org.jetbrains.jetCheck.Generator
import org.jetbrains.jetCheck.ImperativeCommand
import org.jetbrains.jetCheck.PropertyChecker
import kotlin.math.absoluteValue
@SkipSlowTestLocally
class ProjectProblemsViewPropertyTest : BaseUnivocityTest() {
override fun setUp() {
TestModeFlags.set(ProjectProblemUtils.ourTestingProjectProblems, true, testRootDisposable)
super.setUp()
}
fun testAllFilesWithMemberNameReported() {
RecursionManager.disableMissedCacheAssertions(testRootDisposable)
PropertyChecker.customized()
.withIterationCount(50)
.checkScenarios { ImperativeCommand(this::doTestAllFilesWithMemberNameReported) }
}
private fun doTestAllFilesWithMemberNameReported(env: ImperativeCommand.Environment) {
val changedFiles = mutableMapOf<VirtualFile, Set<VirtualFile>>()
MadTestingUtil.changeAndRevert(myProject) {
val nFilesToChange = env.generateValue(Generator.integers(1, 3), "Files to change: %s")
var i = 0
while (i < nFilesToChange) {
val fileToChange = env.generateValue(psiJavaFiles(), null)
val relatedFiles = findRelatedFiles(fileToChange)
if (relatedFiles.isEmpty()) continue
val members = findMembers(fileToChange)
if (members.isEmpty()) continue
val editor = openEditor(fileToChange.virtualFile)
rehighlight(fileToChange, editor)
if (getFilesReportedByProblemSearch(editor).isNotEmpty()) continue
env.logMessage("Selected file: ${fileToChange.name}")
val actual = changeSelectedFile(env, members, fileToChange)
if (actual == null) break
changedFiles[fileToChange.virtualFile] = relatedFiles
val expected = findFilesWithProblems(relatedFiles, members)
assertContainsElements(actual, expected)
i++
}
}
// check that all problems disappeared after revert
val psiManager = PsiManager.getInstance(myProject)
for ((changedFile, relatedFiles) in changedFiles) {
val psiFile = psiManager.findFile(changedFile)!!
val editor = openEditor(changedFile)
rehighlight(psiFile, editor)
val problems: Map<PsiMember, Set<Problem>> = ProjectProblemUtils.getReportedProblems(editor)
if (problems.isNotEmpty()) {
val relatedProblems = findRelatedProblems(problems, relatedFiles)
if (relatedProblems.isNotEmpty()) {
TestCase.fail("""
Problems are still reported even after the fix.
File: ${changedFile.name},
${relatedProblems.map { (member, memberProblems) -> extractMemberProblems(member, memberProblems) }}
""".trimIndent())
}
}
}
}
private data class ScopedMember(val psiMember: PsiMember, var scope: SearchScope)
private fun changeSelectedFile(env: ImperativeCommand.Environment,
members: List<ScopedMember>,
fileToChange: PsiJavaFile): Set<VirtualFile>? {
val reportedFiles = mutableSetOf<VirtualFile>()
val nChanges = env.generateValue(Generator.integers(1, 5), "Changes to make: %s")
for (j in 0 until nChanges) {
val editor = (FileEditorManager.getInstance(myProject).selectedEditor as TextEditor).editor
val member = env.generateValue(Generator.sampledFrom(members), null)
val psiMember = member.psiMember
val prevScope = psiMember.useScope
env.logMessage("Changing member: ${JavaDocUtil.getReferenceText(myProject, psiMember)}")
val usages = findUsages(psiMember)
if (usages == null || usages.isEmpty()) {
env.logMessage("Member has no usages (or too many). Skipping.")
continue
}
env.logMessage("Found ${usages.size} usages of member and its parents")
val modifications = Modification.getPossibleModifications(psiMember, env)
if (modifications.isEmpty()) {
env.logMessage("Don't know how to modify this member, skipping it.")
continue
}
val modification = env.generateValue(Generator.sampledFrom(modifications), "Applying modification: %s")
val membersToSearch = getMembersToSearch(member, modification, members)
if (membersToSearch == null) {
env.logMessage("Too costly to analyse change, skipping")
continue
}
rehighlight(fileToChange, editor)
WriteCommandAction.runWriteCommandAction(myProject) { modification.apply(myProject) }
env.logMessage("Modification applied")
rehighlight(fileToChange, editor)
if (!isCheapToSearch(psiMember)) {
env.logMessage("Too costly to analyze element after change, skipping all iteration")
return null
}
reportedFiles.addAll(getFilesReportedByProblemSearch(editor))
val curScope = psiMember.useScope
member.scope = prevScope.union(curScope)
}
return reportedFiles
}
private fun getMembersToSearch(member: ScopedMember, modification: Modification, members: List<ScopedMember>): List<ScopedMember>? {
if (!modification.searchAllMembers()) return listOf(member)
if (members.any { !isCheapToSearch(it.psiMember) }) return null
return members
}
private fun rehighlight(psiFile: PsiFile, editor: Editor): List<HighlightInfo> {
PsiDocumentManager.getInstance(myProject).commitAllDocuments()
return CodeInsightTestFixtureImpl.instantiateAndRun(psiFile, editor, ArrayUtilRt.EMPTY_INT_ARRAY, false)
}
private fun openEditor(virtualFile: VirtualFile) =
FileEditorManager.getInstance(myProject).openTextEditor(OpenFileDescriptor(myProject, virtualFile), true)!!
private fun findRelatedFiles(psiFile: PsiFile): Set<VirtualFile> {
val targetFile = psiFile.virtualFile
if (psiFile !is PsiClassOwner) return mutableSetOf()
return psiFile.classes.asSequence()
.flatMap { ReferencesSearch.search(it).findAll().asSequence() }
.map { it.element }
.filter { !JavaResolveUtil.isInJavaDoc(it) }
.mapNotNull { it.containingFile }
.distinctBy { it.virtualFile }
.mapNotNullTo(mutableSetOf()) {
val virtualFile = it.virtualFile
if (virtualFile == targetFile || hasErrors(it)) null else virtualFile
}
}
private fun findMembers(psiFile: PsiClassOwner): List<ScopedMember> {
return MemberCollector.collectMembers(psiFile) { member ->
if (member is PsiMethod && member.isConstructor) return@collectMembers false
val modifiers = member.modifierList ?: return@collectMembers true
return@collectMembers !modifiers.hasExplicitModifier(PsiModifier.PRIVATE)
}.map { ScopedMember(it, it.useScope) }
}
private fun findUsages(target: PsiMember): List<PsiElement>? {
if (!isCheapToSearch(target)) return null
val members = PsiTreeUtil.collectParents(target, PsiMember::class.java, true) { false }
val usages = mutableListOf<PsiElement>()
for (member in members) {
val name = member.name ?: return null
val scope = member.useScope as? GlobalSearchScope ?: return null
val usageExtractor: (PsiFile, Int) -> PsiElement? = lambda@{ psiFile, index ->
val identifier = psiFile.findElementAt(index) as? PsiIdentifier ?: return@lambda null
return@lambda when (val parent = identifier.parent) {
is PsiReference -> if (parent.isReferenceTo(member)) parent else null
is PsiMethod -> if (isOverride(parent, member)) parent else null
else -> null
}
}
val memberUsages = MemberUsageCollector.collect(name, member.containingFile, scope, usageExtractor) ?: return null
usages.addAll(memberUsages)
}
return usages
}
private fun isCheapToSearch(member: PsiMember): Boolean {
val name = member.name ?: return false
val module = ModuleUtilCore.findModuleForPsiElement(member) ?: return false
val scope = GlobalSearchScope.moduleScope(module)
val memberFile = member.containingFile
return PsiSearchHelper.getInstance(myProject).isCheapEnoughToSearch(name, scope, memberFile, null) != TOO_MANY_OCCURRENCES
}
private fun isOverride(possibleOverride: PsiMethod, target: PsiMember): Boolean {
val targetMethod = target as? PsiMethod ?: return false
val overrideClass = possibleOverride.containingClass ?: return false
val targetClass = targetMethod.containingClass ?: return false
if (!overrideClass.isInheritor(targetClass, true)) return false
return possibleOverride == JavaOverridingMethodsSearcher.findOverridingMethod(overrideClass, target, targetClass)
}
private fun findFilesWithProblems(relatedFiles: Set<VirtualFile>, members: List<ScopedMember>): Set<VirtualFile> {
val psiManager = PsiManager.getInstance(myProject)
val filesWithErrors = mutableSetOf<VirtualFile>()
for (file in relatedFiles) {
val psiFile = psiManager.findFile(file) ?: continue
if (hasErrors(psiFile, members)) filesWithErrors.add(file)
}
return filesWithErrors
}
private fun hasErrors(psiFile: PsiFile, members: List<ScopedMember>? = null): Boolean {
val infos = rehighlight(psiFile, openEditor(psiFile.virtualFile))
return infos.any { info ->
if (info.severity != HighlightSeverity.ERROR) return@any false
if (members == null) return@any true
val startElement = psiFile.findElementAt(info.actualStartOffset) ?: return@any false
val endElement = psiFile.findElementAt(info.actualEndOffset - 1) ?: return@any false
val reported = PsiTreeUtil.findCommonParent(startElement, endElement) ?: return@any false
if (JavaResolveUtil.isInJavaDoc(reported)) return@any false
val context = PsiTreeUtil.getNonStrictParentOfType(reported,
PsiStatement::class.java, PsiClass::class.java,
PsiMethod::class.java, PsiField::class.java,
PsiReferenceList::class.java) ?: return@any false
return@any StreamEx.ofTree(context, { StreamEx.of(*it.children) })
.anyMatch { el -> el is PsiReference && members.any { m -> el.isReferenceTo(m.psiMember) && inScope(el.containingFile, m.scope) } }
}
}
private fun inScope(psiFile: PsiFile, scope: SearchScope): Boolean = scope.contains(psiFile.virtualFile)
private fun findRelatedProblems(problems: Map<PsiMember, Set<Problem>>, relatedFiles: Set<VirtualFile>): Map<PsiMember, Set<Problem>> {
val relatedProblems = mutableMapOf<PsiMember, Set<Problem>>()
for ((member, memberProblems) in problems) {
val memberRelatedProblems = mutableSetOf<Problem>()
for (memberProblem in memberProblems) {
val problemFile = memberProblem.reportedElement.containingFile
if (problemFile.virtualFile in relatedFiles) memberRelatedProblems.add(memberProblem)
}
if (memberRelatedProblems.isNotEmpty()) relatedProblems[member] = memberRelatedProblems
}
return relatedProblems
}
private fun extractMemberProblems(member: PsiMember, memberProblems: Set<Problem>): String {
data class ProblemData(val fileName: String, val offset: Int, val reportedElement: String,
val context: String?, val fileErrors: List<HighlightInfo>)
fun getProblemData(problem: Problem): ProblemData {
val context = problem.context
val reportedElement = problem.reportedElement
val psiFile = reportedElement.containingFile
val fileName = psiFile.name
val offset = reportedElement.textOffset
val textEditor = FileEditorManager.getInstance(myProject).openFile(psiFile.virtualFile, true)[0] as TextEditor
val fileErrors = rehighlight(psiFile, textEditor.editor).filter { it.severity == HighlightSeverity.ERROR }
return ProblemData(fileName, offset, reportedElement.text, context.text, fileErrors)
}
return "Member: ${JavaDocUtil.getReferenceText(member.project, member)}," +
" Problems: ${memberProblems.map { getProblemData(it) }}\n"
}
private fun getFilesReportedByProblemSearch(editor: Editor): Set<VirtualFile> =
ProjectProblemUtils.getReportedProblems(editor).asSequence()
.flatMap { it.value.asSequence() }
.map { it.reportedElement.containingFile }
.mapTo(mutableSetOf()) { it.virtualFile }
private sealed class Modification(protected val member: PsiMember, env: ImperativeCommand.Environment) {
abstract fun apply(project: Project)
abstract override fun toString(): String
open fun searchAllMembers(): Boolean = false
companion object {
val classModifications = arrayOf(::ChangeName, ::ExplicitModifierModification, ::ChangeExtendsList, ::MakeClassInterface)
val methodModifications = arrayOf(::ChangeName, ::ExplicitModifierModification, ::ChangeType, ::AddParam)
val fieldModifications = arrayOf(::ChangeName, ::ExplicitModifierModification, ::ChangeType)
fun getPossibleModifications(member: PsiMember, env: ImperativeCommand.Environment) = when (member) {
is PsiClass -> classModifications.map { it(member, env) }
is PsiMethod -> methodModifications.map { it(member, env) }
is PsiField -> if (member is PsiEnumConstant) emptyList() else fieldModifications.map { it(member, env) }
else -> emptyList()
}
private fun String.absHash(): Int {
val hash = hashCode()
return if (hash == Int.MIN_VALUE) Int.MAX_VALUE else hash.absoluteValue
}
}
private class ChangeName(member: PsiMember, env: ImperativeCommand.Environment) : Modification(member, env) {
private val newName: String
init {
val namedMember = member as PsiNameIdentifierOwner
val identifier = namedMember.nameIdentifier!!
val oldName = identifier.text
newName = oldName + oldName.absHash()
}
override fun apply(project: Project) {
val factory = JavaPsiFacade.getElementFactory(project)
(member as PsiNameIdentifierOwner).nameIdentifier!!.replace(factory.createIdentifier(newName))
}
override fun toString(): String = "ChangeName: new name is '$newName'"
}
private class ExplicitModifierModification(member: PsiMember, env: ImperativeCommand.Environment) : Modification(member, env) {
private val modifier: String = env.generateValue(Generator.sampledFrom(*MODIFIERS), null)
override fun apply(project: Project) {
val modifiers = member.modifierList ?: return
val hasModifier = modifiers.hasExplicitModifier(modifier)
if (!hasModifier && isAccessModifier(modifier)) {
val curAccessModifier = getAccessModifier(modifiers)
if (curAccessModifier != null) modifiers.setModifierProperty(curAccessModifier, false)
}
modifiers.setModifierProperty(modifier, !hasModifier)
}
companion object {
private val MODIFIERS = arrayOf(PsiModifier.PUBLIC, PsiModifier.PROTECTED,
PsiModifier.PRIVATE, PsiModifier.STATIC,
PsiModifier.ABSTRACT, PsiModifier.FINAL)
private val ACCESS_MODIFIERS = arrayOf(PsiModifier.PRIVATE, PsiModifier.PUBLIC, PsiModifier.PROTECTED)
private fun isAccessModifier(modifier: String) = modifier in ACCESS_MODIFIERS
private fun getAccessModifier(modifiers: PsiModifierList): String? =
sequenceOf(*ACCESS_MODIFIERS).firstOrNull { modifiers.hasExplicitModifier(it) }
}
override fun toString(): String = "ExplicitModifierModification: tweaking modifier '$modifier'"
}
private class ChangeType(member: PsiMember, env: ImperativeCommand.Environment) : Modification(member, env) {
private val typeElement = env.generateValue(Generator.sampledFrom(findTypeElements(member)), null)
private val newType = if (typeElement.type == PsiPrimitiveType.INT) TypeUtils.getStringType(typeElement) else PsiPrimitiveType.INT
override fun apply(project: Project) {
val factory = JavaPsiFacade.getElementFactory(project)
typeElement.replace(factory.createTypeElement(newType))
}
private fun findTypeElements(member: PsiMember): List<PsiTypeElement> {
return StreamEx.ofTree(member as PsiElement) { el ->
if (el is PsiCodeBlock || el is PsiComment) StreamEx.empty()
else StreamEx.of(*el.children)
}.filterIsInstance<PsiTypeElement>()
}
override fun toString(): String =
"ChangeType: '${typeElement.type.canonicalText}' is changed to '${newType.canonicalText}'"
}
private class AddParam(method: PsiMethod, env: ImperativeCommand.Environment) : Modification(method, env) {
val paramName: String
init {
val methodName = method.name
paramName = methodName + methodName.absHash()
}
override fun apply(project: Project) {
val factory = JavaPsiFacade.getElementFactory(project)
val param = factory.createParameter(paramName, PsiType.INT)
(member as PsiMethod).parameterList.add(param)
}
override fun toString(): String = "AddParam: param '$paramName' added"
}
private class ChangeExtendsList(psiClass: PsiClass, env: ImperativeCommand.Environment) : Modification(psiClass, env) {
private val parentRef: PsiElement?
init {
val refs = psiClass.extendsList?.referenceElements
parentRef = if (refs == null || refs.size != 1) null else refs[0].element
}
override fun apply(project: Project) {
if (parentRef == null) return
val factory = JavaPsiFacade.getElementFactory(project)
parentRef.replace(factory.createTypeElement(TypeUtils.getObjectType(parentRef)))
}
override fun searchAllMembers() = true
override fun toString(): String =
if (parentRef != null) "ChangeExtendsList: change '${parentRef.text}' to 'java.lang.Object'"
else "ChangeExtendsList: class doesn't extend anything, do nothing"
}
private class MakeClassInterface(psiClass: PsiClass, env: ImperativeCommand.Environment) : Modification(psiClass, env) {
override fun apply(project: Project) {
val psiClass = member as PsiClass
if (psiClass.isEnum || psiClass.isInterface || psiClass.isAnnotationType) return
val classKeyword = PsiTreeUtil.getPrevSiblingOfType(psiClass.nameIdentifier!!, PsiKeyword::class.java) ?: return
val factory = JavaPsiFacade.getElementFactory(project)
val newTypeKeyword = factory.createKeyword(PsiKeyword.INTERFACE)
PsiUtil.setModifierProperty(psiClass, PsiModifier.ABSTRACT, false)
PsiUtil.setModifierProperty(psiClass, PsiModifier.FINAL, false)
classKeyword.replace(newTypeKeyword)
}
override fun searchAllMembers() = true
override fun toString(): String = "MakeClassInterface: type changed to 'interface'"
}
}
}
|
apache-2.0
|
e2b431685cb4c5ac650c1e575f969571
| 44.947253 | 140 | 0.719684 | 4.918824 | false | false | false | false |
siosio/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertFunctionTypeReceiverToParameterIntention.kt
|
1
|
11592
|
// 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.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.util.RefactoringUIUtil
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.builtins.getReceiverTypeFromFunctionType
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.core.*
import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress
import org.jetbrains.kotlin.idea.refactoring.CallableRefactoring
import org.jetbrains.kotlin.idea.refactoring.checkConflictsInteractively
import org.jetbrains.kotlin.idea.refactoring.getAffectedCallables
import org.jetbrains.kotlin.idea.references.KtSimpleReference
import org.jetbrains.kotlin.idea.search.usagesSearch.searchReferencesOrMethodReferences
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.psi.typeRefHelpers.setReceiverTypeReference
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getAbbreviatedTypeOrType
import org.jetbrains.kotlin.resolve.calls.resolvedCallUtil.getArgumentByParameterIndex
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
class ConvertFunctionTypeReceiverToParameterIntention : SelfTargetingRangeIntention<KtTypeReference>(
KtTypeReference::class.java,
KotlinBundle.lazyMessage("convert.function.type.receiver.to.parameter")
) {
class ConversionData(
val functionParameterIndex: Int,
val lambdaReceiverType: KotlinType,
val function: KtFunction
) {
val functionDescriptor by lazy { function.unsafeResolveToDescriptor() as FunctionDescriptor }
}
class FunctionDefinitionInfo(element: KtFunction) : AbstractProcessableUsageInfo<KtFunction, ConversionData>(element) {
override fun process(data: ConversionData, elementsToShorten: MutableList<KtElement>) {
val function = element ?: return
val functionParameter = function.valueParameters.getOrNull(data.functionParameterIndex) ?: return
val functionType = functionParameter.typeReference?.typeElement as? KtFunctionType ?: return
val functionTypeParameterList = functionType.parameterList ?: return
val functionTypeReceiver = functionType.receiverTypeReference ?: return
val parameterToAdd = KtPsiFactory(project).createFunctionTypeParameter(functionTypeReceiver)
functionTypeParameterList.addParameterBefore(parameterToAdd, functionTypeParameterList.parameters.firstOrNull())
functionType.setReceiverTypeReference(null)
}
}
class ParameterCallInfo(element: KtCallExpression) : AbstractProcessableUsageInfo<KtCallExpression, ConversionData>(element) {
override fun process(data: ConversionData, elementsToShorten: MutableList<KtElement>) {
val callExpression = element ?: return
val qualifiedExpression = callExpression.getQualifiedExpressionForSelector() ?: return
val receiverExpression = qualifiedExpression.receiverExpression
val argumentList = callExpression.getOrCreateValueArgumentList()
argumentList.addArgumentBefore(KtPsiFactory(project).createArgument(receiverExpression), argumentList.arguments.firstOrNull())
qualifiedExpression.replace(callExpression)
}
}
class LambdaInfo(element: KtLambdaExpression) : AbstractProcessableUsageInfo<KtLambdaExpression, ConversionData>(element) {
override fun process(data: ConversionData, elementsToShorten: MutableList<KtElement>) {
val lambda = element?.functionLiteral ?: return
val context = lambda.analyze(BodyResolveMode.PARTIAL)
val psiFactory = KtPsiFactory(project)
val validator = CollectingNameValidator(
lambda.valueParameters.mapNotNull { it.name },
NewDeclarationNameValidator(lambda.bodyExpression!!, null, NewDeclarationNameValidator.Target.VARIABLES)
)
val newParameterName = KotlinNameSuggester.suggestNamesByType(data.lambdaReceiverType, validator, "p").first()
val newParameterRefExpression = psiFactory.createExpression(newParameterName)
lambda.forEachDescendantOfType<KtThisExpression> {
val thisTarget = context[BindingContext.REFERENCE_TARGET, it.instanceReference] ?: return@forEachDescendantOfType
if (DescriptorToSourceUtilsIde.getAnyDeclaration(project, thisTarget) == lambda) {
it.replace(newParameterRefExpression)
}
}
val lambdaParameterList = lambda.getOrCreateParameterList()
val parameterToAdd = psiFactory.createLambdaParameterList(newParameterName).parameters.first()
lambdaParameterList.addParameterBefore(parameterToAdd, lambdaParameterList.parameters.firstOrNull())
}
}
private inner class Converter(
private val data: ConversionData,
editor: Editor?,
) : CallableRefactoring<CallableDescriptor>(data.function.project, editor, data.functionDescriptor, text) {
override fun performRefactoring(descriptorsForChange: Collection<CallableDescriptor>) {
val callables = getAffectedCallables(project, descriptorsForChange)
val conflicts = MultiMap<PsiElement, String>()
val usages = ArrayList<AbstractProcessableUsageInfo<*, ConversionData>>()
project.runSynchronouslyWithProgress(KotlinBundle.message("looking.for.usages.and.conflicts"), true) {
runReadAction {
val progressStep = 1.0 / callables.size
val progressIndicator = ProgressManager.getInstance().progressIndicator
progressIndicator.isIndeterminate = false
for ((i, callable) in callables.withIndex()) {
progressIndicator.fraction = (i + 1) * progressStep
if (callable !is KtFunction) continue
if (!checkModifiable(callable)) {
val renderedCallable = RefactoringUIUtil.getDescription(callable, true).capitalize()
conflicts.putValue(callable, KotlinBundle.message("can.t.modify.0", renderedCallable))
}
for (ref in callable.searchReferencesOrMethodReferences()) {
if (ref !is KtSimpleReference<*>) continue
processExternalUsage(ref, usages)
}
usages += FunctionDefinitionInfo(callable)
processInternalUsages(callable, usages)
}
}
}
project.checkConflictsInteractively(conflicts) {
project.executeWriteCommand(text) {
val elementsToShorten = ArrayList<KtElement>()
usages.sortedByDescending { it.element?.textOffset }.forEach { it.process(data, elementsToShorten) }
ShortenReferences.DEFAULT.process(elementsToShorten)
}
}
}
private fun processExternalUsage(
ref: KtSimpleReference<*>,
usages: java.util.ArrayList<AbstractProcessableUsageInfo<*, ConversionData>>
) {
val callElement = ref.element.getParentOfTypeAndBranch<KtCallElement> { calleeExpression } ?: return
val context = callElement.analyze(BodyResolveMode.PARTIAL)
val expressionToProcess = callElement
.getArgumentByParameterIndex(data.functionParameterIndex, context)
.singleOrNull()
?.getArgumentExpression()
?.let { KtPsiUtil.safeDeparenthesize(it) }
?: return
if (expressionToProcess is KtLambdaExpression) {
usages += LambdaInfo(expressionToProcess)
}
}
private fun processInternalUsages(
callable: KtFunction,
usages: java.util.ArrayList<AbstractProcessableUsageInfo<*, ConversionData>>
) {
val body = when (callable) {
is KtConstructor<*> -> callable.containingClassOrObject?.body
else -> callable.bodyExpression
}
if (body != null) {
val functionParameter = callable.valueParameters.getOrNull(data.functionParameterIndex) ?: return
for (ref in ReferencesSearch.search(functionParameter, LocalSearchScope(body))) {
val element = ref.element as? KtSimpleNameExpression ?: continue
val callExpression = element.getParentOfTypeAndBranch<KtCallExpression> { calleeExpression } ?: continue
usages += ParameterCallInfo(callExpression)
}
}
}
}
private fun KtTypeReference.getConversionData(): ConversionData? {
val functionTypeReceiver = parent as? KtFunctionTypeReceiver ?: return null
val functionType = functionTypeReceiver.parent as? KtFunctionType ?: return null
val lambdaReceiverType = functionType
.getAbbreviatedTypeOrType(functionType.analyze(BodyResolveMode.PARTIAL))
?.getReceiverTypeFromFunctionType()
?: return null
val containingParameter = (functionType.parent as? KtTypeReference)?.parent as? KtParameter ?: return null
val ownerFunction = containingParameter.ownerFunction as? KtFunction ?: return null
val functionParameterIndex = ownerFunction.valueParameters.indexOf(containingParameter)
return ConversionData(functionParameterIndex, lambdaReceiverType, ownerFunction)
}
override fun startInWriteAction(): Boolean = false
override fun applicabilityRange(element: KtTypeReference): TextRange? {
val data = element.getConversionData() ?: return null
val elementBefore = data.function.valueParameters[data.functionParameterIndex].typeReference!!.typeElement as KtFunctionType
val elementAfter = elementBefore.copied().apply {
parameterList?.addParameterBefore(
KtPsiFactory(element).createFunctionTypeParameter(element),
parameterList?.parameters?.firstOrNull()
)
setReceiverTypeReference(null)
}
setTextGetter(KotlinBundle.lazyMessage("convert.0.to.1", elementBefore.text, elementAfter.text))
return element.textRange
}
override fun applyTo(element: KtTypeReference, editor: Editor?) {
element.getConversionData()?.let { Converter(it, editor).run() }
}
}
|
apache-2.0
|
e6a815faf46eb9dc819b73627fecef75
| 51.220721 | 158 | 0.702899 | 6.081847 | false | false | false | false |
dowenliu-xyz/ketcd
|
ketcd-core/src/main/kotlin/xyz/dowenliu/ketcd/client/EtcdLeaseServiceImpl.kt
|
1
|
6598
|
package xyz.dowenliu.ketcd.client
import com.google.common.util.concurrent.ListenableFuture
import io.grpc.ManagedChannel
import io.grpc.stub.StreamObserver
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import xyz.dowenliu.ketcd.api.*
import xyz.dowenliu.ketcd.client.EtcdLeaseService.KeepAliveEventHandler
import xyz.dowenliu.ketcd.client.EtcdLeaseService.KeepAliveSentinel
import xyz.dowenliu.ketcd.exception.LeaseNotFoundException
import java.util.concurrent.*
import java.util.concurrent.atomic.AtomicLong
/**
* Implementation of etcd lease service.
*
* create at 2017/4/26
* @author liufl
* @since 0.1.0
*/
class EtcdLeaseServiceImpl internal constructor(override val client: EtcdClient) : EtcdLeaseService {
/**
* Companion object of [EtcdLeaseServiceImpl]
*/
companion object {
private val logger: Logger = LoggerFactory.getLogger(EtcdLeaseServiceImpl::class.java)
private val keepAliveThreadGroup = ThreadGroup("lease-keep-alive")
private val threadCounter = AtomicLong()
}
private val channel: ManagedChannel = client.channelBuilder.build()
private val blockingStub = configureStub(LeaseGrpc.newBlockingStub(channel), client.token)
private val futureStub = configureStub(LeaseGrpc.newFutureStub(channel), client.token)
private val asyncStub = configureStub(LeaseGrpc.newStub(channel), client.token)
/**
* Close this service instance.
*/
override fun close() {
channel.shutdownNow()
}
private fun grantRequest(ttl: Long, leaseId: Long): LeaseGrantRequest =
LeaseGrantRequest.newBuilder().setTTL(ttl).setID(leaseId).build()
override fun grant(ttl: Long, leaseId: Long): LeaseGrantResponse =
blockingStub.leaseGrant(grantRequest(ttl, leaseId))
override fun grantInFuture(ttl: Long, leaseId: Long): ListenableFuture<LeaseGrantResponse> =
futureStub.leaseGrant(grantRequest(ttl, leaseId))
override fun grantAsync(ttl: Long, leaseId: Long, callback: ResponseCallback<LeaseGrantResponse>) =
asyncStub.leaseGrant(grantRequest(ttl, leaseId), CallbackStreamObserver(callback))
private fun timeToLiveRequest(leaseId: Long, withKeys: Boolean): LeaseTimeToLiveRequest =
LeaseTimeToLiveRequest.newBuilder().setID(leaseId).setKeys(withKeys).build()
override fun timeToLive(leaseId: Long, withKeys: Boolean): LeaseTimeToLiveResponse =
blockingStub.leaseTimeToLive(timeToLiveRequest(leaseId, withKeys))
override fun timeToLiveInFuture(leaseId: Long, withKeys: Boolean): ListenableFuture<LeaseTimeToLiveResponse> =
futureStub.leaseTimeToLive(timeToLiveRequest(leaseId, withKeys))
override fun timeToLiveAsync(leaseId: Long,
withKeys: Boolean,
callback: ResponseCallback<LeaseTimeToLiveResponse>) =
asyncStub.leaseTimeToLive(timeToLiveRequest(leaseId, withKeys), CallbackStreamObserver(callback))
override fun revoke(leaseId: Long): LeaseRevokeResponse =
blockingStub.leaseRevoke(LeaseRevokeRequest.newBuilder().setID(leaseId).build())
override fun revokeInFuture(leaseId: Long): ListenableFuture<LeaseRevokeResponse> =
futureStub.leaseRevoke(LeaseRevokeRequest.newBuilder().setID(leaseId).build())
override fun revokeAsync(leaseId: Long, callback: ResponseCallback<LeaseRevokeResponse>) =
asyncStub.leaseRevoke(LeaseRevokeRequest.newBuilder().setID(leaseId).build(),
CallbackStreamObserver(callback))
override fun keepAlive(leaseId: Long, eventHandler: KeepAliveEventHandler?): KeepAliveSentinel =
MyKeepAliveSentinel(leaseId, eventHandler)
private inner class MyKeepAliveSentinel(val leaseId: Long,
val eventHandler: KeepAliveEventHandler?) : KeepAliveSentinel {
private var closed: Boolean = false
private var ttlSignal: BlockingQueue<Long> = ArrayBlockingQueue(1)
private val scheduledExecutor = Executors.newSingleThreadScheduledExecutor {
Thread(keepAliveThreadGroup, it, "lease-$leaseId-keep-alive-thread-${threadCounter.incrementAndGet()}")
// The thread should not be daemon, JVM stop after this thread stop.
}
private val keepAliveResponseStreamObserver: StreamObserver<LeaseKeepAliveResponse> =
object : StreamObserver<LeaseKeepAliveResponse> {
override fun onNext(value: LeaseKeepAliveResponse?) {
if (isClosed()) return
value?.let {
if (logger.isDebugEnabled)
logger.debug("Lease [$leaseId] keep alive response: $it")
ttlSignal.clear()
ttlSignal.put(it.ttl)
try {
scheduledExecutor.schedule({ heartbeat() }, it.ttl / 2 + 1, TimeUnit.SECONDS)
} catch (e: RejectedExecutionException) {
if (!isClosed()) throw e
}
eventHandler?.onResponse(it)
}
}
override fun onError(t: Throwable?) {
t?.let {
logger.debug("Lease [$leaseId] keep alive error:", t)
eventHandler?.onError(it)
}
}
override fun onCompleted() {
logger.debug("Lease [$leaseId] keep alive stream closed.")
}
}
private val keepAliveRequestStreamObserver: StreamObserver<LeaseKeepAliveRequest> =
asyncStub.leaseKeepAlive(keepAliveResponseStreamObserver)
init {
heartbeat()
val ttl = ttlSignal.take()
if (ttl <= 0L) {
close()
throw LeaseNotFoundException("Can not find lease with it $leaseId, maybe it's expired yet.")
}
}
private fun heartbeat() {
this.keepAliveRequestStreamObserver.onNext(LeaseKeepAliveRequest.newBuilder().setID(leaseId).build())
}
@Synchronized
override fun isClosed(): Boolean = closed
@Synchronized
override fun close() {
this.keepAliveRequestStreamObserver.onCompleted()
this.scheduledExecutor.shutdown()
closed = true
}
}
}
|
apache-2.0
|
05eea204621618be32d8453a554b7439
| 44.19863 | 115 | 0.642164 | 5.032799 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/JavaMapForEachInspection.kt
|
2
|
2879
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.builtins.DefaultBuiltIns
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.getLastLambdaExpression
import org.jetbrains.kotlin.idea.inspections.collections.isMap
import org.jetbrains.kotlin.idea.util.textRangeIn
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.synthetic.isResolvedWithSamConversions
class JavaMapForEachInspection : AbstractApplicabilityBasedInspection<KtCallExpression>(
KtCallExpression::class.java
) {
override fun isApplicable(element: KtCallExpression): Boolean {
val calleeExpression = element.calleeExpression ?: return false
if (calleeExpression.text != "forEach") return false
if (element.valueArguments.size != 1) return false
val lambda = element.lambda() ?: return false
val lambdaParameters = lambda.valueParameters
if (lambdaParameters.size != 2 || lambdaParameters.any { it.destructuringDeclaration != null }) return false
val context = element.analyze(BodyResolveMode.PARTIAL)
val resolvedCall = element.getResolvedCall(context) ?: return false
return resolvedCall.dispatchReceiver?.type?.isMap(DefaultBuiltIns.Instance) == true && resolvedCall.isResolvedWithSamConversions()
}
override fun inspectionHighlightRangeInElement(element: KtCallExpression): TextRange? = element.calleeExpression?.textRangeIn(element)
override fun inspectionText(element: KtCallExpression) =
KotlinBundle.message("java.map.foreach.method.call.should.be.replaced.with.kotlin.s.foreach")
override val defaultFixText get() = KotlinBundle.message("replace.with.kotlin.s.foreach")
override fun applyTo(element: KtCallExpression, project: Project, editor: Editor?) {
val lambda = element.lambda() ?: return
val valueParameters = lambda.valueParameters
lambda.functionLiteral.valueParameterList?.replace(
KtPsiFactory(element).createLambdaParameterList("(${valueParameters[0].text}, ${valueParameters[1].text})")
)
}
private fun KtCallExpression.lambda(): KtLambdaExpression? {
return lambdaArguments.singleOrNull()?.getArgumentExpression() as? KtLambdaExpression ?: getLastLambdaExpression()
}
}
|
apache-2.0
|
fefb6d68f99b5f673c65e4cfd78a6b87
| 50.410714 | 158 | 0.777353 | 4.989601 | false | false | false | false |
GunoH/intellij-community
|
plugins/full-line/src/org/jetbrains/completion/full/line/platform/handlers/FullLineInsertHandler.kt
|
2
|
4446
|
package org.jetbrains.completion.full.line.platform.handlers
import com.intellij.codeInsight.completion.InsertHandler
import com.intellij.codeInsight.completion.InsertionContext
import com.intellij.codeInsight.template.impl.LiveTemplateLookupElementImpl
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Document
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.TextRange
import org.jetbrains.completion.full.line.language.FullLineLanguageSupporter
import org.jetbrains.completion.full.line.platform.FullLineLookupElement
import org.jetbrains.completion.full.line.platform.diagnostics.FullLinePart
import org.jetbrains.completion.full.line.platform.diagnostics.logger
import org.jetbrains.completion.full.line.settings.state.MLServerCompletionSettings
class FullLineInsertHandler private constructor(private val supporter: FullLineLanguageSupporter) :
InsertHandler<FullLineLookupElement> {
override fun handleInsert(context: InsertionContext, item: FullLineLookupElement) {
ApplicationManager.getApplication().runWriteAction {
val document = context.document
val offset = context.tailOffset
var completionRange = TextRange(context.startOffset + item.head.length, context.selectionEndOffset)
if (item.suffix.isNotEmpty()) {
context.document.insertString(context.selectionEndOffset, item.suffix)
context.commitDocument()
completionRange = completionRange.grown(item.suffix.length)
}
val endLine = document.getLineEndOffset(document.getLineNumber(offset))
if (LOG.isDebugEnabled) {
val starLine = document.getLineStartOffset(document.getLineNumber(offset))
LOG.debug(
"Full line with picked suggestion: `"
+ document.getText(starLine, context.startOffset)
+ "|${document.getText(context.startOffset, context.tailOffset)}|"
+ document.getText(context.tailOffset, endLine)
+ "`."
)
}
val elementAtStart = context.file.findElementAt(completionRange.startOffset) ?: return@runWriteAction
removeOverwritingChars(
document.getText(TextRange.create(completionRange.startOffset, offset)),
document.getText(TextRange.create(context.selectionEndOffset, endLine))
).takeIf { it > 0 }?.run {
LOG.debug("Removing overwriting characters `${document.text.substring(offset, +offset)}`.")
document.deleteString(offset, plus(offset))
}
if (
MLServerCompletionSettings.getInstance().enableStringsWalking(supporter.language)
&& supporter.isStringWalkingEnabled(elementAtStart)
) {
val template = supporter.createStringTemplate(context.file, TextRange(context.startOffset, completionRange.endOffset))
if (template != null) {
LOG.debug("Create string-walking template `${template.string}`.")
LiveTemplateLookupElementImpl.startTemplate(context, template)
}
}
ProgressManager.getInstance().executeNonCancelableSection {
val importedElements = supporter.autoImportFix(context.file, context.editor, completionRange)
if (LOG.isDebugEnabled && importedElements.isNotEmpty()) {
val a = "Elements were imported:" + importedElements.joinToString("--\n\t--") {
it.text
}
LOG.debug(a)
}
}
}
}
private fun removeOverwritingChars(completion: String, line: String): Int {
var amount = 0
for (char in line) {
var found = false
for (charWithOffset in completion.drop(amount)) {
if (!charWithOffset.isLetterOrWhitespace() && charWithOffset == char) {
found = true
break
}
}
if (found) {
amount++
}
else {
break
}
}
return amount
}
private fun Char.isLetterOrWhitespace(): Boolean {
return isWhitespace() || isLetter()
}
companion object {
private val LOG = logger<FullLineInsertHandler>(FullLinePart.PRE_PROCESSING)
fun of(context: InsertionContext, supporter: FullLineLanguageSupporter): InsertHandler<FullLineLookupElement> {
return when (context.completionChar) {
'\t' -> FirstTokenInsertHandler(supporter)
else -> FullLineInsertHandler(supporter)
}
}
}
}
fun Document.getText(start: Int, end: Int): String {
return text.substring(start, end)
}
|
apache-2.0
|
47d9a0a16773d85657831370c6ed7409
| 37 | 126 | 0.711876 | 4.806486 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/compiler-reference-index/tests/test/org/jetbrains/kotlin/idea/search/refIndex/AbstractKotlinCompilerReferenceTest.kt
|
4
|
2772
|
// 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.search.refIndex
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.intellij.testFramework.assertEqualsToFile
import org.jetbrains.kotlin.utils.addToStdlib.ifNotEmpty
import kotlin.io.path.Path
import kotlin.io.path.listDirectoryEntries
import kotlin.io.path.name
import kotlin.io.path.reader
abstract class AbstractKotlinCompilerReferenceTest : KotlinCompilerReferenceTestBase() {
override fun setUp() {
super.setUp()
installCompiler()
}
protected fun doTest(testDataFilePath: String) {
myFixture.testDataPath = testDataFilePath
val configurationPath = Path(testDataFilePath, "testConfig.json")
val config: JsonObject = JsonParser.parseReader(configurationPath.reader()).asJsonObject
val mainFile = config[MAIN_FILE]?.asString ?: error("Main file not found")
val shouldBeUsage = config[SHOULD_BE_USAGE]?.asJsonArray?.map { it.asString }?.toSet().orEmpty()
val allFiles = listOf(mainFile) + Path(testDataFilePath).listDirectoryEntries().map { it.name }.minus(mainFile)
myFixture.configureByFiles(*allFiles.toTypedArray())
rebuildProject()
val actualUsages = getReferentFilesForElementUnderCaret()
assertEqualsToFile(
"",
configurationPath.toFile(),
createActualText(mainFile, actualUsages, shouldBeUsage)
)
}
companion object {
private const val USAGES = "usages"
private const val SHOULD_BE_USAGE = "shouldBeUsage"
private const val MAIN_FILE = "mainFile"
private fun createActualText(mainFile: String, actualUsages: Set<String>?, shouldBeUsage: Set<String>): String {
val mainFileText = createPair(MAIN_FILE, "\"$mainFile\"")
val actualUsagesText = actualUsages?.ifNotEmpty { createPair(USAGES, createArray(this)) }
val shouldBeFixedText = shouldBeUsage.minus(actualUsages.orEmpty()).ifNotEmpty {
createPair(SHOULD_BE_USAGE, createArray(this))
}
return listOfNotNull(mainFileText, actualUsagesText, shouldBeFixedText).joinToString(
prefix = "{\n ",
separator = ",\n ",
postfix = "\n}"
)
}
private fun createArray(values: Set<String>): String = values.sorted().joinToString(
prefix = "[\n \"",
separator = "\",\n \"",
postfix = "\"\n ]"
)
private fun createPair(name: String, value: String) = "\"$name\": $value"
}
}
|
apache-2.0
|
cdf46c6bf1353106bcd0cd7c65d25450
| 40.38806 | 158 | 0.659812 | 4.771084 | false | true | false | false |
GunoH/intellij-community
|
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/index/SubpackageIndexServiceTest.kt
|
7
|
2525
|
// 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.index
import org.jetbrains.kotlin.idea.base.indices.KotlinPackageIndexUtils
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.scopes.MemberScope
class SubpackageIndexServiceTest : KotlinLightCodeInsightFixtureTestCase() {
fun testBasicWithoutCaching() {
setupSimpleTest()
basicSimpleTest()
}
fun testBasicWithCaching() {
setupSimpleTest()
basicSimpleTest()
basicSimpleTest()
}
private fun basicSimpleTest() {
val fqName1 = FqName("foo")
val fqName2 = fqName1.child(Name.identifier("bar"))
val fqName30 = fqName2.child(Name.identifier("zoo"))
val fqName31 = fqName2.child(Name.identifier("moo"))
listOf(FqName.ROOT, fqName1, fqName2, fqName30, fqName31).forEach {
assertTrue("fqName `${it.asString()}` should exist", KotlinPackageIndexUtils.packageExists(it, project))
}
val scope = module.moduleProductionSourceScope
listOf(FqName.ROOT, fqName1, fqName2, fqName30, fqName31).forEach {
assertTrue("fqName `${it.asString()}` should exist", KotlinPackageIndexUtils.packageExists(it, scope))
}
listOf(fqName2.child(Name.identifier("doo")), FqName("a")).forEach {
assertFalse("fqName `${it.asString()}` shouldn't exist", KotlinPackageIndexUtils.packageExists(it, scope))
}
assertSameElements(listOf(fqName1), KotlinPackageIndexUtils.getSubpackages(FqName.ROOT, scope, MemberScope.ALL_NAME_FILTER))
assertSameElements(listOf(fqName2), KotlinPackageIndexUtils.getSubpackages(fqName1, scope, MemberScope.ALL_NAME_FILTER))
assertSameElements(listOf(fqName31, fqName30), KotlinPackageIndexUtils.getSubpackages(fqName2, scope, MemberScope.ALL_NAME_FILTER)
.sortedBy(FqName::asString))
listOf(fqName31, fqName30, fqName31.child(Name.identifier("a")), fqName30.child(Name.identifier("a"))).forEach {
assertTrue(KotlinPackageIndexUtils.getSubpackages(it, scope, MemberScope.ALL_NAME_FILTER).isEmpty())
}
}
private fun setupSimpleTest() {
myFixture.configureByText("1.kt", "package foo.bar.zoo")
myFixture.configureByText("2.kt", "package foo.bar.moo")
}
}
|
apache-2.0
|
bde3593ec623f160a0224626f4bf6091
| 42.551724 | 138 | 0.710891 | 4.368512 | false | true | false | false |
kosiakk/Android-Books
|
app/src/main/java/com/kosenkov/androidbooks/books/GoogleBooksHttp.kt
|
1
|
2316
|
package com.kosenkov.androidbooks.books
import android.net.Uri
import android.util.Log
import org.json.JSONObject
import java.net.URL
import kotlin.text.Charsets.UTF_8
class GoogleBooksHttp : GoogleBooks {
private fun httpAPI() = Uri.Builder()
.scheme("https")
.authority("www.googleapis.com")
.appendEncodedPath("books/v1/volumes")
.appendQueryParameter("key", "AIzaSyAyiYb_NGVu6MIim1TmQDRG0VRrnO0C550")
/**
* Fixed number of volumes fetched per HTTP-request at once
*/
override val pageSize = 32
/**
* Performs blocking HTTP request to Google API and parses resulting JSON
*/
@Throws(Exception::class)
override fun search(query: String, startIndex: Int): GoogleBooks.Volumes {
Log.v("GoogleBooksHttp", "$query (start from $startIndex)")
require(startIndex >= 0)
// doc: https://developers.google.com/books/docs/v1/reference/volumes/list
val uri = httpAPI()
.appendQueryParameter("q", query)
.appendQueryParameter("maxResults", pageSize.toString())
.appendQueryParameter("orderBy", "relevance")
.appendQueryParameter("fields", "totalItems,items(id,kind,volumeInfo(title,subtitle,authors,imageLinks(thumbnail)))")
.appendQueryParameter("startIndex", startIndex.toString())
.build()
return uri.readJson().toVolumes()
}
override fun details(volumeId: String): GoogleBooks.VolumeDetails {
Log.v("GoogleBooksHttp", volumeId)
// doc: https://developers.google.com/books/docs/v1/reference/volumes/get
val uri = httpAPI()
.appendPath(volumeId)
.appendQueryParameter("projection", "lite")
.build()
val json = uri.readJson()
return GoogleBooks.VolumeDetails(json.toVolume(), json)
}
private fun Uri.readJson() = JSONObject(readString())
/*
The method will throw exception on failures, because retry after timeout might be too late for GUI.
How to handle 5xx errors? Quota Exceeded errors?
*/
private fun Uri.readString(): String =
URL(toString()).openStream().use {
it.bufferedReader(charset = UTF_8).readText()
}
}
|
gpl-3.0
|
424056ca86edf3f55686c39feaa1a27d
| 32.565217 | 133 | 0.635579 | 4.394687 | false | false | false | false |
smmribeiro/intellij-community
|
platform/remoteDev-util/src/com/intellij/remoteDev/downloader/ThinClientSessionInfoFetcher.kt
|
1
|
3120
|
package com.intellij.remoteDev.downloader
import com.fasterxml.jackson.databind.ObjectMapper
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.util.SystemInfo
import com.intellij.remoteDev.connection.CodeWithMeSessionInfoProvider
import com.intellij.remoteDev.connection.StunTurnServerInfo
import com.intellij.util.io.HttpRequests
import com.intellij.util.system.CpuArch
import com.intellij.util.withFragment
import org.jetbrains.annotations.ApiStatus
import java.net.HttpURLConnection
import java.net.URI
/**
* Lightweight implementation of LobbyServerAPI to avoid obfuscation issues
*/
@ApiStatus.Experimental
object ThinClientSessionInfoFetcher {
private val objectMapper = lazy { ObjectMapper() }
fun getSessionUrl(joinLinkUrl: URI): CodeWithMeSessionInfoProvider {
val url = createUrl(joinLinkUrl)
val requestString = objectMapper.value.createObjectNode().apply {
put("clientBuildNumber", currentBuildNumber())
put("clientPlatform", currentPlatform())
}.toPrettyString()
return HttpRequests.post(url, HttpRequests.JSON_CONTENT_TYPE)
.throwStatusCodeException(false)
.productNameAsUserAgent()
.connect { request ->
request.write(requestString)
val connection = request.connection as HttpURLConnection
val responseString = request.readString()
if (connection.responseCode >= 400) {
throw Exception("Request to $url failed with status code ${connection.responseCode}")
}
val sessionInfo = objectMapper.value.reader().readTree(responseString)
return@connect object : CodeWithMeSessionInfoProvider {
override val hostBuildNumber = sessionInfo["hostBuildNumber"].asText()
override val compatibleClientName = sessionInfo["compatibleClientName"].asText()
override val compatibleClientUrl = sessionInfo["compatibleClientUrl"].asText()
override val compatibleJreName = sessionInfo["compatibleJreName"].asText()
override val isUnattendedMode = false
override val compatibleJreUrl = sessionInfo["compatibleJreUrl"].asText()
override val hostFeaturesToEnable: Set<String>? = null
override val stunTurnServers: List<StunTurnServerInfo>? = null
override val turnAllocationServerInfo: StunTurnServerInfo? = null
override val downloadPgpPublicKeyUrl: String? = null
}
}
}
private fun createUrl(joinLinkUrl: URI): String {
val baseLink = joinLinkUrl.withFragment(null).toString().trimEnd('/')
return "$baseLink/info"
}
private fun currentBuildNumber(): String {
return ApplicationInfo.getInstance().build.toString()
}
private fun currentPlatform(): String {
return when {
SystemInfo.isMac && CpuArch.isArm64() -> "osx-aarch64"
SystemInfo.isMac && CpuArch.isIntel64() -> "osx-x64"
SystemInfo.isLinux && CpuArch.isIntel64() -> "linux-x64"
SystemInfo.isWindows && CpuArch.isIntel64() -> "windows-x64"
else -> error("Unsupported OS type: ${SystemInfo.OS_NAME}, CpuArch: ${CpuArch.CURRENT}")
}
}
}
|
apache-2.0
|
7fcbec3821a85b89b706463d03311d11
| 39.532468 | 95 | 0.73109 | 4.852255 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/tests/testData/structuralsearch/binaryExpression/binaryDivAssign.kt
|
8
|
285
|
class Foo {
operator fun divAssign(other: Foo) { print(other) }
}
fun foo() {
var z = 1
<warning descr="SSR">z /= 2</warning>
<warning descr="SSR">z = z / 2</warning>
print(z)
var x = Foo()
val y = Foo()
<warning descr="SSR">x.divAssign(y)</warning>
}
|
apache-2.0
|
d0b2d683f94aa453e98643aae5f52104
| 19.428571 | 55 | 0.557895 | 3.031915 | false | false | false | false |
smmribeiro/intellij-community
|
platform/vcs-log/graph/test/com/intellij/vcs/log/graph/TestGraphBuilder.kt
|
5
|
10017
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.log.graph
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.MultiMap
import com.intellij.vcs.log.graph.BaseTestGraphBuilder.SimpleEdge
import com.intellij.vcs.log.graph.BaseTestGraphBuilder.SimpleNode
import com.intellij.vcs.log.graph.api.EdgeFilter
import com.intellij.vcs.log.graph.api.LinearGraph
import com.intellij.vcs.log.graph.api.elements.GraphEdge
import com.intellij.vcs.log.graph.api.elements.GraphEdgeType
import com.intellij.vcs.log.graph.api.elements.GraphNode
import com.intellij.vcs.log.graph.api.elements.GraphNodeType
import com.intellij.vcs.log.graph.api.permanent.PermanentCommitsInfo
import com.intellij.vcs.log.graph.api.permanent.PermanentGraphInfo
import com.intellij.vcs.log.graph.impl.facade.LinearGraphController
import com.intellij.vcs.log.graph.impl.facade.VisibleGraphImpl
import com.intellij.vcs.log.graph.impl.permanent.GraphLayoutBuilder
import com.intellij.vcs.log.graph.utils.LinearGraphUtils
import com.intellij.vcs.log.graph.utils.TimestampGetter
import java.util.*
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
interface BaseTestGraphBuilder {
val Int.U: SimpleNode get() = SimpleNode(this, GraphNodeType.USUAL)
val Int.UNM: SimpleNode get() = SimpleNode(this, GraphNodeType.UNMATCHED)
val Int.NOT_LOAD: SimpleNode get() = SimpleNode(this, GraphNodeType.NOT_LOAD_COMMIT)
val Int.u: SimpleEdge get() = SimpleEdge(this, GraphEdgeType.USUAL)
val Int.dot: SimpleEdge get() = SimpleEdge(this, GraphEdgeType.DOTTED)
val Int?.up_dot: SimpleEdge get() = SimpleEdge(this, GraphEdgeType.DOTTED_ARROW_UP)
val Int?.down_dot: SimpleEdge get() = SimpleEdge(this, GraphEdgeType.DOTTED_ARROW_DOWN)
val Int?.not_load: SimpleEdge get() = SimpleEdge(this, GraphEdgeType.NOT_LOAD_COMMIT)
class SimpleEdge(val toNode: Int?, val type: GraphEdgeType = GraphEdgeType.USUAL)
class SimpleNode(val nodeId: Int, val type: GraphNodeType = GraphNodeType.USUAL)
}
class TestGraphBuilder : BaseTestGraphBuilder {
private val nodes = ArrayList<NodeWithEdges>()
fun done(): LinearGraph = TestLinearGraph(nodes)
operator fun Int.invoke() = newNode(asSimpleNode())
operator fun Int.invoke(vararg edge: Int) = newNode(asSimpleNode(), edge.asSimpleEdges())
operator fun Int.invoke(vararg edge: SimpleEdge) = newNode(asSimpleNode(), edge.toList())
operator fun SimpleNode.invoke() = newNode(this)
operator fun SimpleNode.invoke(vararg edge: Int) = newNode(this, edge.asSimpleEdges())
operator fun SimpleNode.invoke(vararg edge: SimpleEdge) = newNode(this, edge.toList())
private class NodeWithEdges(val nodeId: Int, val edges: List<SimpleEdge>, val type: GraphNodeType = GraphNodeType.USUAL)
private fun IntArray.asSimpleEdges() = map { SimpleEdge(it) }
private fun Int.asSimpleNode() = SimpleNode(this)
private fun newNode(node: SimpleNode, edges: List<SimpleEdge> = listOf()) {
nodes.add(NodeWithEdges(node.nodeId, edges, node.type))
}
fun node(id: Int, vararg edge: Int) {
nodes.add(NodeWithEdges(id, edge.map {
SimpleEdge(it, GraphEdgeType.USUAL)
}))
}
fun node(id: Int, vararg edge: SimpleEdge) {
nodes.add(NodeWithEdges(id, edge.toList()))
}
private class TestLinearGraph(buildNodes: List<NodeWithEdges>) : LinearGraph {
private val nodes: List<GraphNode>
private val nodeIndexToId: Map<Int, Int>
private val nodeIdToIndex: Map<Int, Int>
private val edges = MultiMap<Int, GraphEdge>()
val SimpleEdge.toIndex: Int? get() = toNode?.let { nodeIdToIndex[it] }
init {
val idsMap = HashMap<Int, Int>()
nodes = buildNodes.map2 { index, it ->
idsMap[index] = it.nodeId
GraphNode(index, it.type)
}
nodeIndexToId = idsMap
nodeIdToIndex = ContainerUtil.reverseMap(idsMap)
// create edges
for (node in buildNodes) {
val nodeIndex = nodeIdToIndex[node.nodeId]!!
for (simpleEdge in node.edges) {
val edgeType = simpleEdge.type
if (edgeType.isNormalEdge) {
val anotherNodeIndex = simpleEdge.toIndex ?: error(
"Graph is incorrect. Node ${node.nodeId} has ${edgeType} edge to not existed node: ${simpleEdge.toNode}")
val graphEdge = GraphEdge.createNormalEdge(anotherNodeIndex!!, nodeIndex, edgeType)
edges.putValue(nodeIndex, graphEdge)
edges.putValue(anotherNodeIndex, graphEdge)
}
else {
edges.putValue(nodeIndex, GraphEdge.createEdgeWithTargetId(nodeIndex, simpleEdge.toNode, edgeType))
}
}
}
}
override fun nodesCount() = nodes.size
override fun getNodeId(nodeIndex: Int): Int = nodeIndexToId[nodeIndex]!!
override fun getAdjacentEdges(nodeIndex: Int, filter: EdgeFilter): List<GraphEdge> {
return edges[nodeIndex].filter {
if (it.type.isNormalEdge) {
(LinearGraphUtils.isEdgeUp(it, nodeIndex) && filter.upNormal)
|| (LinearGraphUtils.isEdgeDown(it, nodeIndex) && filter.downNormal)
}
else {
filter.special
}
}
}
override fun getGraphNode(nodeIndex: Int) = nodes[nodeIndex]
override fun getNodeIndex(nodeId: Int) = nodeIdToIndex[nodeId]
}
}
private fun LinearGraph.assertEdge(nodeIndex: Int, edge: GraphEdge) {
if (edge.type.isNormalEdge) {
if (nodeIndex == edge.upNodeIndex) {
assertTrue(getAdjacentEdges(edge.downNodeIndex!!, EdgeFilter.NORMAL_UP).contains(edge))
}
else {
assertTrue(nodeIndex == edge.downNodeIndex)
assertTrue(getAdjacentEdges(edge.upNodeIndex!!, EdgeFilter.NORMAL_DOWN).contains(edge))
}
}
else {
when (edge.type) {
GraphEdgeType.NOT_LOAD_COMMIT, GraphEdgeType.DOTTED_ARROW_DOWN -> {
assertTrue(nodeIndex == edge.upNodeIndex)
assertNull(edge.downNodeIndex)
}
GraphEdgeType.DOTTED_ARROW_UP -> {
assertTrue(nodeIndex == edge.downNodeIndex)
assertNull(edge.upNodeIndex)
}
}
}
}
fun LinearGraph.asTestGraphString(sorted: Boolean = false): String = StringBuilder().apply {
for (nodeIndex in 0 until nodesCount()) {
val node = getGraphNode(nodeIndex)
append(getNodeId(nodeIndex))
assertEquals(nodeIndex, node.nodeIndex,
"nodeIndex: $nodeIndex, but for node with this index(nodeId: ${getNodeId(nodeIndex)}) nodeIndex: ${node.nodeIndex}"
)
when (node.type) {
GraphNodeType.UNMATCHED -> append(".UNM")
GraphNodeType.NOT_LOAD_COMMIT -> append(".NOT_LOAD")
}
// edges
var adjacentEdges = getAdjacentEdges(nodeIndex, EdgeFilter.ALL)
if (sorted) {
adjacentEdges = adjacentEdges.sortedWith(GraphStrUtils.GRAPH_ELEMENT_COMPARATOR)
}
append("(")
adjacentEdges.mapNotNull {
assertEdge(nodeIndex, it)
if (it.upNodeIndex == nodeIndex) {
val startId = when {
it.type.isNormalEdge -> getNodeId(it.downNodeIndex!!).toString()
it.targetId != null -> it.targetId.toString()
else -> "null"
}
when (it.type) {
GraphEdgeType.USUAL -> startId
GraphEdgeType.DOTTED -> "$startId.dot"
GraphEdgeType.DOTTED_ARROW_UP -> "$startId.up_dot"
GraphEdgeType.DOTTED_ARROW_DOWN -> "$startId.down_dot"
GraphEdgeType.NOT_LOAD_COMMIT -> "$startId.not_load"
}
}
else {
null
}
}.joinTo(this, separator = ", ") { it }
append(")")
append("\n")
}
}.toString()
fun graph(f: TestGraphBuilder.() -> Unit): LinearGraph {
val builder = TestGraphBuilder()
builder.f()
return builder.done()
}
private fun <T, R> Iterable<T>.map2(transform: (Int, T) -> R): List<R> {
return mapIndexedTo(ArrayList()) { index, element -> transform(index, element) }
}
class TestPermanentGraphInfo(
val graph: LinearGraph,
private vararg val headsOrder: Int = IntArray(0),
private val branchNodes: Set<Int> = setOf()
) : PermanentGraphInfo<Int> {
val commitInfo = object : PermanentCommitsInfo<Int> {
override fun getCommitId(nodeId: Int) = nodeId
override fun getTimestamp(nodeId: Int) = nodeId.toLong()
override fun getNodeId(commitId: Int) = commitId
override fun convertToNodeIds(heads: Collection<Int>) = heads.toSet()
}
val timestampGetter = object : TimestampGetter {
override fun size() = graph.nodesCount()
override fun getTimestamp(index: Int) = commitInfo.getTimestamp(graph.getNodeId(index))
}
val graphLayout = GraphLayoutBuilder.build(graph) { x, y ->
if (headsOrder.isEmpty()) {
graph.getNodeId(x) - graph.getNodeId(y)
}
else {
val t = if (headsOrder.indexOf(x) == -1) x else if (headsOrder.indexOf(y) == -1) y else -1
if (t != -1) throw IllegalStateException("Not found headsOrder for $t node by id")
headsOrder.indexOf(x) - headsOrder.indexOf(y)
}
}
override fun getPermanentCommitsInfo() = commitInfo
override fun getLinearGraph() = graph
override fun getPermanentGraphLayout() = graphLayout
override fun getBranchNodeIds() = branchNodes
}
class TestColorManager : GraphColorManager<Int> {
override fun getColorOfBranch(headCommit: Int): Int = headCommit
override fun getColorOfFragment(headCommit: Int?, magicIndex: Int): Int = magicIndex
override fun compareHeads(head1: Int, head2: Int): Int = head1.compareTo(head2)
}
class TestLinearController(val graph: LinearGraph) : LinearGraphController {
override fun getCompiledGraph() = graph
override fun performLinearGraphAction(action: LinearGraphController.LinearGraphAction) = throw UnsupportedOperationException()
}
fun LinearGraph.asVisibleGraph(): VisibleGraph<Int> = VisibleGraphImpl(TestLinearController(this), TestPermanentGraphInfo(this),
TestColorManager())
|
apache-2.0
|
44ca0fa7ffe847c0893bae3e866d7004
| 36.943182 | 140 | 0.699511 | 3.905263 | false | true | false | false |
Jire/Charlatano
|
src/main/kotlin/com/charlatano/utils/Every.kt
|
1
|
1582
|
/*
* Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO
* Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.charlatano.utils
import java.util.concurrent.ThreadLocalRandom
import kotlin.concurrent.thread
@Volatile
var inBackground = false
@Volatile
var notInGame = false
inline fun every(duration: Int, continuous: Boolean = false,
crossinline body: () -> Unit) = every(duration, duration, continuous, body)
inline fun every(minDuration: Int, maxDuration: Int,
continuous: Boolean = false,
crossinline body: () -> Unit) = thread {
while (!Thread.interrupted()) {
if (continuous || !(inBackground && notInGame)) body()
Thread.sleep((if (maxDuration > minDuration)
ThreadLocalRandom.current().nextInt(maxDuration - minDuration + 1) + minDuration
else minDuration).toLong())
}
}
|
agpl-3.0
|
77b5b8110926428f5e38cc7546803695
| 37.609756 | 92 | 0.702276 | 4.346154 | false | false | false | false |
WYKCode/WYK-Android
|
app/src/main/java/college/wyk/app/ui/LandingActivity.kt
|
1
|
6882
|
package college.wyk.app.ui
import android.app.FragmentTransaction
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.PersistableBundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import college.wyk.app.BuildConfig
import college.wyk.app.R
import college.wyk.app.commons.BetterMaterialViewPager
import college.wyk.app.commons.alterColor
import college.wyk.app.commons.newThemedDialog
import college.wyk.app.ui.feed.FeedFragment
import college.wyk.app.ui.feed.indices
import college.wyk.app.ui.publications.PublicationFragment
import college.wyk.app.ui.settings.SettingsActivity
import college.wyk.app.ui.timetable.TimetableActivity
import com.jaeger.library.StatusBarUtil
import com.mikepenz.community_material_typeface_library.CommunityMaterial
import com.mikepenz.google_material_typeface_library.GoogleMaterial
import com.mikepenz.materialdrawer.AccountHeaderBuilder
import com.mikepenz.materialdrawer.Drawer
import com.mikepenz.materialdrawer.DrawerBuilder
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem
import com.mikepenz.materialdrawer.model.ProfileDrawerItem
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.dialog_about.view.*
import org.joor.Reflect
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper
class LandingActivity : AppCompatActivity() {
lateinit var drawer: Drawer
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// set up account
val headerResult = AccountHeaderBuilder().withActivity(this).addProfiles(
ProfileDrawerItem()
.withName("WYK Student")
.withEmail("[email protected]")
//.withIcon(resources.getDrawable(R.drawable.avatar))
).withSelectionListEnabled(false).build()
// set up drawer
drawer = DrawerBuilder()
.withActivity(this)
//.withAccountHeader(headerResult)
.withActionBarDrawerToggleAnimated(true)
.addDrawerItems(
PrimaryDrawerItem().withIdentifier(400L).withName("Timetable").withIcon(CommunityMaterial.Icon.cmd_timetable).withSelectable(false)
)
.addStickyDrawerItems(
PrimaryDrawerItem().withIdentifier(500L).withName("Visit website").withIcon(GoogleMaterial.Icon.gmd_open_in_new).withSelectable(false),
PrimaryDrawerItem().withIdentifier(501L).withName("Settings").withIcon(GoogleMaterial.Icon.gmd_settings).withSelectable(false),
PrimaryDrawerItem().withIdentifier(502L).withName("About").withIcon(GoogleMaterial.Icon.gmd_help).withSelectable(false)
)
.withOnDrawerItemClickListener {
view, position, drawerItem ->
drawer.closeDrawer()
when (drawerItem.identifier) {
400L -> {
startActivity(Intent(this, TimetableActivity::class.java))
}
500L -> {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("http://wyk.edu.hk")))
}
501L -> {
startActivity(Intent(this, SettingsActivity::class.java))
}
502L -> {
val dialog = newThemedDialog(this)
.customView(R.layout.dialog_about, false)
.neutralText("View on Github")
.positiveText("Close")
.onPositive { dialog, action -> dialog.dismiss() }
.onNeutral { dialog, action -> startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/WYKCode/WYK-Android"))) }
.show()
val dialogView = dialog.view
dialogView.about_badge.setImageResource(R.drawable.badge)
dialogView.about_version.text = BuildConfig.VERSION_NAME
}
}
true
}
.build()
drawer.deselect()
// set up bottom bar
bottom_bar.setOnTabSelectListener {
supportFragmentManager.beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.replace(main_container.id,
when (it) {
R.id.tab_feed -> FeedFragment()
R.id.tab_publications -> PublicationFragment()
// R.id.tab_welfare -> WelfareFragment()
else -> FeedFragment()
}
)
.commit()
when (it) {
R.id.tab_feed -> StatusBarUtil.setColorForDrawerLayout(this, drawer.drawerLayout, resources.getColor(R.color.container_background), (255 * 0.1).toInt())
R.id.tab_publications -> StatusBarUtil.setColorForDrawerLayout(this, drawer.drawerLayout, resources.getColor(R.color.md_black_1000), (255 * 0.1).toInt())
// R.id.tab_welfare -> StatusBarUtil.setColorForDrawerLayout(this, drawer.drawerLayout, resources.getColor(R.color.welfare), (255 * 0.1).toInt())
}
}
bottom_bar.setOnTabReselectListener {
if (it == R.id.tab_feed) {
(root_view.findViewById(R.id.view_pager) as BetterMaterialViewPager).viewPager.setCurrentItem(indices["School"]!!, true)
}
}
for (i in 1..bottom_bar.tabCount) {
bottom_bar.getTabAtPosition(i - 1).apply {
Reflect.on(this)["barColorWhenSelected"] = alterColor(Reflect.on(this)["barColorWhenSelected"], 0.93f)
}
}
}
override fun onSaveInstanceState(outState: Bundle?, outPersistentState: PersistableBundle?) {
super.onSaveInstanceState(outState, outPersistentState)
bottom_bar.onSaveInstanceState()
}
override fun attachBaseContext(newBase: Context?) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)) // add Calligraphy support
}
fun updateToolbar(toolbar: Toolbar) {
drawer.setToolbar(this, toolbar, true)
supportActionBar?.setDisplayShowHomeEnabled(false)
supportActionBar?.setDisplayShowTitleEnabled(true)
drawer.actionBarDrawerToggle.isDrawerIndicatorEnabled = true
}
}
|
mit
|
441fb63286d43917469fe2c4346d5dd2
| 47.132867 | 169 | 0.610869 | 5.112927 | false | false | false | false |
aosp-mirror/platform_frameworks_support
|
navigation/safe-args-generator/src/tests/kotlin/androidx/navigation/safe/args/generator/NavParserTest.kt
|
1
|
5404
|
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.navigation.safe.args.generator
import androidx.navigation.safe.args.generator.NavType.BOOLEAN
import androidx.navigation.safe.args.generator.NavType.FLOAT
import androidx.navigation.safe.args.generator.NavType.INT
import androidx.navigation.safe.args.generator.NavType.REFERENCE
import androidx.navigation.safe.args.generator.NavType.STRING
import androidx.navigation.safe.args.generator.models.Action
import androidx.navigation.safe.args.generator.models.Argument
import androidx.navigation.safe.args.generator.models.Destination
import androidx.navigation.safe.args.generator.models.ResReference
import com.squareup.javapoet.ClassName
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.CoreMatchers.nullValue
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class NavParserTest {
@Test
fun test() {
val id: (String) -> ResReference = { id -> ResReference("a.b", "id", id) }
val navGraph = NavParser.parseNavigationFile(testData("naive_test.xml"),
"a.b", "foo.app", Context())
val nameFirst = ClassName.get("androidx.navigation.testapp", "MainFragment")
val nameNext = ClassName.get("foo.app", "NextFragment")
val expectedFirst = Destination(id("first_screen"), nameFirst, "fragment",
listOf(Argument("myarg1", STRING, StringValue("one"))),
listOf(Action(id("next"), id("next_fragment"), listOf(
Argument("myarg2", STRING),
Argument("randomArgument", STRING),
Argument("intArgument", INT, IntValue("261"))
))))
val expectedNext = Destination(id("next_fragment"), nameNext, "fragment",
listOf(Argument("myarg2", STRING)),
listOf(Action(id("next"), id("first_screen")),
Action(id("finish"), null)))
val expectedGraph = Destination(null, null, "navigation", emptyList(), emptyList(),
listOf(expectedFirst, expectedNext))
assertThat(navGraph, `is`(expectedGraph))
}
@Test
fun testReferenceParsing() {
assertThat(parseReference("@+id/next", "a.b"), `is`(ResReference("a.b", "id", "next")))
assertThat(parseReference("@id/next", "a.b"), `is`(ResReference("a.b", "id", "next")))
assertThat(parseReference("@android:string/text", "a.b"),
`is`(ResReference("android", "string", "text")))
assertThat(parseReference("@android:id/text", "a.b"),
`is`(ResReference("android", "id", "text")))
assertThat(parseReference("@not.android:string/text", "a.b"),
`is`(ResReference("not.android", "string", "text")))
}
@Test
fun testIntValueParsing() {
assertThat(parseIntValue("foo"), nullValue())
assertThat(parseIntValue("10"), `is`(IntValue("10")))
assertThat(parseIntValue("-10"), `is`(IntValue("-10")))
assertThat(parseIntValue("0xA"), `is`(IntValue("0xA")))
assertThat(parseIntValue("0xFFFFFFFF"), `is`(IntValue("0xFFFFFFFF")))
assertThat(parseIntValue("0x1FFFFFFFF"), nullValue())
}
@Test
fun testArgInference() {
val infer = { value: String -> inferArgument("foo", value, "a.b") }
val intArg = { value: String -> Argument("foo", INT, IntValue(value)) }
val floatArg = { value: String -> Argument("foo", FLOAT, FloatValue(value)) }
val stringArg = { value: String -> Argument("foo", STRING, StringValue(value)) }
val boolArg = { value: String -> Argument("foo", BOOLEAN, BooleanValue(value)) }
val referenceArg = { pName: String, type: String, value: String ->
Argument("foo", REFERENCE, ReferenceValue(ResReference(pName, type, value)))
}
assertThat(infer("spb"), `is`(stringArg("spb")))
assertThat(infer("10"), `is`(intArg("10")))
assertThat(infer("0x10"), `is`(intArg("0x10")))
assertThat(infer("@android:id/some_la"), `is`(referenceArg("android", "id", "some_la")))
assertThat(infer("@foo"), `is`(stringArg("@foo")))
assertThat(infer("@+id/foo"), `is`(referenceArg("a.b", "id", "foo")))
assertThat(infer("@foo:stuff"), `is`(stringArg("@foo:stuff")))
assertThat(infer("@/stuff"), `is`(stringArg("@/stuff")))
assertThat(infer("10101010100100"), `is`(floatArg("10101010100100")))
assertThat(infer("1."), `is`(floatArg("1.")))
assertThat(infer("1.2e-4"), `is`(floatArg("1.2e-4")))
assertThat(infer(".4"), `is`(floatArg(".4")))
assertThat(infer("true"), `is`(boolArg("true")))
assertThat(infer("false"), `is`(boolArg("false")))
}
}
|
apache-2.0
|
a7daa55f5db0199561e3673c703cec0c
| 46.831858 | 96 | 0.640822 | 4.023827 | false | true | false | false |
Bambooin/trime
|
app/src/main/java/com/osfans/trime/setup/SetupActivity.kt
|
1
|
5056
|
package com.osfans.trime.setup
import android.app.PendingIntent
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.appcompat.app.AlertDialog
import androidx.core.app.NotificationCompat
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.blankj.utilcode.util.NotificationUtils
import com.osfans.trime.R
import com.osfans.trime.databinding.ActivitySetupBinding
import com.osfans.trime.setup.SetupPage.Companion.firstUndonePage
import com.osfans.trime.setup.SetupPage.Companion.isLastPage
class SetupActivity : FragmentActivity() {
private lateinit var viewPager: ViewPager2
private val viewModel: SetupViewModel by viewModels()
companion object {
private var binaryCount = false
private const val NOTIFY_ID = 87463
fun shouldSetup() = !binaryCount && SetupPage.hasUndonePage()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivitySetupBinding.inflate(layoutInflater)
setContentView(binding.root)
val prevButton = binding.prevButton.apply {
text = getString(R.string.setup__prev)
setOnClickListener { viewPager.currentItem = viewPager.currentItem - 1 }
}
binding.skipButton.apply {
text = getString(R.string.setup__skip)
setOnClickListener {
AlertDialog.Builder(this@SetupActivity)
.setMessage(R.string.setup__skip_hint)
.setPositiveButton(R.string.setup__skip_hint_yes) { _, _ ->
finish()
}
.setNegativeButton(R.string.setup__skip_hint_no, null)
.show()
}
}
val nextButton = binding.nextButton.apply {
setOnClickListener {
if (viewPager.currentItem != SetupPage.values().size - 1) {
viewPager.currentItem = viewPager.currentItem + 1
} else finish()
}
}
viewPager = binding.viewpager
viewPager.adapter = Adapter()
viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
// Manually call following observer when page changed
// intentionally before changing the text of nextButton
viewModel.isAllDone.value = viewModel.isAllDone.value
// Hide prev button for the first page
prevButton.visibility = if (position != 0) View.VISIBLE else View.GONE
nextButton.text =
getString(
if (position.isLastPage())
R.string.setup__done else R.string.setup__next
)
}
})
viewModel.isAllDone.observe(this) { allDone ->
nextButton.apply {
// Hide next button for the last page when allDone == false
(allDone || !viewPager.currentItem.isLastPage()).let {
visibility = if (it) View.VISIBLE else View.GONE
}
}
}
// Skip to undone page
firstUndonePage()?.let { viewPager.currentItem = it.ordinal }
binaryCount = true
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
val fragment = supportFragmentManager.findFragmentByTag("f${viewPager.currentItem}")
(fragment as SetupFragment).sync()
}
override fun onPause() {
if (SetupPage.hasUndonePage()) {
NotificationUtils.notify(NOTIFY_ID) { param ->
param.setSmallIcon(R.drawable.ic_trime_status)
.setContentTitle(getText(R.string.trime_app_name))
.setContentText(getText(R.string.setup__notify_hint))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(
PendingIntent.getActivity(
this,
0,
Intent(this, javaClass),
PendingIntent.FLAG_IMMUTABLE
)
)
.setAutoCancel(true)
}
}
super.onPause()
}
override fun onResume() {
NotificationUtils.cancel(NOTIFY_ID)
super.onResume()
}
private inner class Adapter : FragmentStateAdapter(this) {
override fun getItemCount(): Int = SetupPage.values().size
override fun createFragment(position: Int): Fragment =
SetupFragment().apply {
arguments = bundleOf("page" to SetupPage.values()[position])
}
}
}
|
gpl-3.0
|
d3ddda08f2cf5640801d2bc187694242
| 38.5 | 92 | 0.600475 | 5.244813 | false | false | false | false |
mgoodwin14/barcrawler
|
app/src/main/java/com/nonvoid/barcrawler/brewery/BreweryDetailsPresenter.kt
|
2
|
3363
|
package com.nonvoid.barcrawler.brewery
import com.google.firebase.auth.FirebaseAuth
import com.nonvoid.barcrawler.model.Brewery
import com.nonvoid.barcrawler.social.FireBaseSocialClient
import com.nonvoid.barcrawler.social.SocialRepoAPI
import com.nonvoid.barcrawler.database.BreweryDataBaseAPI
import com.nonvoid.barcrawler.database.BreweryDataBaseClient
import com.nonvoid.barcrawler.model.Beer
class BreweryDetailsPresenter(
private val detailsView: BreweryDetailsView,
private val listView: BeerListView,
private val brewery: Brewery,
private val dbClient: BreweryDataBaseAPI,
private val socialClient: SocialRepoAPI = FireBaseSocialClient(FirebaseAuth.getInstance().currentUser!!)
){
fun onCreate(){
detailsView.displayBrewery(brewery)
getBeerList()
socialClient.getNumberOfFavoritesForBrewery(brewery)
.subscribe({result -> detailsView.displayFavoriteCount(result)})
}
fun getBrewery(): Brewery{
return brewery
}
fun setFavoriteMenuItem(){
socialClient.isBreweryFavorited(brewery)
.subscribe({result -> detailsView.displayAsFavorite(result)})
}
fun toggleFavorite(){
socialClient.isBreweryFavorited(brewery)
.subscribe({result-> setBreweryAsFavorite(!result)})
}
fun getBeerList(){
dbClient.getBeersForBrewery(brewery.id)
.subscribe{list -> listView.displayBeerList(list)}
}
fun submitComment(message: String){
socialClient.submitComment(brewery, message)
}
private fun setBreweryAsFavorite(favorite: Boolean){
if(favorite){
socialClient.favoriteBrewery(brewery)
}else {
socialClient.unfavoriteBrewery(brewery)
}
detailsView.displayAsFavorite(favorite)
socialClient.getNumberOfFavoritesForBrewery(brewery)
.subscribe({result -> detailsView.displayFavoriteCount(result)})
}
interface BreweryDetailsView{
fun displayBrewery(brewery :Brewery)
fun displayAsFavorite(favorite :Boolean)
fun displayFavoriteCount(count :Int)
}
interface BeerListView{
fun displayBeerList(list: MutableList<Beer>)
}
class Builder{
private lateinit var detailsView: BreweryDetailsView
private lateinit var listView: BeerListView
private lateinit var brewery: Brewery
private lateinit var dbClient: BreweryDataBaseAPI
private lateinit var socialClient: SocialRepoAPI
fun detailsView(view: BreweryDetailsView) :Builder{
this.detailsView = view
return this
}
fun listView(view: BeerListView) :Builder{
this.listView = view
return this
}
fun brewery(brewery: Brewery) :Builder{
this.brewery = brewery
return this
}
fun dbClient(dbClient: BreweryDataBaseAPI) :Builder{
this.dbClient = dbClient
return this
}
fun sociallClient(socialClient: SocialRepoAPI) :Builder{
this.socialClient = socialClient
return this
}
fun build(): BreweryDetailsPresenter{
return BreweryDetailsPresenter(detailsView, listView, brewery, dbClient, socialClient)
}
}
}
|
gpl-3.0
|
beaa476cf5b9a4585df6f1d1a504ca62
| 30.735849 | 112 | 0.673506 | 4.520161 | false | false | false | false |
Esri/arcgis-runtime-samples-android
|
kotlin/offline-routing/src/main/java/com/esri/arcgisruntime/sample/offlinerouting/MainActivity.kt
|
1
|
12378
|
/*
* Copyright 2020 Esri
*
* 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.esri.arcgisruntime.sample.offlinerouting
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.widget.Button
import android.widget.RadioGroup
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.esri.arcgisruntime.data.TileCache
import com.esri.arcgisruntime.geometry.Envelope
import com.esri.arcgisruntime.geometry.Point
import com.esri.arcgisruntime.geometry.SpatialReferences
import com.esri.arcgisruntime.layers.ArcGISTiledLayer
import com.esri.arcgisruntime.loadable.LoadStatus
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.Basemap
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener
import com.esri.arcgisruntime.mapping.view.Graphic
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.symbology.CompositeSymbol
import com.esri.arcgisruntime.symbology.PictureMarkerSymbol
import com.esri.arcgisruntime.symbology.SimpleLineSymbol
import com.esri.arcgisruntime.symbology.TextSymbol
import com.esri.arcgisruntime.tasks.networkanalysis.RouteParameters
import com.esri.arcgisruntime.tasks.networkanalysis.RouteTask
import com.esri.arcgisruntime.sample.offlinerouting.databinding.ActivityMainBinding
import com.esri.arcgisruntime.tasks.networkanalysis.Stop
import kotlin.math.roundToInt
class MainActivity : AppCompatActivity() {
private val stopsOverlay: GraphicsOverlay by lazy { GraphicsOverlay() }
private val routeOverlay: GraphicsOverlay by lazy { GraphicsOverlay() }
private var routeParameters: RouteParameters? = null
private val routeTask: RouteTask by lazy {
RouteTask(
this,
getExternalFilesDir(null)?.path + getString(R.string.geodatabase_path),
"Streets_ND"
)
}
private val TAG: String = MainActivity::class.java.simpleName
private val activityMainBinding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
private val mapView: MapView by lazy {
activityMainBinding.mapView
}
private val clearButton: Button by lazy {
activityMainBinding.clearButton
}
private val modeSwitch: RadioGroup by lazy {
activityMainBinding.modeSwitch
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(activityMainBinding.root)
// create a tile cache from the tpkx
val tileCache = TileCache(getExternalFilesDir(null)?.path + getString(R.string.tpkx_path))
val tiledLayer = ArcGISTiledLayer(tileCache)
// make a basemap with the tiled layer and add it to the mapview as an ArcGISMap
mapView.map = ArcGISMap(Basemap(tiledLayer))
// add the graphics overlays to the map view
mapView.graphicsOverlays.addAll(listOf(stopsOverlay, routeOverlay))
// load the route task
routeTask.loadAsync()
routeTask.addDoneLoadingListener {
if (routeTask.loadStatus == LoadStatus.LOADED) {
try {
// create route parameters
routeParameters = routeTask.createDefaultParametersAsync().get()
} catch (e: Exception) {
val error = "Error getting default route parameters. ${e.message}"
Log.e(TAG, error)
Toast.makeText(this, error, Toast.LENGTH_LONG).show()
}
} else {
val error = "Error loading route task: ${routeTask.loadError.message}"
Log.e(TAG, error)
Toast.makeText(this, error, Toast.LENGTH_LONG).show()
}
}
// set up travel mode switch
modeSwitch.setOnCheckedChangeListener { _, isChecked ->
routeParameters?.travelMode = when (isChecked) {
R.id.fastest_button -> routeTask.routeTaskInfo.travelModes[0]
R.id.shortest_button -> routeTask.routeTaskInfo.travelModes[1]
else -> routeTask.routeTaskInfo.travelModes[0]
}
Toast.makeText(
this,
"${routeParameters?.travelMode?.name} route selected.",
Toast.LENGTH_SHORT
).show()
updateRoute()
}
// make a clear button to reset the stops and routes
clearButton.setOnClickListener {
stopsOverlay.graphics.clear()
routeOverlay.graphics.clear()
}
// move the clear button above the attribution bar
mapView.addAttributionViewLayoutChangeListener { v, _, _, _, _, _, oldTop, _, oldBottom ->
val heightChanged = v.height - (oldBottom - oldTop)
clearButton.y += -heightChanged
}
// add a graphics overlay to show the boundary
GraphicsOverlay().let {
val envelope = Envelope(
Point(-13045352.223196, 3864910.900750, 0.0, SpatialReferences.getWebMercator()),
Point(-13024588.857198, 3838880.505604, 0.0, SpatialReferences.getWebMercator())
)
val boundarySymbol =
SimpleLineSymbol(SimpleLineSymbol.Style.DASH, 0xFF00FF00.toInt(), 5f)
it.graphics.add(Graphic(envelope, boundarySymbol))
mapView.graphicsOverlays.add(it)
}
// set up the touch listeners on the map view
createMapGestures()
}
/**
* Sets up the onTouchListener for the mapView.
* For single taps, graphics will be selected.
* For double touch drags, graphics will be moved.
* */
private fun createMapGestures() {
mapView.onTouchListener = object : DefaultMapViewOnTouchListener(this, mapView) {
override fun onSingleTapConfirmed(motionEvent: MotionEvent): Boolean {
val screenPoint = android.graphics.Point(
motionEvent.x.roundToInt(),
motionEvent.y.roundToInt()
)
addOrSelectGraphic(screenPoint)
return true
}
override fun onDoubleTouchDrag(motionEvent: MotionEvent): Boolean {
val screenPoint = android.graphics.Point(
motionEvent.x.roundToInt(),
motionEvent.y.roundToInt()
)
// move the selected graphic to the new location
if (stopsOverlay.selectedGraphics.isNotEmpty()) {
stopsOverlay.selectedGraphics[0]?.geometry =
mapView.screenToLocation(screenPoint)
updateRoute()
}
// ignore default double touch drag gesture
return true
}
// ignore default double tap gesture
override fun onDoubleTap(e: MotionEvent?): Boolean {
return true
}
}
}
/**
* Updates the calculated route by calling routeTask.solveRouteAsync().
* Creates a graphic to display the route.
* */
private fun updateRoute() {
// get a list of stops from the graphics currently on the graphics overlay.
val stops = stopsOverlay.graphics.map {
Stop(it.geometry as Point)
}
// do not calculate a route if there is only one stop
if (stops.size <= 1) return
routeParameters?.setStops(stops)
// solve the route
val results = routeTask.solveRouteAsync(routeParameters)
results.addDoneListener {
try {
val result = results.get()
val route = result.routes[0]
// create graphic for route
val graphic = Graphic(
route.routeGeometry, SimpleLineSymbol(
SimpleLineSymbol.Style.SOLID,
0xFF0000FF.toInt(), 3F
)
)
routeOverlay.graphics.clear()
routeOverlay.graphics.add(graphic)
} catch (e: Exception) {
val error = "No route solution. ${e.message}"
Log.e(TAG, error)
Toast.makeText(this, error, Toast.LENGTH_LONG).show()
routeOverlay.graphics.clear()
}
}
}
/**
* Selects a graphic if there is one at the provided tapped location or, if there is none, creates a new graphic.
*
* @param screenPoint a point in screen space where the user tapped
* */
private fun addOrSelectGraphic(screenPoint: android.graphics.Point) {
// identify the selected graphic
val results = mapView.identifyGraphicsOverlayAsync(stopsOverlay, screenPoint, 10.0, false)
results.addDoneListener {
try {
val graphics = results.get().graphics
// unselect everything
if (stopsOverlay.selectedGraphics.isNotEmpty()) {
stopsOverlay.unselectGraphics(stopsOverlay.selectedGraphics)
}
// if the user tapped on something, select it
if (graphics.isNotEmpty()) {
val firstGraphic = graphics[0]
firstGraphic.isSelected = true
} else { // there is no graphic at this location
// make a new graphic at the tapped location
val locationPoint = mapView.screenToLocation(screenPoint)
createStopSymbol(stopsOverlay.graphics.size + 1, locationPoint)
}
} catch (e: Exception) {
val error = "Error identifying graphic: ${e.stackTrace}"
Log.e(TAG, error)
Toast.makeText(this, error, Toast.LENGTH_LONG).show()
}
}
}
/**
* Creates a composite symbol to represent a numbered stop.
*
* @param stopNumber the ordinal number of this stop
* @param locationPoint the point in map space where the symbol should be placed
*/
private fun createStopSymbol(stopNumber: Int, locationPoint: Point) {
try {
// create a new picture marker symbol and load it
val pictureMarkerSymbol = PictureMarkerSymbol.createAsync(
ContextCompat.getDrawable(
this,
R.drawable.pin_symbol
) as BitmapDrawable
).get()
// create a text symbol with the stop number
val textSymbol = TextSymbol(
12f,
stopNumber.toString(),
0xFFFFFFFF.toInt(),
TextSymbol.HorizontalAlignment.CENTER,
TextSymbol.VerticalAlignment.BOTTOM
)
textSymbol.offsetY = -4f
// create a composite symbol and add the picture marker symbol and text symbol
val compositeSymbol = CompositeSymbol()
compositeSymbol.symbols.addAll(listOf(pictureMarkerSymbol, textSymbol))
// create a graphic to add to the overlay and update the route
val graphic = Graphic(locationPoint, compositeSymbol)
stopsOverlay.graphics.add(graphic)
updateRoute()
} catch (e: Exception) {
Log.e(TAG, "Failed to create composite symbol: ${e.stackTrace}")
}
}
override fun onPause() {
mapView.pause()
super.onPause()
}
override fun onResume() {
super.onResume()
mapView.resume()
}
override fun onDestroy() {
mapView.dispose()
super.onDestroy()
}
}
|
apache-2.0
|
a30911819dbc5dfbbcaa46fa084731d7
| 37.440994 | 117 | 0.619971 | 5.037851 | false | false | false | false |
kunickiaj/vault-kotlin
|
src/main/kotlin/com/adamkunicki/vault/VaultConfiguration.kt
|
1
|
1693
|
/*
* Copyright 2016 Adam Kunicki
*
* 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.adamkunicki.vault
data class VaultConfiguration(
val adddress: String = VAULT_ADDRESS,
val token: String = "",
val openTimeout: Int = 0,
val proxyAddress: String = "",
val proxyPort: Int = 8080,
val proxyUsername: String = "",
val proxyPassword: String = "",
val readTimeout: Int = 0,
val sslCiphers: String = SSL_CIPHERS,
val sslPemFile: String = "",
val sslPemPassphrase: String = "",
val sslCaCert: String = "",
val sslCaPath: String = "",
val sslVerify: Boolean = true,
val sslTimeout: Int = 0,
val timeout: Int = 0
) {
companion object {
// The default vault address.
val VAULT_ADDRESS = "https://127.0.0.1:8200"
// val VAULT_DISK_TOKEN
// SSL ciphers to allow. This should not be changed.
val SSL_CIPHERS = "TLSv1.2"
// The default number of request retry attempts.
val RETRY_ATTEMPTS = 2
// The default backoff interval for retries.
val RETRY_BASE = 0.05
// The maximum amount of time for a single exponential backoff to sleep.
val RETRY_MAX_WAIT = 2.0
}
}
|
apache-2.0
|
07a5f5ccbb21f383f60714c5a15eae66
| 29.8 | 76 | 0.673361 | 3.804494 | false | false | false | false |
openbase/jul
|
module/communication/default/src/main/java/org/openbase/jul/communication/iface/Publisher.kt
|
1
|
3747
|
package org.openbase.jul.communication.iface
import com.google.protobuf.Any
import com.google.protobuf.Message
import org.openbase.jul.communication.iface.Communicator
import java.lang.InterruptedException
import org.openbase.jul.communication.iface.RPCCommunicator
import org.openbase.jul.communication.config.CommunicatorConfig
import org.openbase.jul.communication.iface.RPCClient
import org.openbase.jul.exception.CouldNotPerformException
import org.openbase.type.communication.EventType.Event
import org.openbase.type.communication.ScopeType.Scope
/*
* #%L
* JUL Communication Default
* %%
* Copyright (C) 2015 - 2021 openbase.org
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/ /**
*
* @author [Divine Threepwood](mailto:[email protected])
*/
interface Publisher : Communicator {
/**
* Send an [Event] to all subscriber.
*
* @param event the event to send.
* @return modified event with set timing information.
* @throws CouldNotPerformException is thrown in case the message could not be sent.
* @throws InterruptedException thrown in case the current thread was internally interrupted.
*/
@Throws(CouldNotPerformException::class, InterruptedException::class)
fun publish(event: Event, attachTimestamp: Boolean = true): Event
/**
* Send data (of type T) to all subscriber.
*
* @param data data to send with default setting from the publisher.
* @return generated event
* @throws CouldNotPerformException is thrown in case the message could not be sent.
* @throws InterruptedException thrown in case the current thread was internally interrupted.
*/
@Throws(CouldNotPerformException::class, InterruptedException::class)
fun publish(data: Message, attachTimestamp: Boolean = true) = publish(Event.newBuilder().setPayload(Any.pack(data)).build(), attachTimestamp)
/**
* Send an [Event] to all subscriber.
*
* @param event the event to send.
* @param scope the scope of the event to send.
* @return modified event with set timing information.
* @throws CouldNotPerformException is thrown in case the message could not be sent.
* @throws InterruptedException thrown in case the current thread was internally interrupted.
*/
@Throws(CouldNotPerformException::class, InterruptedException::class)
fun publish(event: Event, scope: Scope, attachTimestamp: Boolean = true): Event
/**
* Send data (of type T) to all subscriber.
*
* @param data data to send with default setting from the publisher.
* @param scope the scope of the event to send.
* @return generated event
* @throws CouldNotPerformException is thrown in case the message could not be sent.
* @throws InterruptedException thrown in case the current thread was internally interrupted.
*/
@Throws(CouldNotPerformException::class, InterruptedException::class)
fun publish(data: Message, scope: Scope, attachTimestamp: Boolean = true) = publish(Event.newBuilder().setPayload(Any.pack(data)).build(), scope, attachTimestamp)
}
|
lgpl-3.0
|
0e2c12a4fe1aacbfcfe7876bbd48be6e
| 43.607143 | 166 | 0.736322 | 4.367133 | false | false | false | false |
joseph-roque/BowlingCompanion
|
app/src/main/java/ca/josephroque/bowlingcompanion/utils/sharing/ShareUtils.kt
|
1
|
6945
|
package ca.josephroque.bowlingcompanion.utils.sharing
import android.app.Activity
import android.graphics.Bitmap
import android.widget.Toast
import android.os.Environment
import java.io.File
import java.io.FileOutputStream
import java.lang.Exception
import android.provider.MediaStore
import android.content.ContentValues
import ca.josephroque.bowlingcompanion.R
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.launch
import android.content.Intent
import android.graphics.Canvas
import android.graphics.Paint
import android.util.Log
import android.view.View
import ca.josephroque.bowlingcompanion.common.Android
import ca.josephroque.bowlingcompanion.games.Game
import ca.josephroque.bowlingcompanion.games.views.GameNumberView
import ca.josephroque.bowlingcompanion.games.views.ScoreSheet
import ca.josephroque.bowlingcompanion.utils.Analytics
import ca.josephroque.bowlingcompanion.utils.BCError
import ca.josephroque.bowlingcompanion.utils.Permission
import ca.josephroque.bowlingcompanion.utils.toBitmap
import android.support.v4.content.FileProvider
import ca.josephroque.bowlingcompanion.BuildConfig
/**
* Copyright (C) 2018 Joseph Roque
*
* Utility functions for sharing data from the app.
*/
object ShareUtils {
@Suppress("unused")
private const val TAG = "ShareUtils"
private const val exportFileType = "png"
private const val interGameBorderWidth = 4
fun shareGames(activity: Activity, games: List<Game>) {
if (Permission.WriteExternalStorage.requestPermission(activity)) {
launch(CommonPool) {
val bitmap = buildBitmap(activity, games)
val destination = saveBitmap(activity, games.size, bitmap)
bitmap.recycle()
if (destination == null) {
return@launch
}
val providedImage = FileProvider.getUriForFile(activity,
"${BuildConfig.APPLICATION_ID}.utils.sharing.GameOverviewBitmapFileProvider",
destination)
val shareIntent = Intent(Intent.ACTION_SEND)
shareIntent.type = "image/$exportFileType"
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
shareIntent.putExtra(Intent.EXTRA_STREAM, providedImage)
launch(Android) {
activity.startActivity(Intent.createChooser(shareIntent, activity.resources.getString(R.string.share_image)))
Analytics.trackShareImage(games.size)
}
}
}
}
fun saveGames(activity: Activity, games: List<Game>) {
if (Permission.WriteExternalStorage.requestPermission(activity)) {
launch(CommonPool) {
val bitmap = buildBitmap(activity, games)
val destination = saveBitmap(activity, games.size, bitmap)
bitmap.recycle()
if (destination == null) { return@launch }
launch(Android) {
Toast.makeText(activity, activity.resources.getString(R.string.image_export_success), Toast.LENGTH_SHORT).show()
Analytics.trackSaveImage(games.size)
}
}
}
}
private fun buildBitmap(activity: Activity, games: List<Game>): Bitmap {
// Create view to render game details
val scoreSheet = ScoreSheet(activity)
scoreSheet.frameNumbersEnabled = false
scoreSheet.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
val scoreSheetHeight = scoreSheet.measuredHeight
// Create view to render game number
val gameNumberView = GameNumberView(activity)
gameNumberView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
// Create bitmap to export
val bitmapWidth = scoreSheet.measuredWidth + gameNumberView.measuredWidth
val bitmapHeight = (scoreSheetHeight * games.size) + (interGameBorderWidth * games.size - 1)
val bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
val paintBlackLine = Paint()
paintBlackLine.color = android.graphics.Color.BLACK
games.forEachIndexed { index, game ->
scoreSheet.apply(-1, -1, game)
val scoreSheetBitmap = scoreSheet.toBitmap()
canvas.drawBitmap(scoreSheetBitmap, gameNumberView.measuredWidth.toFloat(), (index * (scoreSheetHeight + interGameBorderWidth)).toFloat(), null)
scoreSheetBitmap.recycle()
gameNumberView.gameNumber = game.ordinal
val gameNumberBitmap = gameNumberView.toBitmap()
canvas.drawBitmap(gameNumberBitmap, 0F, (index * (scoreSheetHeight + interGameBorderWidth)).toFloat(), null)
gameNumberBitmap.recycle()
for (i in 1..interGameBorderWidth) {
val y = (index * (scoreSheetHeight + interGameBorderWidth) - i).toFloat()
canvas.drawLine(0F, y, bitmapWidth.toFloat(), y, paintBlackLine)
}
}
return bitmap
}
private fun saveBitmap(activity: Activity, numberOfGames: Int, bitmap: Bitmap): File? {
// Get filepath to store the image
val externalStorage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
var destination = File(externalStorage, "BowlingCompanion")
destination.mkdirs()
destination = File(destination, "bc_${System.currentTimeMillis()}.$exportFileType")
// Output the file and report any errors
var outputStream: FileOutputStream? = null
try {
outputStream = FileOutputStream(destination)
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
} catch (ex: Exception) {
Log.e(TAG, "Error writing image to file", ex)
launch(Android) {
BCError(
R.string.error_failed_image_export_title,
R.string.error_failed_image_export_message,
BCError.Severity.Error
).show(activity)
}
Analytics.trackSaveImageFailed(numberOfGames)
return null
} finally {
outputStream?.flush()
outputStream?.close()
}
// Update file metadata and add it to the user's gallery
launch(Android) {
val values = ContentValues().apply {
put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis())
put(MediaStore.Images.Media.MIME_TYPE, "image/$exportFileType")
put(MediaStore.MediaColumns.DATA, destination.absolutePath)
}
activity.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
}
return destination
}
}
|
mit
|
7f78d685e4093f6e6ee48c49bde6ade7
| 39.144509 | 156 | 0.660043 | 4.971367 | false | false | false | false |
coil-kt/coil
|
coil-base/src/main/java/coil/util/Contexts.kt
|
1
|
3064
|
@file:JvmName("-Contexts")
package coil.util
import android.content.Context
import android.content.ContextWrapper
import android.content.pm.PackageManager.PERMISSION_GRANTED
import android.content.res.Resources
import android.graphics.drawable.Drawable
import android.os.Build.VERSION.SDK_INT
import android.util.Xml
import androidx.annotation.DrawableRes
import androidx.annotation.XmlRes
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.content.ContextCompat
import androidx.core.content.getSystemService
import androidx.core.content.res.ResourcesCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.vectordrawable.graphics.drawable.AnimatedVectorDrawableCompat
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserException
internal fun Context.getDrawableCompat(@DrawableRes resId: Int): Drawable {
return checkNotNull(AppCompatResources.getDrawable(this, resId)) { "Invalid resource ID: $resId" }
}
internal fun Resources.getDrawableCompat(@DrawableRes resId: Int, theme: Resources.Theme?): Drawable {
return checkNotNull(ResourcesCompat.getDrawable(this, resId, theme)) { "Invalid resource ID: $resId" }
}
/**
* Supports inflating XML [Drawable]s from other package's resources.
*
* Prefer using [Context.getDrawableCompat] for resources that are part of the current package.
*/
internal fun Context.getXmlDrawableCompat(resources: Resources, @XmlRes resId: Int): Drawable {
// Find the XML's start tag.
val parser = resources.getXml(resId)
var type = parser.next()
while (type != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) {
type = parser.next()
}
if (type != XmlPullParser.START_TAG) {
throw XmlPullParserException("No start tag found.")
}
// Modified from androidx.appcompat.widget.ResourceManagerInternal.
if (SDK_INT < 24) {
when (parser.name) {
"vector" -> {
return VectorDrawableCompat.createFromXmlInner(resources, parser,
Xml.asAttributeSet(parser), theme)
}
"animated-vector" -> {
return AnimatedVectorDrawableCompat.createFromXmlInner(this, resources,
parser, Xml.asAttributeSet(parser), theme)
}
}
}
// Fall back to the platform APIs.
return resources.getDrawableCompat(resId, theme)
}
internal fun Context?.getLifecycle(): Lifecycle? {
var context: Context? = this
while (true) {
when (context) {
is LifecycleOwner -> return context.lifecycle
!is ContextWrapper -> return null
else -> context = context.baseContext
}
}
}
internal inline fun <reified T : Any> Context.requireSystemService(): T = getSystemService()!!
internal fun Context.isPermissionGranted(permission: String): Boolean {
return ContextCompat.checkSelfPermission(this, permission) == PERMISSION_GRANTED
}
|
apache-2.0
|
d4f65a84764ea0274887f27069949366
| 36.365854 | 106 | 0.72846 | 4.721109 | false | false | false | false |
mymikemiller/gamegrumpsplayer
|
app/src/main/java/com/mymikemiller/gamegrumpsplayer/util/WatchedMillis.kt
|
1
|
4911
|
package com.mymikemiller.gamegrumpsplayer.util
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.util.Log
import com.mymikemiller.gamegrumpsplayer.Detail
import java.sql.SQLException
/**
* Keeps track of how long you've watched each episode.
*/
class WatchedMillis {
companion object {
// Increment this when the table definition changes
val DATABASE_VERSION: Int = 66
val DATABASE_NAME: String = "WatchedMillis"
val WATCHED_MILLIS_TABLE_NAME: String = "WatchedMillisTable"
// VideoList columns
val KEY_VIDEOID: String="Video_Id"
val KEY_WATCHED_MILLIS: String = "Watched_Millis"
private val WATCHED_MILLIS_TABLE_CREATE =
"CREATE TABLE " + WATCHED_MILLIS_TABLE_NAME + " (" +
KEY_VIDEOID + " TEXT NOT NULL UNIQUE, " +
KEY_WATCHED_MILLIS + " INTEGER);"
// This will return all the Details currently in the database, and will call
// the databaseUpgradeCallback if the database had to be upgraded to a new version by
// incrementing the DATABASE_VERSION above
fun getWatchedMillis (context: Context, detail: Detail): Int{
val dbHelper = WatchedMillisOpenHelper(context.applicationContext)
return dbHelper.getWatchedMillis(detail)
}
fun addOrUpdateWatchedMillis(context:Context, detail: Detail, watchedMillis: Int) {
val dbHelper = WatchedMillisOpenHelper(context.applicationContext)
return dbHelper.addOrUpdateWatchedMillis(detail, watchedMillis)
}
}
class WatchedMillisOpenHelper internal constructor(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
if (oldVersion != newVersion) {
// Simplest implementation is to drop all old tables and recreate them
db.execSQL("DROP TABLE IF EXISTS " + WATCHED_MILLIS_TABLE_NAME)
onCreate(db)
}
}
override fun onCreate(db: SQLiteDatabase) {
db.execSQL(WATCHED_MILLIS_TABLE_CREATE)
}
fun getWatchedMillis(detail: Detail): Int {
// If we don't find any rows, the watchedMillis should be 0
var watchedMillis = 0
// SELECT
// ISNULL(MAX(WatchedMillis),'John Doe')
// FROM
// Users
// WHERE
// Id = @UserId
val SELECT_QUERY = "SELECT $KEY_WATCHED_MILLIS" +
" FROM $WATCHED_MILLIS_TABLE_NAME WHERE $KEY_VIDEOID='${detail.videoId}'"
//val SELECT_QUERY = "SELECT * FROM $WATCHED_MILLIS_TABLE_NAME"
val db: SQLiteDatabase
try {
db = this.readableDatabase
} catch (s: SQLException) {
// We sometimes get an error opening the database.
// Don't get the watched time, just return 0.
return 0
}
val cursor = db.rawQuery(SELECT_QUERY, null)
try {
if (cursor.moveToFirst()) {
watchedMillis = cursor.getInt(cursor.getColumnIndex(KEY_WATCHED_MILLIS))
}
} catch (e: Exception) {
Log.d(ContentValues.TAG, "Error while trying to get watched millis from database")
} finally {
if (cursor != null && !cursor.isClosed) {
cursor.close()
}
db.close()
}
return watchedMillis
}
// Add or update the watched time.
fun addOrUpdateWatchedMillis(detail: Detail, watchedMillis: Int) {
val db: SQLiteDatabase
try {
db = this.writableDatabase
} catch (s: SQLException) {
// We sometimes get an error opening the database.
// Don't save the watched time. 's ok. Maybe next time.
return
}
val initialValues = ContentValues()
initialValues.put(KEY_VIDEOID, detail.videoId) // the execution is different if _id is 2
initialValues.put(KEY_WATCHED_MILLIS, watchedMillis)
// This is some magic that will insert, and if it can't, it'll update
val id = db.insertWithOnConflict(WATCHED_MILLIS_TABLE_NAME, null, initialValues, SQLiteDatabase.CONFLICT_IGNORE)
if (id == (-1).toLong()) {
db.update(WATCHED_MILLIS_TABLE_NAME, initialValues, "$KEY_VIDEOID=?", arrayOf(detail.videoId)) // number 1 is the _id here, update to variable for your code
}
db.close()
}
}
}
|
mit
|
466f848ca94cc78ef6a159939e9c3dba
| 38.604839 | 173 | 0.592955 | 4.828909 | false | false | false | false |
ujpv/intellij-rust
|
src/test/kotlin/org/rust/ide/intentions/UnElideLifetimesIntentionTest.kt
|
1
|
1333
|
package org.rust.ide.intentions
class UnElideLifetimesIntentionTest : RustIntentionTestBase(UnElideLifetimesIntention()) {
fun testUnavailable1() = doUnavailableTest(
"""
fn bar/*caret*/(x: i32) -> i32 {}
"""
)
fun testUnavailableBlockBody() = doUnavailableTest(
"""
fn bar(x: &i32) {/*caret*/}
"""
)
fun testUnavailableNoArgs() = doUnavailableTest(
"""
fn bar(/*caret*/) {}
"""
)
fun testUnavailableUnElided() = doUnavailableTest(
"""
fn bar<'a>(x: &'a /*caret*/ i32) {}
"""
)
fun testSimple() = doAvailableTest(
"""
fn foo(p: &/*caret*/ i32) -> & i32 { p }
"""
,
"""
fn foo<'a>(p: &/*caret*/'a i32) -> &'a i32 { p }
"""
)
fun testGenericType() = doAvailableTest(
"""
fn foo<T>(p1:/*caret*/ &i32, p2: T) -> & i32 { p }
"""
,
"""
fn foo<'a, T>(p1:/*caret*/ &'a i32, p2: T) -> &'a i32 { p }
"""
)
fun testUnknown() = doAvailableTest(
"""
fn foo(p1: &i32,/*caret*/ p2: &i32) -> &i32 { p2 }
"""
,
"""
fn foo<'a, 'b>(p1: &'a i32,/*caret*/ p2: &'b i32) -> &'<selection>unknown</selection> i32 { p2 }
"""
)
}
|
mit
|
01ac61f0592213358e7b0f1c96ca43b9
| 21.216667 | 104 | 0.43886 | 3.564171 | false | true | false | false |
LorittaBot/Loritta
|
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/administration/WarnListCommand.kt
|
1
|
4880
|
package net.perfectdreams.loritta.morenitta.commands.vanilla.administration
import net.perfectdreams.loritta.morenitta.commands.AbstractCommand
import net.perfectdreams.loritta.morenitta.commands.CommandContext
import net.perfectdreams.loritta.morenitta.dao.Warn
import net.perfectdreams.loritta.morenitta.tables.Warns
import net.perfectdreams.loritta.morenitta.utils.Constants
import net.perfectdreams.loritta.morenitta.utils.extensions.humanize
import net.perfectdreams.loritta.common.locale.BaseLocale
import net.perfectdreams.loritta.common.locale.LocaleKeyData
import net.dv8tion.jda.api.EmbedBuilder
import net.dv8tion.jda.api.Permission
import net.perfectdreams.loritta.common.commands.ArgumentType
import net.perfectdreams.loritta.common.commands.CommandArguments
import net.perfectdreams.loritta.common.commands.arguments
import net.perfectdreams.loritta.morenitta.utils.PunishmentAction
import org.jetbrains.exposed.sql.and
import net.perfectdreams.loritta.morenitta.LorittaBot
class WarnListCommand(loritta: LorittaBot) : AbstractCommand(loritta, "punishmentlist", listOf("listadeavisos", "modlog", "modlogs", "infractions", "warnlist", "warns"), net.perfectdreams.loritta.common.commands.CommandCategory.MODERATION) {
companion object {
private val LOCALE_PREFIX = "commands.command"
}
override fun getDescriptionKey() = LocaleKeyData("$LOCALE_PREFIX.warnlist.description")
override fun getExamplesKey() = LocaleKeyData("$LOCALE_PREFIX.warnlist.examples")
override fun getUsage(): CommandArguments {
return arguments {
argument(ArgumentType.USER) {
optional = false
}
}
}
override fun getDiscordPermissions(): List<Permission> {
return listOf(Permission.KICK_MEMBERS)
}
override fun canUseInPrivateChannel(): Boolean {
return false
}
override suspend fun run(context: CommandContext, locale: BaseLocale) {
val user = context.getUserAt(0)
if (user != null) {
val warns = loritta.newSuspendedTransaction {
Warn.find { (Warns.guildId eq context.guild.idLong) and (Warns.userId eq user.idLong) }.sortedBy { it.receivedAt } .toMutableList()
}
if (warns.isEmpty()) {
context.reply(
context.locale["$LOCALE_PREFIX.warnlist.userDoesntHaveWarns", user.asMention],
Constants.ERROR
)
return
}
val warnPunishments = AdminUtils.retrieveWarnPunishmentActions(loritta, context.config)
val embed = EmbedBuilder().apply {
setColor(Constants.DISCORD_BLURPLE)
setAuthor(user.name, null, user.effectiveAvatarUrl)
setTitle("\uD83D\uDE94 ${context.locale["$LOCALE_PREFIX.warnlist.title"]}")
val warn = warns.size
val nextPunishment = warnPunishments.firstOrNull { it.warnCount == warn + 1 }
if (nextPunishment != null) {
val type = when (nextPunishment.punishmentAction) {
PunishmentAction.BAN -> context.locale["$LOCALE_PREFIX.ban.punishAction"]
PunishmentAction.KICK -> context.locale["$LOCALE_PREFIX.kick.punishAction"]
PunishmentAction.MUTE -> context.locale["$LOCALE_PREFIX.mute.punishAction"]
else -> throw RuntimeException("Punishment $nextPunishment is not supported")
}.toLowerCase()
setFooter(context.locale["$LOCALE_PREFIX.warnlist.nextPunishment", type], null)
}
warns.forEachIndexed({ idx, warn ->
addField(
context.locale["$LOCALE_PREFIX.warn.punishAction"],
"""**${context.locale["$LOCALE_PREFIX.warnlist.common"]} #${idx + 1}**
|**${context.locale["$LOCALE_PREFIX.ban.punishedBy"]}:** <@${warn.punishedById}>
|**${context.locale["$LOCALE_PREFIX.ban.punishmentReason"]}:** ${warn.content}
|**${context.locale["$LOCALE_PREFIX.warnlist.date"]}:** ${warn.receivedAt.humanize(locale)}
""".trimMargin(),
false
)
})
}
val message = context.sendMessage(context.getAsMention(true), embed.build())
/* message.onReactionAddByAuthor(context) {
val idx = Constants.INDEXES.indexOf(it.emoji.name)
val warn = warns.getOrNull(idx)
if (warn != null) {
val punisher = loritta.lorittaShards.getUserById(warn.punishedById)
val embed = EmbedBuilder().apply {
setColor(Constants.DISCORD_BLURPLE)
setAuthor(user.name, null, user.effectiveAvatarUrl)
setTitle("\uD83D\uDE94 Aviso")
if (punisher != null)
setThumbnail(punisher.effectiveAvatarUrl)
addField(
locale["BAN_PunishedBy"],
"<@${warn.punishedById}>",
true
)
addField(
locale["BAN_PunishmentReason"],
"${warn.content}",
true
)
addField(
locale["KYM_DATE"],
warn.receivedAt.humanize(locale),
true
)
}
val _message = message.edit(context.getAsMention(true), embed.build())
}
}
for (i in 0 until warns.size) {
message.addReaction(Constants.INDEXES[i]).queue()
} */
} else {
this.explain(context)
}
}
}
|
agpl-3.0
|
81d662438d73a1b75daffbeefcf5779d
| 34.889706 | 241 | 0.715164 | 3.647235 | false | false | false | false |
darakeon/dfm
|
android/ErrorLogs/src/main/kotlin/com/darakeon/dfm/error_logs/ListActivity.kt
|
1
|
1761
|
package com.darakeon.dfm.error_logs
import android.os.Bundle
import android.os.Handler
import android.view.View
import com.darakeon.dfm.error_logs.service.SiteErrorService
import com.darakeon.dfm.lib.Log
import com.darakeon.dfm.lib.api.entities.status.ErrorList
import com.darakeon.dfm.lib.api.entities.status.ErrorLog
import com.darakeon.dfm.lib.extensions.refresh
import kotlinx.android.synthetic.main.list.list
import kotlinx.android.synthetic.main.list.main
import kotlinx.android.synthetic.main.list.message
import kotlinx.android.synthetic.main.list.start
import kotlinx.android.synthetic.main.list.stop
class ListActivity : BaseActivity() {
private var logs: MutableList<ErrorLog> = mutableListOf()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.list)
Handler(mainLooper).postDelayed({
api.listErrors(this::fillList)
}, 5000)
toggleButtons()
main.setOnRefreshListener { refresh() }
main.listChild = list
}
private fun fillList(errors: ErrorList) {
if (errors.count == 0) {
message.setText(R.string.empty)
logs.clear()
} else {
message.text = ""
errors.logs.forEach(logs::add)
}
list.adapter = ErrorAdapter(this, api, logs)
}
@Suppress("UNUSED_PARAMETER")
fun stopService(view: View) {
SiteErrorService.stop(this)
toggleButtons()
}
@Suppress("UNUSED_PARAMETER")
fun startService(view: View) {
SiteErrorService.start(this)
toggleButtons()
}
private fun toggleButtons() {
Log.record(SiteErrorService.running)
val running = SiteErrorService.running
toggle(stop, running)
toggle(start, !running)
}
private fun toggle(view: View, visible: Boolean) {
view.visibility = if (visible) View.VISIBLE else View.GONE
}
}
|
gpl-3.0
|
a1f966003c5fd28bfc9e3ea4a5b525ad
| 24.897059 | 60 | 0.759796 | 3.373563 | false | false | false | false |
cbeyls/fosdem-companion-android
|
app/src/main/java/be/digitalia/fosdem/activities/SearchResultActivity.kt
|
1
|
3769
|
package be.digitalia.fosdem.activities
import android.app.SearchManager
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.EditText
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isGone
import androidx.core.widget.doOnTextChanged
import androidx.fragment.app.add
import androidx.fragment.app.commit
import androidx.lifecycle.lifecycleScope
import be.digitalia.fosdem.R
import be.digitalia.fosdem.fragments.SearchResultListFragment
import be.digitalia.fosdem.utils.trimNonAlpha
import be.digitalia.fosdem.viewmodels.SearchViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.sample
@AndroidEntryPoint
class SearchResultActivity : AppCompatActivity(R.layout.search_result) {
private val viewModel: SearchViewModel by viewModels()
private lateinit var searchEditText: EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setSupportActionBar(findViewById(R.id.toolbar))
supportActionBar?.setDisplayHomeAsUpEnabled(true)
searchEditText = findViewById(R.id.search_edittext)
val searchClearButton: View = findViewById(R.id.search_clear)
@OptIn(kotlinx.coroutines.FlowPreview::class)
searchEditText.textChangeEvents
.conflate()
.onEach {
// immediately update the button state
searchClearButton.isGone = it.isNullOrEmpty()
}
.sample(SEARCH_INPUT_SAMPLE_MILLIS)
.onEach {
// only update the results every SEARCH_INPUT_SAMPLE_MILLIS
viewModel.setQuery(it?.toString().orEmpty())
}
.launchIn(lifecycleScope)
searchClearButton.setOnClickListener {
searchEditText.text = null
}
if (savedInstanceState == null) {
supportFragmentManager.commit { add<SearchResultListFragment>(R.id.content) }
handleIntent(intent)
searchEditText.requestFocus()
}
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
viewModel.setQuery(searchEditText.text?.toString().orEmpty())
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
handleIntent(intent)
}
private fun handleIntent(intent: Intent) {
val query = when (intent.action) {
Intent.ACTION_SEARCH, GMS_ACTION_SEARCH -> intent.getStringExtra(SearchManager.QUERY)
?.trimNonAlpha().orEmpty()
else -> ""
}
viewModel.setQuery(query)
searchEditText.setText(query)
}
override fun onSupportNavigateUp(): Boolean {
onBackPressedDispatcher.onBackPressed()
return true
}
override fun finish() {
super.finish()
overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
}
private val EditText.textChangeEvents: Flow<CharSequence?>
get() = callbackFlow {
val textWatcher = doOnTextChanged { text, _, _, _ -> trySend(text) }
awaitClose { removeTextChangedListener(textWatcher) }
}
companion object {
// Search Intent sent by Google Now
private const val GMS_ACTION_SEARCH = "com.google.android.gms.actions.SEARCH_ACTION"
private const val SEARCH_INPUT_SAMPLE_MILLIS = 400L
}
}
|
apache-2.0
|
8922c1cbc3aae235d74b0b4500ce445e
| 33.587156 | 97 | 0.700451 | 5.018642 | false | false | false | false |
Muks14x/susi_android
|
app/src/main/java/org/fossasia/susi/ai/skills/skilllisting/SkillListingFragment.kt
|
1
|
2557
|
package org.fossasia.susi.ai.skills.skilllisting
import android.app.Fragment
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_skill_listing.*
import org.fossasia.susi.ai.R
import org.fossasia.susi.ai.rest.responses.susi.SkillData
import org.fossasia.susi.ai.skills.SkillsActivity
import org.fossasia.susi.ai.skills.skilllisting.adapters.recycleradapters.SkillGroupAdapter
import org.fossasia.susi.ai.skills.skilllisting.contract.ISkillListingPresenter
import org.fossasia.susi.ai.skills.skilllisting.contract.ISkillListingView
/**
*
* Created by chiragw15 on 15/8/17.
*/
class SkillListingFragment: Fragment(), ISkillListingView {
lateinit var skillListingPresenter: ISkillListingPresenter
var skills: ArrayList<Pair<String, Map<String, SkillData>>> = ArrayList()
lateinit var skillGroupAdapter: SkillGroupAdapter
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
return inflater.inflate(R.layout.fragment_skill_listing, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
(activity as SkillsActivity).title = (activity as SkillsActivity).getString(R.string.skills_activity)
skillListingPresenter = SkillListingPresenter()
skillListingPresenter.onAttach(this)
setUPAdapter()
skillListingPresenter.getGroups()
super.onViewCreated(view, savedInstanceState)
}
fun setUPAdapter() {
val mLayoutManager = LinearLayoutManager(activity)
mLayoutManager.orientation = LinearLayoutManager.VERTICAL
skillGroups.layoutManager = mLayoutManager
skillGroupAdapter = SkillGroupAdapter(activity, skills)
skillGroups.adapter = skillGroupAdapter
}
override fun visibilityProgressBar(boolean: Boolean) {
if(boolean) skillWait.visibility = View.VISIBLE else skillWait.visibility = View.GONE
}
override fun displayError() {
if(activity != null) {
error_skill_fetch.visibility = View.VISIBLE
}
}
override fun updateAdapter(skills: ArrayList<Pair<String, Map<String, SkillData>>>) {
this.skills.clear()
this.skills.addAll(skills)
skillGroupAdapter.notifyDataSetChanged()
}
override fun onDestroyView() {
skillListingPresenter.onDetach()
super.onDestroyView()
}
}
|
apache-2.0
|
bcf1465f4e0fbc60a6fd705cf70091dc
| 36.617647 | 115 | 0.74736 | 4.478109 | false | false | false | false |
ngageoint/mage-android
|
mage/src/main/java/mil/nga/giat/mage/observation/edit/FormPickerBottomSheetFragment.kt
|
1
|
4661
|
package mil.nga.giat.mage.observation.edit
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.PorterDuff
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.widget.ImageViewCompat
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.google.gson.JsonParser
import dagger.hilt.android.AndroidEntryPoint
import mil.nga.giat.mage.R
import mil.nga.giat.mage.databinding.FragmentFormPickerBottomSheetBinding
import mil.nga.giat.mage.databinding.ViewFormPickerItemBinding
import mil.nga.giat.mage.form.Form
import mil.nga.giat.mage.form.FormViewModel
import mil.nga.giat.mage.network.gson.asJsonObjectOrNull
import mil.nga.giat.mage.sdk.datastore.user.EventHelper
@AndroidEntryPoint
class FormPickerBottomSheetFragment: BottomSheetDialogFragment() {
interface OnFormClickListener {
fun onFormPicked(form: Form)
}
data class FormState(val form: Form, val disabled: Boolean)
var formPickerListener: OnFormClickListener? = null
private lateinit var binding: FragmentFormPickerBottomSheetBinding
private lateinit var viewModel: FormViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProvider(this).get(FormViewModel::class.java)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentFormPickerBottomSheetBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val recyclerView: RecyclerView = view.findViewById(R.id.recycler_view)
recyclerView.layoutManager = LinearLayoutManager(context)
// TODO get from ViewModel
val jsonForms = EventHelper.getInstance(context).currentEvent.forms
val forms = jsonForms
.asSequence()
.mapNotNull { form ->
JsonParser.parseString(form.json).asJsonObjectOrNull()?.let { json ->
Form.fromJson(json)
}
}
.filterNot { it.archived }
.map { form ->
val formMax = form.max
val totalOfForm = viewModel.observationState.value?.forms?.value?.filter { it.definition.id == form.id }?.size ?: 0
val disabled = formMax != null && totalOfForm <= formMax
FormState(form, disabled)
}
.toList()
recyclerView.adapter = FormAdapter(forms) { onForm(it.form) }
}
private fun onForm(form: Form) {
dismiss()
formPickerListener?.onFormPicked(form)
}
private class FormAdapter(private val forms: List<FormState>, private val onFormClicked: (FormState) -> Unit) : RecyclerView.Adapter<FormViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FormViewHolder {
val binding = ViewFormPickerItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return FormViewHolder(binding) { position -> onFormClicked(forms[position]) }
}
override fun onBindViewHolder(holder: FormViewHolder, position: Int) {
val formState = forms[position]
holder.bindForm(formState)
}
override fun getItemCount() = forms.size
}
private class FormViewHolder(val binding: ViewFormPickerItemBinding, onFormClicked: (Int) -> Unit) : RecyclerView.ViewHolder(binding.root) {
init {
binding.root.setOnClickListener { onFormClicked(adapterPosition) }
}
fun bindForm(formState: FormState) {
binding.formName.text = formState.form.name
binding.formDescription.text = formState.form.description
if (formState.disabled) {
binding.formName.alpha = .38f
binding.formDescription.alpha = .38f
val color = formState.form.hexColor.replace("#", "#60")
ImageViewCompat.setImageTintMode(binding.formIcon, PorterDuff.Mode.SRC_ATOP)
ImageViewCompat.setImageTintList(binding.formIcon, ColorStateList.valueOf(Color.parseColor(color)))
} else {
binding.formName.alpha = .87f
binding.formDescription.alpha = .60f
// Lets add a tiny bit of transparency to soften things up.
val color = formState.form.hexColor.replace("#", "#DE")
ImageViewCompat.setImageTintMode(binding.formIcon, PorterDuff.Mode.SRC_ATOP)
ImageViewCompat.setImageTintList(binding.formIcon, ColorStateList.valueOf(Color.parseColor(color)))
}
}
}
}
|
apache-2.0
|
ce089580aa2a7596a1e0a81fd1d0b89f
| 35.421875 | 155 | 0.740614 | 4.405482 | false | false | false | false |
ngageoint/mage-android
|
mage/src/main/java/mil/nga/giat/mage/map/Geocoder.kt
|
1
|
2463
|
package mil.nga.giat.mage.map
import android.app.Application
import android.location.Geocoder
import android.util.Log
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import mil.nga.gars.GARS
import mil.nga.giat.mage.coordinate.CoordinateSystem
import mil.nga.mgrs.MGRS
import java.io.IOException
import java.text.ParseException
import javax.inject.Inject
class Geocoder @Inject constructor(
private val application: Application
) {
data class SearchResult(val markerOptions: MarkerOptions, val zoom: Int)
suspend fun search(text: String): SearchResult? = withContext(Dispatchers.IO) {
if (MGRS.isMGRS(text)) {
try {
val point = MGRS.parse(text).toPoint()
val options = MarkerOptions()
.position(LatLng(point.latitude, point.longitude))
.title(CoordinateSystem.MGRS.name)
.snippet(text)
SearchResult(options, 18)
} catch (ignore: ParseException) {
null
}
} else if (GARS.isGARS(text)) {
try {
val point = GARS.parse(text).toPoint()
val options = MarkerOptions()
.position(LatLng(point.latitude, point.longitude))
.title(CoordinateSystem.GARS.name)
.snippet(text)
SearchResult(options, 18)
} catch (ignore: ParseException) {
null
}
} else {
val geocoder = Geocoder(application)
try {
val addresses = geocoder.getFromLocationName(text, 1)
addresses.firstOrNull()?.let { address ->
val addressLines = address.maxAddressLineIndex + 1
val markerOptions = MarkerOptions()
.position(LatLng(address.latitude, address.longitude))
.title(text)
.snippet(address.getAddressLine(0))
val zoom = MAX_ADDRESS_ZOOM - (MAX_ADDRESS_LINES - addressLines) * 2
SearchResult(markerOptions, zoom)
}
} catch (e: IOException) {
Log.e(LOG_NAME, "Problem executing search.", e)
null
}
}
}
companion object {
private val LOG_NAME = Geocoder::class.java.name
private const val MAX_ADDRESS_LINES = 3
private const val MAX_ADDRESS_ZOOM = 18
}
}
|
apache-2.0
|
659d10a0b95e10cc7c238f9eff4885e8
| 31 | 83 | 0.616322 | 4.367021 | false | false | false | false |
edsilfer/presence-control
|
app/src/main/java/br/com/edsilfer/android/presence_control/place/presentation/model/MapCircle.kt
|
1
|
547
|
package br.com.edsilfer.android.presence_control.place.presentation.model
import br.com.edsilfer.android.presence_control.R
import com.google.android.gms.maps.model.LatLng
import java.io.Serializable
/**
* Created by ferna on 6/1/2017.
*/
data class MapCircle(
val location: LatLng? = null,
val radius: Int = 10,
val clearPrevious: Boolean = true,
val fillColor: Int = R.color.color_circle_fill,
val borderColor: Int = R.color.color_circle_border,
val moveCamera: Boolean = true
) : Serializable
|
apache-2.0
|
bbcbbc764342a8d0a46aa73a8815bd8e
| 31.235294 | 73 | 0.702011 | 3.671141 | false | false | false | false |
andrei-heidelbacher/algostorm
|
clients/algostorm-android/src/main/kotlin/com/andreihh/algostorm/android/EngineHolder.kt
|
1
|
2281
|
/*
* Copyright (c) 2017 Andrei Heidelbacher <[email protected]>
*
* 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.andreihh.algostorm.android
import android.content.Context
import android.os.Bundle
import android.view.SurfaceView
import com.andreihh.algostorm.core.drivers.input.Input
import com.andreihh.algostorm.core.drivers.ui.UiListener
import com.andreihh.algostorm.core.engine.Engine
import com.andreihh.algostorm.core.engine.Platform
class EngineHolder(context: Context) {
private val appContext = context.applicationContext
private val audioDriver = AndroidAudioDriver(appContext)
private val graphicsDriver = AndroidGraphicsDriver(appContext)
private val inputDriver = AndroidInputDriver(appContext)
private val fileSystemDriver = AndroidFileSystemDriver(appContext)
private val uiDriver = AndroidUiDriver(appContext)
private val platform = Platform(
audioDriver, graphicsDriver, inputDriver, fileSystemDriver, uiDriver
)
private val engine = Engine(platform)
private fun Bundle.toMap(): Map<String, Any?> =
keySet().associate { it to get(it) }
fun init(args: Bundle) {
engine.init(args.toMap())
}
fun sendInput(input: Input) {
inputDriver.write(input)
}
fun setListener(listener: UiListener) {
uiDriver.setListener(listener)
}
fun attachSurface(surfaceView: SurfaceView) {
surfaceView.setOnTouchListener(inputDriver)
graphicsDriver.attachSurface(surfaceView.holder)
}
fun detachSurface() {
graphicsDriver.detachSurface()
}
fun start() {
engine.start()
}
fun stop() {
engine.stop(100)
}
fun release() {
engine.release()
}
}
|
apache-2.0
|
49414f8d115c2ca53276b9a9346b1a2f
| 29.413333 | 76 | 0.716791 | 4.328273 | false | false | false | false |
robinverduijn/gradle
|
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/codegen/ApiTypeProvider.kt
|
1
|
20187
|
/*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl.codegen
import com.google.common.annotations.VisibleForTesting
import org.gradle.api.Incubating
import org.gradle.internal.classanalysis.AsmConstants.ASM_LEVEL
import org.gradle.kotlin.dsl.accessors.contains
import org.gradle.kotlin.dsl.accessors.primitiveTypeStrings
import org.gradle.kotlin.dsl.support.ClassBytesRepository
import org.gradle.kotlin.dsl.support.classPathBytesRepositoryFor
import org.gradle.kotlin.dsl.support.unsafeLazy
import org.jetbrains.org.objectweb.asm.AnnotationVisitor
import org.jetbrains.org.objectweb.asm.Attribute
import org.jetbrains.org.objectweb.asm.ClassReader
import org.jetbrains.org.objectweb.asm.ClassReader.SKIP_CODE
import org.jetbrains.org.objectweb.asm.ClassReader.SKIP_DEBUG
import org.jetbrains.org.objectweb.asm.ClassReader.SKIP_FRAMES
import org.jetbrains.org.objectweb.asm.FieldVisitor
import org.jetbrains.org.objectweb.asm.Opcodes.ACC_ABSTRACT
import org.jetbrains.org.objectweb.asm.Opcodes.ACC_PUBLIC
import org.jetbrains.org.objectweb.asm.Opcodes.ACC_STATIC
import org.jetbrains.org.objectweb.asm.Opcodes.ACC_SYNTHETIC
import org.jetbrains.org.objectweb.asm.Opcodes.ACC_VARARGS
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.TypePath
import org.jetbrains.org.objectweb.asm.signature.SignatureReader
import org.jetbrains.org.objectweb.asm.signature.SignatureVisitor
import org.jetbrains.org.objectweb.asm.tree.AnnotationNode
import org.jetbrains.org.objectweb.asm.tree.ClassNode
import org.jetbrains.org.objectweb.asm.tree.MethodNode
import java.io.Closeable
import java.io.File
import java.util.ArrayDeque
import javax.annotation.Nullable
@VisibleForTesting
fun apiTypeProviderFor(
classPath: List<File>,
classPathDependencies: List<File> = emptyList(),
parameterNamesSupplier: ParameterNamesSupplier = { null }
): ApiTypeProvider =
ApiTypeProvider(classPathBytesRepositoryFor(classPath, classPathDependencies), parameterNamesSupplier)
private
typealias ApiTypeSupplier = () -> ApiType
typealias ParameterNamesSupplier = (String) -> List<String>?
fun ParameterNamesSupplier.parameterNamesFor(typeName: String, functionName: String, parameterTypeNames: List<String>): List<String>? =
this("$typeName.$functionName(${parameterTypeNames.joinToString(",")})")
/**
* Provides [ApiType] instances by Kotlin source name from a class path.
*
* Keeps JAR files open for fast lookup, must be closed.
* Once closed, type graph navigation from [ApiType] and [ApiFunction] instances
* will throw [IllegalStateException].
*
* Limitations:
* - supports Java byte code only, not Kotlin
* - does not support nested Java arrays as method parameters
* - does not support generics with multiple bounds
*/
@VisibleForTesting
class ApiTypeProvider internal constructor(
private val repository: ClassBytesRepository,
parameterNamesSupplier: ParameterNamesSupplier
) : Closeable {
private
val context = Context(this, parameterNamesSupplier)
private
val apiTypesBySourceName = mutableMapOf<String, ApiTypeSupplier?>()
private
var closed = false
fun type(sourceName: String): ApiType? = open {
apiTypesBySourceName.computeIfAbsent(sourceName) {
repository.classBytesFor(sourceName)?.let { apiTypeFor(sourceName) { it } }
}?.invoke()
}
fun allTypes(): Sequence<ApiType> = open {
repository.allClassesBytesBySourceName().map { (sourceName, classBytes) ->
apiTypesBySourceName.computeIfAbsent(sourceName) {
apiTypeFor(sourceName, classBytes)
}!!
}.map { it() }
}
override fun close() =
try {
repository.close()
} finally {
closed = true
}
private
fun apiTypeFor(sourceName: String, classBytes: () -> ByteArray) = {
ApiType(sourceName, classNodeFor(classBytes), context)
}
private
fun classNodeFor(classBytesSupplier: () -> ByteArray) = {
ApiTypeClassNode().also {
ClassReader(classBytesSupplier()).accept(it, SKIP_DEBUG or SKIP_CODE or SKIP_FRAMES)
}
}
private
fun <T> open(action: () -> T): T =
if (closed) throw IllegalStateException("ApiTypeProvider closed!")
else action()
internal
class Context(
private val typeProvider: ApiTypeProvider,
private val parameterNamesSupplier: ParameterNamesSupplier
) {
fun type(sourceName: String): ApiType? =
typeProvider.type(sourceName)
fun parameterNamesFor(typeName: String, functionName: String, parameterTypeNames: List<String>): List<String>? =
parameterNamesSupplier.parameterNamesFor(typeName, functionName, parameterTypeNames)
}
}
@VisibleForTesting
class ApiType internal constructor(
val sourceName: String,
private val delegateSupplier: () -> ClassNode,
private val context: ApiTypeProvider.Context
) {
val isPublic: Boolean
get() = delegate.access.isPublic
val isDeprecated: Boolean
get() = delegate.visibleAnnotations.has<java.lang.Deprecated>()
val isIncubating: Boolean
get() = delegate.visibleAnnotations.has<Incubating>()
val isSAM: Boolean by unsafeLazy {
delegate.access.isAbstract && singleAbstractMethodOf(delegate)?.access?.isPublic == true
}
val typeParameters: List<ApiTypeUsage> by unsafeLazy {
context.apiTypeParametersFor(visitedSignature)
}
val functions: List<ApiFunction> by unsafeLazy {
delegate.methods.filter(::isSignificantDeclaration).map { ApiFunction(this, it, context) }
}
private
fun singleAbstractMethodOf(classNode: ClassNode) =
classNode.methods.singleOrNull { it.access.run { !isStatic && isAbstract } }
/**
* Test if a method is a prime declaration or an overrides that change the signature.
*
* There's no way to tell from the byte code that a method overrides the signature
* of a parent declaration other than crawling up the type hierarchy.
*/
private
fun isSignificantDeclaration(methodNode: MethodNode): Boolean {
if (methodNode.access.isSynthetic) return false
if (!hasSuperType) return true
fun ArrayDeque<String>.addSuperTypesOf(classNode: ClassNode) {
classNode.interfaces.forEach { push(it) }
if (classNode.superName != null) push(classNode.superName)
}
val superTypeStack = ArrayDeque<String>().apply {
addSuperTypesOf(delegate)
}
val visited = mutableSetOf<String>()
val matchesMethodNode = { candidate: MethodNode ->
candidate.desc == methodNode.desc && candidate.signature == methodNode.signature
}
while (superTypeStack.isNotEmpty()) {
val superTypeName = superTypeStack.pop()
if (!visited.add(superTypeName)) continue
val superType = typeForInternalName(superTypeName) ?: continue
if (superType.delegate.methods.any(matchesMethodNode)) return false
superTypeStack.addSuperTypesOf(superType.delegate)
}
return true
}
private
fun typeForInternalName(internalType: String): ApiType? =
context.type(sourceNameOfBinaryName(binaryNameOfInternalName(internalType)))
private
val hasSuperType: Boolean by unsafeLazy {
delegate.interfaces.isNotEmpty() || delegate.superName != null
}
private
val delegate: ClassNode by unsafeLazy {
delegateSupplier()
}
private
val visitedSignature: ClassSignatureVisitor? by unsafeLazy {
delegate.signature?.let { signature ->
ClassSignatureVisitor().also { SignatureReader(signature).accept(it) }
}
}
}
@VisibleForTesting
class ApiFunction internal constructor(
val owner: ApiType,
private val delegate: MethodNode,
private val context: ApiTypeProvider.Context
) {
val name: String =
delegate.name
val isPublic: Boolean =
delegate.access.isPublic
val isDeprecated: Boolean
get() = owner.isDeprecated || delegate.visibleAnnotations.has<java.lang.Deprecated>()
val isIncubating: Boolean
get() = owner.isIncubating || delegate.visibleAnnotations.has<Incubating>()
val isStatic: Boolean =
delegate.access.isStatic
val typeParameters: List<ApiTypeUsage> by unsafeLazy {
context.apiTypeParametersFor(visitedSignature)
}
val parameters: List<ApiFunctionParameter> by unsafeLazy {
context.apiFunctionParametersFor(this, delegate, visitedSignature)
}
val returnType: ApiTypeUsage by unsafeLazy {
context.apiTypeUsageForReturnType(delegate, visitedSignature?.returnType)
}
private
val visitedSignature: MethodSignatureVisitor? by unsafeLazy {
delegate.signature?.let { signature ->
MethodSignatureVisitor().also { visitor -> SignatureReader(signature).accept(visitor) }
}
}
}
@VisibleForTesting
data class ApiTypeUsage internal constructor(
val sourceName: String,
val isNullable: Boolean = false,
val type: ApiType? = null,
val variance: Variance = Variance.INVARIANT,
val typeArguments: List<ApiTypeUsage> = emptyList(),
val bounds: List<ApiTypeUsage> = emptyList()
) {
val isRaw: Boolean
get() = typeArguments.isEmpty() && type?.typeParameters?.isEmpty() != false
}
@VisibleForTesting
enum class Variance {
/**
* Represent an invariant type argument.
* e.g. `<T>`
*/
INVARIANT,
/**
* Represent a covariant type argument.
* Also known as "extends-bound" or "upper bound".
* e.g. `<? extends T>`
*/
COVARIANT,
/**
* Represent a contravariant type argument.
* Also known as "super-bound" or "lower bound".
* e.g. `<? super T>`
*/
CONTRAVARIANT
}
@VisibleForTesting
data class ApiFunctionParameter internal constructor(
val index: Int,
val isVarargs: Boolean,
private val nameSupplier: () -> String?,
val type: ApiTypeUsage
) {
val name: String? by unsafeLazy {
nameSupplier()
}
}
private
fun ApiTypeProvider.Context.apiTypeUsageFor(
binaryName: String,
isNullable: Boolean = false,
variance: Variance = Variance.INVARIANT,
typeArguments: List<TypeSignatureVisitor> = emptyList(),
bounds: List<TypeSignatureVisitor> = emptyList()
): ApiTypeUsage =
if (binaryName == "?") starProjectionTypeUsage
else sourceNameOfBinaryName(binaryName).let { sourceName ->
ApiTypeUsage(
sourceName,
isNullable,
type(sourceName),
variance,
typeArguments.map { apiTypeUsageFor(it.binaryName, variance = it.variance, typeArguments = it.typeArguments) },
bounds.map { apiTypeUsageFor(it.binaryName, variance = it.variance, typeArguments = it.typeArguments) })
}
internal
val ApiTypeUsage.isStarProjectionTypeUsage
get() = this === starProjectionTypeUsage
internal
val starProjectionTypeUsage = ApiTypeUsage("*")
internal
val singletonListOfStarProjectionTypeUsage = listOf(starProjectionTypeUsage)
private
fun ApiTypeProvider.Context.apiTypeParametersFor(visitedSignature: BaseSignatureVisitor?): List<ApiTypeUsage> =
visitedSignature?.typeParameters?.map { (binaryName, bounds) -> apiTypeUsageFor(binaryName, bounds = bounds) }
?: emptyList()
private
fun ApiTypeProvider.Context.apiFunctionParametersFor(function: ApiFunction, delegate: MethodNode, visitedSignature: MethodSignatureVisitor?) =
delegate.visibleParameterAnnotations?.map { it.has<Nullable>() }.let { parametersNullability ->
val parameterTypesBinaryNames = visitedSignature?.parameters?.map { if (it.isArray) "${it.typeArguments.single().binaryName}[]" else it.binaryName }
?: Type.getArgumentTypes(delegate.desc).map { it.className }
val names by unsafeLazy {
parameterNamesFor(
function.owner.sourceName,
function.name,
parameterTypesBinaryNames)
}
parameterTypesBinaryNames.mapIndexed { idx, parameterTypeBinaryName ->
val isNullable = parametersNullability?.get(idx) == true
val signatureParameter = visitedSignature?.parameters?.get(idx)
val parameterTypeName = signatureParameter?.binaryName ?: parameterTypeBinaryName
val variance = signatureParameter?.variance ?: Variance.INVARIANT
val typeArguments = signatureParameter?.typeArguments ?: emptyList<TypeSignatureVisitor>()
ApiFunctionParameter(
index = idx,
isVarargs = idx == parameterTypesBinaryNames.lastIndex && delegate.access.isVarargs,
nameSupplier = { names?.get(idx) },
type = apiTypeUsageFor(parameterTypeName, isNullable, variance, typeArguments)
)
}
}
private
fun ApiTypeProvider.Context.apiTypeUsageForReturnType(delegate: MethodNode, returnType: TypeSignatureVisitor?) =
apiTypeUsageFor(
returnType?.binaryName ?: Type.getReturnType(delegate.desc).className,
delegate.visibleAnnotations.has<Nullable>(),
returnType?.variance ?: Variance.INVARIANT,
returnType?.typeArguments ?: emptyList())
private
inline fun <reified AnnotationType : Any> List<AnnotationNode>?.has() =
if (this == null) false
else Type.getDescriptor(AnnotationType::class.java).let { desc -> any { it.desc == desc } }
private
class ApiTypeClassNode : ClassNode(ASM_LEVEL) {
override fun visitSource(file: String?, debug: String?) = Unit
override fun visitOuterClass(owner: String?, name: String?, desc: String?) = Unit
override fun visitTypeAnnotation(typeRef: Int, typePath: TypePath?, desc: String?, visible: Boolean): AnnotationVisitor? = null
override fun visitAttribute(attr: Attribute?) = Unit
override fun visitInnerClass(name: String?, outerName: String?, innerName: String?, access: Int) = Unit
override fun visitField(access: Int, name: String?, desc: String?, signature: String?, value: Any?): FieldVisitor? = null
}
private
abstract class BaseSignatureVisitor : SignatureVisitor(ASM_LEVEL) {
val typeParameters: MutableMap<String, MutableList<TypeSignatureVisitor>> = LinkedHashMap(1)
private
var currentTypeParameter: String? = null
override fun visitFormalTypeParameter(binaryName: String) {
typeParameters[binaryName] = ArrayList(1)
currentTypeParameter = binaryName
}
override fun visitClassBound(): SignatureVisitor =
visitTypeParameterBound()
override fun visitInterfaceBound(): SignatureVisitor =
visitTypeParameterBound()
private
fun visitTypeParameterBound() =
TypeSignatureVisitor().also { typeParameters[currentTypeParameter]!!.add(it) }
}
private
class ClassSignatureVisitor : BaseSignatureVisitor()
private
class MethodSignatureVisitor : BaseSignatureVisitor() {
val parameters: MutableList<TypeSignatureVisitor> = ArrayList(1)
val returnType = TypeSignatureVisitor()
override fun visitParameterType(): SignatureVisitor =
TypeSignatureVisitor().also { parameters.add(it) }
override fun visitReturnType(): SignatureVisitor =
returnType
}
private
class TypeSignatureVisitor(val variance: Variance = Variance.INVARIANT) : SignatureVisitor(ASM_LEVEL) {
var isArray = false
lateinit var binaryName: String
val typeArguments = ArrayList<TypeSignatureVisitor>(1)
private
var expectTypeArgument = false
override fun visitBaseType(descriptor: Char) =
visitBinaryName(binaryNameOfBaseType(descriptor))
override fun visitArrayType(): SignatureVisitor =
TypeSignatureVisitor().also {
visitBinaryName("kotlin.Array")
isArray = true
typeArguments.add(it)
}
override fun visitClassType(internalName: String) =
visitBinaryName(binaryNameOfInternalName(internalName))
override fun visitInnerClassType(localName: String) {
binaryName += "${'$'}$localName"
}
override fun visitTypeArgument() {
typeArguments.add(TypeSignatureVisitor().also { it.binaryName = "?" })
}
override fun visitTypeArgument(wildcard: Char): SignatureVisitor =
TypeSignatureVisitor(boundOf(wildcard)).also {
expectTypeArgument = true
typeArguments.add(it)
}
override fun visitTypeVariable(internalName: String) {
visitBinaryName(binaryNameOfInternalName(internalName))
}
private
fun visitBinaryName(binaryName: String) {
if (expectTypeArgument) {
TypeSignatureVisitor().let {
typeArguments.add(it)
SignatureReader(binaryName).accept(it)
}
expectTypeArgument = false
} else {
this.binaryName = binaryName
}
}
private
fun boundOf(wildcard: Char) =
when (wildcard) {
'+' -> Variance.COVARIANT
'-' -> Variance.CONTRAVARIANT
else -> Variance.INVARIANT
}
}
private
fun binaryNameOfBaseType(descriptor: Char) =
Type.getType(descriptor.toString()).className
private
fun binaryNameOfInternalName(internalName: String): String =
Type.getObjectType(internalName).className
private
fun sourceNameOfBinaryName(binaryName: String): String =
when (binaryName) {
"void" -> "Unit"
"?" -> "*"
in mappedTypeStrings.keys -> mappedTypeStrings[binaryName]!!
in primitiveTypeStrings.keys -> primitiveTypeStrings[binaryName]!!
else -> binaryName.replace('$', '.')
}
/**
* See https://kotlinlang.org/docs/reference/java-interop.html#mapped-types
*/
private
val mappedTypeStrings =
mapOf(
// Built-ins
"java.lang.Cloneable" to "kotlin.Cloneable",
"java.lang.Comparable" to "kotlin.Comparable",
"java.lang.Enum" to "kotlin.Enum",
"java.lang.Annotation" to "kotlin.Annotation",
"java.lang.Deprecated" to "kotlin.Deprecated",
"java.lang.CharSequence" to "kotlin.CharSequence",
"java.lang.Number" to "kotlin.Number",
"java.lang.Throwable" to "kotlin.Throwable",
// Collections
"java.util.Iterable" to "kotlin.collections.Iterable",
"java.util.Iterator" to "kotlin.collections.Iterator",
"java.util.ListIterator" to "kotlin.collections.ListIterator",
"java.util.Collection" to "kotlin.collections.Collection",
"java.util.List" to "kotlin.collections.List",
"java.util.ArrayList" to "kotlin.collections.ArrayList",
"java.util.Set" to "kotlin.collections.Set",
"java.util.HashSet" to "kotlin.collections.HashSet",
"java.util.LinkedHashSet" to "kotlin.collections.LinkedHashSet",
"java.util.Map" to "kotlin.collections.Map",
"java.util.Map.Entry" to "kotlin.collections.Map.Entry",
"java.util.HashMap" to "kotlin.collections.HashMap",
"java.util.LinkedHashMap" to "kotlin.collections.LinkedHashMap")
private
inline val Int.isStatic: Boolean
get() = ACC_STATIC in this
private
inline val Int.isPublic: Boolean
get() = ACC_PUBLIC in this
private
inline val Int.isAbstract: Boolean
get() = ACC_ABSTRACT in this
private
inline val Int.isVarargs: Boolean
get() = ACC_VARARGS in this
private
inline val Int.isSynthetic: Boolean
get() = ACC_SYNTHETIC in this
|
apache-2.0
|
6cab6a2c7c41acabe8e51d4ead3887c6
| 30.992076 | 156 | 0.697627 | 4.618394 | false | false | false | false |
robinverduijn/gradle
|
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/execution/Interpreter.kt
|
1
|
20135
|
/*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl.execution
import org.gradle.api.Project
import org.gradle.api.initialization.Settings
import org.gradle.api.initialization.dsl.ScriptHandler
import org.gradle.api.internal.initialization.ClassLoaderScope
import org.gradle.api.invocation.Gradle
import org.gradle.groovy.scripts.ScriptSource
import org.gradle.internal.classpath.ClassPath
import org.gradle.internal.exceptions.LocationAwareException
import org.gradle.internal.hash.HashCode
import org.gradle.internal.service.ServiceRegistry
import org.gradle.kotlin.dsl.accessors.projectAccessorsClassPath
import org.gradle.kotlin.dsl.support.KotlinScriptHost
import org.gradle.kotlin.dsl.support.ScriptCompilationException
import org.gradle.kotlin.dsl.support.loggerFor
import org.gradle.kotlin.dsl.support.serviceRegistryOf
import org.gradle.kotlin.dsl.support.unsafeLazy
import org.gradle.plugin.management.internal.PluginRequests
import com.google.common.annotations.VisibleForTesting
import java.io.File
import java.lang.reflect.InvocationTargetException
/**
* An optimised interpreter for the Kotlin DSL based on the idea of
* [partial evaluation](https://en.wikipedia.org/wiki/Partial_evaluation).
*
* Instead of interpreting a given Kotlin DSL script directly, the interpreter emits a
* specialized program that captures the optimal execution procedure for the particular
* combination of script structure (does it contain a `buildscript` block? a `plugins` block?
* a script body? etc), target object and context (top-level or not).
*
* The specialized program is then cached via a cheap cache key based on the original,
* unprocessed contents of the script, the target object type and parent `ClassLoader`.
*
* Because each program is specialized to a given script structure, a lot of work is
* avoided. For example, a top-level script containing a `plugins` block but no body
* can be compiled down to a specialized program that instantiates the precompiled
* `plugins` block class directly - without reflection - and does nothing else. The
* same strategy can be used for a **script plugin** (a non top-level script) with a
* body but no `buildscript` block since the classpath is completely determined at
* the time the specialized program is emitted.
*
* @see Program
* @see PartialEvaluator
* @see ResidualProgram
* @see ResidualProgramCompiler
*/
class Interpreter(val host: Host) {
interface Host {
fun cachedClassFor(
programId: ProgramId
): Class<*>?
fun cache(
specializedProgram: Class<*>,
programId: ProgramId
)
fun cachedDirFor(
scriptHost: KotlinScriptHost<*>,
templateId: String,
sourceHash: HashCode,
parentClassLoader: ClassLoader,
accessorsClassPath: ClassPath?,
initializer: (File) -> Unit
): File
fun startCompilerOperation(
description: String
): AutoCloseable
fun compilationClassPathOf(
classLoaderScope: ClassLoaderScope
): ClassPath
/**
* Provides an additional [ClassPath] to be used in the compilation of a top-level [Project] script
* `plugins` block.
*
* The [ClassPath] is assumed not to influence the cache key of the script by itself as it should
* already be implied by [ProgramId.parentClassLoader].
*/
fun pluginAccessorsFor(
scriptHost: KotlinScriptHost<*>
): ClassPath
fun loadClassInChildScopeOf(
classLoaderScope: ClassLoaderScope,
childScopeId: String,
location: File,
className: String,
accessorsClassPath: ClassPath?
): Class<*>
fun applyPluginsTo(
scriptHost: KotlinScriptHost<*>,
pluginRequests: PluginRequests
)
fun applyBasePluginsTo(project: Project)
fun setupEmbeddedKotlinFor(scriptHost: KotlinScriptHost<*>)
fun closeTargetScopeOf(scriptHost: KotlinScriptHost<*>)
fun hashOf(classPath: ClassPath): HashCode
fun runCompileBuildOperation(scriptPath: String, stage: String, action: () -> String): String
val implicitImports: List<String>
fun serviceRegistryFor(programTarget: ProgramTarget, target: Any): ServiceRegistry = when (programTarget) {
ProgramTarget.Project -> serviceRegistryOf(target as Project)
ProgramTarget.Settings -> serviceRegistryOf(target as Settings)
ProgramTarget.Gradle -> serviceRegistryOf(target as Gradle)
}
}
fun eval(
target: Any,
scriptSource: ScriptSource,
sourceHash: HashCode,
scriptHandler: ScriptHandler,
targetScope: ClassLoaderScope,
baseScope: ClassLoaderScope,
topLevelScript: Boolean,
options: EvalOptions = defaultEvalOptions
) {
val programKind =
if (topLevelScript) ProgramKind.TopLevel
else ProgramKind.ScriptPlugin
val programTarget =
programTargetFor(target)
val templateId =
templateIdFor(programTarget, programKind, "stage1")
val parentClassLoader =
baseScope.exportClassLoader
val programId =
ProgramId(templateId, sourceHash, parentClassLoader)
val cachedProgram =
host.cachedClassFor(programId)
val scriptHost =
scriptHostFor(programTarget, target, scriptSource, scriptHandler, targetScope, baseScope)
val programHost =
programHostFor(options)
if (cachedProgram != null) {
programHost.eval(cachedProgram, scriptHost)
return
}
val specializedProgram =
emitSpecializedProgramFor(
scriptHost,
scriptSource,
sourceHash,
templateId,
parentClassLoader,
targetScope,
baseScope,
programKind,
programTarget
)
host.cache(
specializedProgram,
programId
)
programHost.eval(specializedProgram, scriptHost)
}
private
fun programTargetFor(target: Any): ProgramTarget =
when (target) {
is Settings -> ProgramTarget.Settings
is Project -> ProgramTarget.Project
is Gradle -> ProgramTarget.Gradle
else -> throw IllegalArgumentException("Unsupported target: $target")
}
private
fun scriptHostFor(
programTarget: ProgramTarget,
target: Any,
scriptSource: ScriptSource,
scriptHandler: ScriptHandler,
targetScope: ClassLoaderScope,
baseScope: ClassLoaderScope
) =
KotlinScriptHost(
target,
scriptSource,
scriptHandler,
targetScope,
baseScope,
host.serviceRegistryFor(programTarget, target))
private
fun programHostFor(options: EvalOptions) =
if (EvalOption.SkipBody in options) FirstStageOnlyProgramHost() else defaultProgramHost
private
fun emitSpecializedProgramFor(
scriptHost: KotlinScriptHost<Any>,
scriptSource: ScriptSource,
sourceHash: HashCode,
templateId: String,
parentClassLoader: ClassLoader,
targetScope: ClassLoaderScope,
baseScope: ClassLoaderScope,
programKind: ProgramKind,
programTarget: ProgramTarget
): Class<*> {
val pluginAccessorsClassPath by unsafeLazy {
// TODO: consider computing plugin accessors only when there's a plugins block
if (requiresAccessors(programTarget, programKind)) host.pluginAccessorsFor(scriptHost)
else null
}
val scriptPath =
scriptHost.fileName
val cachedDir =
host.cachedDirFor(
scriptHost,
templateId,
sourceHash,
parentClassLoader,
null
) { cachedDir ->
startCompilerOperationFor(scriptSource, templateId).use {
val outputDir =
stage1SubDirOf(cachedDir).apply { mkdir() }
val sourceText =
scriptSource.resource!!.text
val programSource =
ProgramSource(scriptPath, sourceText)
val program =
ProgramParser.parse(programSource, programKind, programTarget)
val residualProgram = program.map { program ->
PartialEvaluator(programKind, programTarget).reduce(program)
}
scriptSource.withLocationAwareExceptionHandling {
ResidualProgramCompiler(
outputDir = outputDir,
classPath = host.compilationClassPathOf(targetScope.parent),
originalSourceHash = sourceHash,
programKind = programKind,
programTarget = programTarget,
implicitImports = host.implicitImports,
logger = interpreterLogger,
compileBuildOperationRunner = host::runCompileBuildOperation,
pluginAccessorsClassPath = pluginAccessorsClassPath ?: ClassPath.EMPTY,
packageName = residualProgram.packageName
).compile(residualProgram.document)
}
}
}
val classesDir =
stage1SubDirOf(cachedDir)
return loadClassInChildScopeOf(
baseScope,
scriptPath,
classesDir,
templateId,
pluginAccessorsClassPath,
scriptSource
)
}
private
fun stage1SubDirOf(cachedDir: File) =
cachedDir.resolve("stage-1")
private
fun loadClassInChildScopeOf(
baseScope: ClassLoaderScope,
scriptPath: String,
classesDir: File,
scriptTemplateId: String,
accessorsClassPath: ClassPath?,
scriptSource: ScriptSource
): Class<*> {
logClassLoadingOf(scriptTemplateId, scriptSource)
return host.loadClassInChildScopeOf(
baseScope,
childScopeId = classLoaderScopeIdFor(scriptPath, scriptTemplateId),
accessorsClassPath = accessorsClassPath,
location = classesDir,
className = "Program"
)
}
private
val defaultProgramHost = ProgramHost()
private
inner class FirstStageOnlyProgramHost : ProgramHost() {
override fun evaluateSecondStageOf(
program: ExecutableProgram.StagedProgram,
scriptHost: KotlinScriptHost<*>,
scriptTemplateId: String,
sourceHash: HashCode,
accessorsClassPath: ClassPath?
) = Unit
}
private
open inner class ProgramHost : ExecutableProgram.Host {
override fun setupEmbeddedKotlinFor(scriptHost: KotlinScriptHost<*>) {
host.setupEmbeddedKotlinFor(scriptHost)
}
override fun applyPluginsTo(scriptHost: KotlinScriptHost<*>, pluginRequests: PluginRequests) {
host.applyPluginsTo(scriptHost, pluginRequests)
}
override fun applyBasePluginsTo(project: Project) {
host.applyBasePluginsTo(project)
}
override fun handleScriptException(
exception: Throwable,
scriptClass: Class<*>,
scriptHost: KotlinScriptHost<*>
) {
locationAwareExceptionHandlingFor(exception, scriptClass, scriptHost.scriptSource)
}
override fun closeTargetScopeOf(scriptHost: KotlinScriptHost<*>) {
host.closeTargetScopeOf(scriptHost)
}
override fun evaluateSecondStageOf(
program: ExecutableProgram.StagedProgram,
scriptHost: KotlinScriptHost<*>,
scriptTemplateId: String,
sourceHash: HashCode,
accessorsClassPath: ClassPath?
) {
val targetScope =
scriptHost.targetScope
val parentClassLoader =
targetScope.exportClassLoader
val classPathHash: HashCode? =
accessorsClassPath?.let { host.hashOf(it) }
val programId =
ProgramId(scriptTemplateId, sourceHash, parentClassLoader, classPathHash)
val cachedProgram =
host.cachedClassFor(programId)
if (cachedProgram != null) {
eval(cachedProgram, scriptHost)
return
}
val specializedProgram =
program.loadSecondStageFor(
this,
scriptHost,
scriptTemplateId,
sourceHash,
accessorsClassPath)
host.cache(
specializedProgram,
programId)
eval(specializedProgram, scriptHost)
}
override fun accessorsClassPathFor(scriptHost: KotlinScriptHost<*>) =
projectAccessorsClassPath(
scriptHost.target as Project,
host.compilationClassPathOf(scriptHost.targetScope)
).bin
override fun compileSecondStageOf(
program: ExecutableProgram.StagedProgram,
scriptHost: KotlinScriptHost<*>,
scriptTemplateId: String,
sourceHash: HashCode,
programKind: ProgramKind,
programTarget: ProgramTarget,
accessorsClassPath: ClassPath?
): Class<*> {
val originalScriptPath =
scriptHost.fileName
val targetScope =
scriptHost.targetScope
val parentClassLoader =
targetScope.exportClassLoader
val scriptSource =
scriptHost.scriptSource
val cacheDir =
host.cachedDirFor(
scriptHost,
scriptTemplateId,
sourceHash,
parentClassLoader,
accessorsClassPath
) { outputDir ->
startCompilerOperationFor(scriptSource, scriptTemplateId).use {
val targetScopeClassPath =
host.compilationClassPathOf(targetScope)
val compilationClassPath =
accessorsClassPath?.let {
targetScopeClassPath + it
} ?: targetScopeClassPath
scriptSource.withLocationAwareExceptionHandling {
withTemporaryScriptFileFor(originalScriptPath, program.secondStageScriptText) { scriptFile ->
ResidualProgramCompiler(
outputDir,
compilationClassPath,
sourceHash,
programKind,
programTarget,
host.implicitImports,
interpreterLogger,
host::runCompileBuildOperation
).emitStage2ProgramFor(
scriptFile,
originalScriptPath
)
}
}
}
}
return loadClassInChildScopeOf(
targetScope,
originalScriptPath,
cacheDir,
scriptTemplateId,
accessorsClassPath,
scriptSource)
}
open fun eval(specializedProgram: Class<*>, scriptHost: KotlinScriptHost<*>) {
withContextClassLoader(specializedProgram.classLoader) {
instantiate(specializedProgram)
.execute(this, scriptHost)
}
}
private
fun instantiate(specializedProgram: Class<*>) =
specializedProgram.getDeclaredConstructor().newInstance() as ExecutableProgram
}
private
fun startCompilerOperationFor(scriptSource: ScriptSource, scriptTemplateId: String): AutoCloseable {
logCompilationOf(scriptTemplateId, scriptSource)
return host.startCompilerOperation(scriptSource.displayName)
}
}
@VisibleForTesting
fun templateIdFor(programTarget: ProgramTarget, programKind: ProgramKind, stage: String): String =
programTarget.name + "/" + programKind.name + "/" + stage
private
fun classLoaderScopeIdFor(scriptPath: String, stage: String) =
"kotlin-dsl:$scriptPath:$stage"
private
fun locationAwareExceptionHandlingFor(e: Throwable, scriptClass: Class<*>, scriptSource: ScriptSource): Nothing {
val targetException = maybeUnwrapInvocationTargetException(e)
val locationAware = locationAwareExceptionFor(targetException, scriptClass, scriptSource)
throw locationAware ?: targetException
}
private
fun locationAwareExceptionFor(
original: Throwable,
scriptClass: Class<*>,
scriptSource: ScriptSource
): LocationAwareException? {
val scriptClassName = scriptClass.name
val scriptClassNameInnerPrefix = "$scriptClassName$"
fun scriptStackTraceElement(element: StackTraceElement) =
element.className?.run {
equals(scriptClassName) || startsWith(scriptClassNameInnerPrefix)
} == true
tailrec fun inferLocationFrom(exception: Throwable): LocationAwareException? {
if (exception is LocationAwareException) {
return exception
}
exception.stackTrace.find(::scriptStackTraceElement)?.run {
return LocationAwareException(original, scriptSource, lineNumber.takeIf { it >= 0 })
}
val cause = exception.cause ?: return null
return inferLocationFrom(cause)
}
return inferLocationFrom(original)
}
private
inline fun <T> ScriptSource.withLocationAwareExceptionHandling(action: () -> T): T =
try {
action()
} catch (e: ScriptCompilationException) {
throw LocationAwareException(e, this, e.firstErrorLine)
}
private
fun maybeUnwrapInvocationTargetException(e: Throwable) =
if (e is InvocationTargetException) e.targetException
else e
private
inline fun withContextClassLoader(classLoader: ClassLoader, block: () -> Unit) {
val currentThread = Thread.currentThread()
val previous = currentThread.contextClassLoader
try {
currentThread.contextClassLoader = classLoader
block()
} finally {
currentThread.contextClassLoader = previous
}
}
private
fun logCompilationOf(templateId: String, source: ScriptSource) {
interpreterLogger.debug("Compiling $templateId from ${source.displayName}")
}
private
fun logClassLoadingOf(templateId: String, source: ScriptSource) {
interpreterLogger.debug("Loading $templateId from ${source.displayName}")
}
internal
val interpreterLogger = loggerFor<Interpreter>()
|
apache-2.0
|
7654d84860681f63f9f8d1c62fd7eb85
| 31.633712 | 121 | 0.614452 | 5.939528 | false | false | false | false |
charbgr/CliffHanger
|
cliffhanger/feature-search/src/main/kotlin/com/github/charbgr/cliffhanger/feature/search/arch/StateReducer.kt
|
1
|
1893
|
package com.github.charbgr.cliffhanger.feature.search.arch
import com.github.charbgr.arch.BaseStateReducer
import com.github.charbgr.cliffhanger.domain.MiniMovie
import com.github.charbgr.cliffhanger.feature.search.arch.PartialChange.Failed
import com.github.charbgr.cliffhanger.feature.search.arch.PartialChange.InProgress
import com.github.charbgr.cliffhanger.feature.search.arch.PartialChange.Initial
import com.github.charbgr.cliffhanger.feature.search.arch.PartialChange.Success
internal class StateReducer : BaseStateReducer<PartialChange, ViewModel>() {
val initial: Pair<PartialChange, ViewModel> by lazy {
Pair(PartialChange.Initial,
ViewModel.Initial())
}
override fun reduceState(
previousPartialChange: PartialChange,
previousViewModel: ViewModel,
partialChange: PartialChange
): ViewModel {
return when (partialChange) {
Initial -> {
ViewModel.Initial()
}
is InProgress -> {
var movies: List<MiniMovie>? = previousViewModel.movies
if (!partialChange.fromInfiniteScroll) {
movies = null
}
previousViewModel.copy(
showError = false,
showLoader = !partialChange.fromInfiniteScroll,
movies = movies
)
}
is Failed -> {
previousViewModel.copy(
showError = true,
throwable = partialChange.throwable,
showLoader = false,
showMovies = false
)
}
is Success -> {
val movies: MutableList<MiniMovie> = previousViewModel.movies?.toMutableList()
?: mutableListOf()
movies.addAll(partialChange.searchResults.movies)
previousViewModel.copy(
showError = false,
throwable = null,
showLoader = false,
showMovies = true,
movies = movies
)
}
}
}
}
|
mit
|
d02c43d122aecc182040f1c0d82c6244
| 29.047619 | 86 | 0.656101 | 4.904145 | false | false | false | false |
sibay/vertx-web
|
vertx-web/src/main/kotlin/io/vertx/kotlin/ext/web/handler/sockjs/BridgeOptions.kt
|
1
|
650
|
package io.vertx.kotlin.ext.web.handler.sockjs
import io.vertx.ext.web.handler.sockjs.BridgeOptions
fun BridgeOptions(
maxAddressLength: Int? = null,
maxHandlersPerSocket: Int? = null,
pingTimeout: Long? = null,
replyTimeout: Long? = null): BridgeOptions = io.vertx.ext.web.handler.sockjs.BridgeOptions().apply {
if (maxAddressLength != null) {
this.maxAddressLength = maxAddressLength
}
if (maxHandlersPerSocket != null) {
this.maxHandlersPerSocket = maxHandlersPerSocket
}
if (pingTimeout != null) {
this.pingTimeout = pingTimeout
}
if (replyTimeout != null) {
this.replyTimeout = replyTimeout
}
}
|
apache-2.0
|
5e40b014ba8b6569ddd02bc62357a2c9
| 22.214286 | 102 | 0.712308 | 3.59116 | false | false | false | false |
jksiezni/xpra-client
|
xpra-client-android/src/main/java/com/github/jksiezni/xpra/config/ServersListFragment.kt
|
1
|
6218
|
/*
* Copyright (C) 2020 Jakub Ksiezniak
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.github.jksiezni.xpra.config
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.*
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.github.jksiezni.xpra.ConnectXpraActivity
import com.github.jksiezni.xpra.R
import com.github.jksiezni.xpra.client.ConnectionEventListener
import com.github.jksiezni.xpra.client.ServiceBinderFragment
import com.github.jksiezni.xpra.connection.ActiveConnectionFragment
import com.github.jksiezni.xpra.databinding.ServersFragmentBinding
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.addTo
import timber.log.Timber
import java.io.IOException
class ServersListFragment : Fragment() {
private val disposables = CompositeDisposable()
private val service by lazy { ServiceBinderFragment.obtain(activity) }
private val adapter = ServerDetailsAdapter()
private var _binding: ServersFragmentBinding? = null
private val binding get() = _binding!!
private val connectionListener = object : ConnectionEventListener {
override fun onConnected(serverDetails: ServerDetails) {
adapter.setConnected(serverDetails, true)
}
override fun onDisconnected(serverDetails: ServerDetails) {
adapter.setConnected(serverDetails, false)
}
override fun onConnectionError(serverDetails: ServerDetails, e: IOException) {
adapter.setConnected(serverDetails, false)
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_binding = ServersFragmentBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
Timber.v("onViewCreated")
val floatingButton = view.findViewById<View>(R.id.floatingButton)
floatingButton.setOnClickListener { newConnection() }
binding.serversList.adapter = adapter
adapter.secondaryAction.subscribe { item ->
if (adapter.isConnected(item)) {
service.whenXpraAvailable { it.disconnect() }
} else {
editConnection(item)
}
}.addTo(disposables)
adapter.primaryAction.subscribe { item ->
when {
adapter.isConnected(item) -> {
openActiveConnection()
}
service.xpraAPI?.isConnected == true -> {
Toast.makeText(requireContext(), R.string.already_connected, Toast.LENGTH_LONG).show()
}
else -> {
Timber.v("User intents to connect with xpra..")
val intent = Intent(context, ConnectXpraActivity::class.java)
intent.putExtra(ConnectXpraActivity.EXTRA_CONNECTION_ID, item.id)
startActivityForResult(intent, RESULT_CONNECTION)
}
}
}.addTo(disposables)
val viewModel = ViewModelProvider(this)[ServerDetailsViewModel::class.java]
updateServersList(viewModel.getAllServers().value)
viewModel.getAllServers().observe(viewLifecycleOwner) { items ->
updateServersList(items)
}
service.whenXpraAvailable { s ->
s.registerConnectionListener(connectionListener)
}
}
override fun onDestroyView() {
super.onDestroyView()
disposables.clear()
service.whenXpraAvailable { s ->
s.unregisterConnectionListener(connectionListener)
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.servers_menu, menu)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RESULT_CONNECTION && resultCode == Activity.RESULT_OK) {
openActiveConnection()
}
}
private fun openActiveConnection() {
parentFragmentManager.beginTransaction()
.replace(id, ActiveConnectionFragment())
.addToBackStack(null)
.commit()
}
private fun updateServersList(list: List<ServerDetails>?) {
adapter.submitList(list)
if (list?.isEmpty() == false) {
binding.emptyView.visibility = View.GONE
} else {
binding.emptyView.visibility = View.VISIBLE
}
adapter.clearConnections()
service.whenXpraAvailable { s ->
s.connectionDetails?.let {
adapter.setConnected(it, s.isConnected)
}
}
}
private fun newConnection() {
parentFragmentManager.beginTransaction()
.replace(id, ServerDetailsFragment.create(ServerDetails()))
.addToBackStack(null)
.commit()
}
private fun editConnection(connection: ServerDetails) {
parentFragmentManager.beginTransaction()
.replace(id, ServerDetailsFragment.create(connection))
.addToBackStack(null)
.commit()
}
companion object {
private const val RESULT_CONNECTION = 1
}
init {
setHasOptionsMenu(true)
}
}
|
gpl-3.0
|
fb7ffc13d74e111b62242095201e3bf3
| 35.582353 | 116 | 0.65616 | 4.907656 | false | false | false | false |
siosio/DomaSupport
|
src/main/java/siosio/doma/sql/ParameterCompletionContributor.kt
|
1
|
4141
|
package siosio.doma.sql
import com.intellij.codeInsight.completion.*
import com.intellij.codeInsight.lookup.*
import com.intellij.patterns.*
import com.intellij.patterns.PlatformPatterns.*
import com.intellij.patterns.StandardPatterns.*
import com.intellij.psi.*
import com.intellij.util.*
import org.jetbrains.kotlin.idea.completion.or
import siosio.doma.*
open class ParameterCompletionContributor : CompletionContributor() {
init {
extend(CompletionType.BASIC,
psiElement(PsiComment::class.java)
.andOr(
psiElement().inFile(psiFile().withName(StandardPatterns.string().endsWith(".sql"))),
psiElement().inFile(psiFile().withName(StandardPatterns.string().endsWith(".java")))
.and(psiElement().withParent(PsiAnnotation::class.java).withText(StandardPatterns.string().startsWith("@Sql")))
),
SqlParameterCompletionProvider())
}
private class SqlParameterCompletionProvider : CompletionProvider<CompletionParameters>() {
private val buildInFunctionLookupList = listOf(
"escape",
"prefix",
"infix",
"suffix",
"roundDownTimePart",
"roundDownTimePart",
"roundDownTimePart",
"roundUpTimePart",
"roundUpTimePart",
"roundUpTimePart",
"isEmpty",
"isNotEmpty",
"isBlank",
"isNotBlank"
).map {
LookupElementBuilder.create(it)
.withAutoCompletionPolicy(AutoCompletionPolicy.ALWAYS_AUTOCOMPLETE)
}
private val percentCommentLookupList = listOf(
"expand",
"if",
"end"
).map {
LookupElementBuilder.create(it)
.withAutoCompletionPolicy(AutoCompletionPolicy.ALWAYS_AUTOCOMPLETE)
}
override fun addCompletions(parameters: CompletionParameters,
p1: ProcessingContext,
result: CompletionResultSet) {
val originalFile = parameters.originalFile
val text = parameters.originalPosition?.text?.let {
val text = it.substringAfter("/*%if")
.substringAfter("/*")
.substringBefore("*/")
.trim()
text
} ?: ""
if (isBuiltInFunction(text)) {
result.addAllElements(buildInFunctionLookupList)
} else if (isPercentComment(text)) {
result.addAllElements(percentCommentLookupList)
} else {
val paramList = toDaoClass(originalFile)
?.findMethodsByName(toMethodName(originalFile), false)
?.firstOrNull()
?.parameterList
?.parameters
if (text.contains("(")) {
val paramText = text.substringAfter("(")
paramList
?.filter {
it.name.startsWith(paramText)
}
?.map(::VariableLookupItem)
?.toList()
?.let { list ->
result.addAllElements(list)
}
} else {
paramList
?.map(::VariableLookupItem)
?.toList()
?.let { list ->
result.addAllElements(list)
}
}
}
result.stopHere()
}
private fun isBuiltInFunction(text: String): Boolean = text.startsWith("@") && !text.contains('(')
private fun isPercentComment(text: String): Boolean = text.startsWith("%")
}
}
|
mit
|
99c73080c2e2692140a8f695936e8868
| 37.700935 | 151 | 0.489012 | 6.3125 | false | false | false | false |
inorichi/tachiyomi
|
app/src/main/java/eu/kanade/tachiyomi/ui/browse/source/browse/SourceItem.kt
|
1
|
3471
|
package eu.kanade.tachiyomi.ui.browse.source.browse
import android.view.Gravity
import android.view.View
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.widget.FrameLayout
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.RecyclerView
import com.tfcporciuncula.flow.Preference
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.davidea.flexibleadapter.items.AbstractFlexibleItem
import eu.davidea.flexibleadapter.items.IFlexible
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.databinding.SourceComfortableGridItemBinding
import eu.kanade.tachiyomi.databinding.SourceCompactGridItemBinding
import eu.kanade.tachiyomi.ui.library.setting.DisplayModeSetting
import eu.kanade.tachiyomi.widget.AutofitRecyclerView
class SourceItem(val manga: Manga, private val displayMode: Preference<DisplayModeSetting>) :
AbstractFlexibleItem<SourceHolder<*>>() {
override fun getLayoutRes(): Int {
return when (displayMode.get()) {
DisplayModeSetting.COMPACT_GRID -> R.layout.source_compact_grid_item
DisplayModeSetting.COMFORTABLE_GRID -> R.layout.source_comfortable_grid_item
DisplayModeSetting.LIST -> R.layout.source_list_item
}
}
override fun createViewHolder(
view: View,
adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>
): SourceHolder<*> {
return when (displayMode.get()) {
DisplayModeSetting.COMPACT_GRID -> {
val binding = SourceCompactGridItemBinding.bind(view)
val parent = adapter.recyclerView as AutofitRecyclerView
val coverHeight = parent.itemWidth / 3 * 4
view.apply {
binding.card.layoutParams = FrameLayout.LayoutParams(
MATCH_PARENT,
coverHeight
)
binding.gradient.layoutParams = FrameLayout.LayoutParams(
MATCH_PARENT,
coverHeight / 2,
Gravity.BOTTOM
)
}
SourceCompactGridHolder(view, adapter)
}
DisplayModeSetting.COMFORTABLE_GRID -> {
val binding = SourceComfortableGridItemBinding.bind(view)
val parent = adapter.recyclerView as AutofitRecyclerView
val coverHeight = parent.itemWidth / 3 * 4
view.apply {
binding.card.layoutParams = ConstraintLayout.LayoutParams(
MATCH_PARENT,
coverHeight
)
}
SourceComfortableGridHolder(view, adapter)
}
DisplayModeSetting.LIST -> {
SourceListHolder(view, adapter)
}
}
}
override fun bindViewHolder(
adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>,
holder: SourceHolder<*>,
position: Int,
payloads: List<Any?>?
) {
holder.onSetValues(manga)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other is SourceItem) {
return manga.id!! == other.manga.id!!
}
return false
}
override fun hashCode(): Int {
return manga.id!!.hashCode()
}
}
|
apache-2.0
|
7b98e5fb36e1a57f5f9e2c0b5cb7d87f
| 37.142857 | 93 | 0.626621 | 5.127031 | false | false | false | false |
JoosungPark/Leaning-Kotlin-Android
|
app/src/main/java/ma/sdop/weatherapp/extensions/ViewExtensions.kt
|
1
|
488
|
package ma.sdop.weatherapp.extensions
import android.content.Context
import android.view.View
import android.widget.TextView
/**
* Created by parkjoosung on 2017. 4. 19..
*/
val View.ctx: Context
get() = context
var TextView.textColor: Int
get() = currentTextColor
set(v) = setTextColor(v)
fun View.slideExit() {
if ( translationY == 0f ) animate().translationY(-height.toFloat())
}
fun View.slideEnter() {
if ( translationY < 0f ) animate().translationY(0f)
}
|
apache-2.0
|
73128854ee8418a42d77f2bdb846329a
| 19.375 | 71 | 0.69877 | 3.485714 | false | false | false | false |
JimSeker/ui
|
Navigation/MenuDemo_kt/app/src/main/java/edu/cs4730/menudemo_kt/FragMenuActivity.kt
|
1
|
2798
|
package edu.cs4730.menudemo_kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.content.Intent
import android.view.Menu
import android.view.MenuItem
import androidx.core.app.NavUtils
/**
* So this activity shows hwo the menu can change based on the fragments
* which is FragMenu1 and FragMenu2 will show extra menu items.
*/
class FragMenuActivity : AppCompatActivity() {
lateinit var one: FragMenu1
lateinit var two: FragMenu2
var isfrag1 = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_fragmenu)
//turn on up button
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
//setup the two fragments, and then add one to screen.
one = FragMenu1()
two = FragMenu2()
supportFragmentManager.beginTransaction()
.add(R.id.text_container, one).commit()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.activity_fragmenu, menu)
if (isfrag1) {
menu.findItem(R.id.frag1).isEnabled = false
menu.findItem(R.id.frag2).isEnabled = true
} else {
menu.findItem(R.id.frag1).isEnabled = true
menu.findItem(R.id.frag2).isEnabled = false
}
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
if (id == android.R.id.home) {
val upIntent = Intent(this, MainActivity::class.java)
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpTo(this, upIntent)
return true
} else if (id == R.id.frag1) {
if (!isfrag1) {
supportFragmentManager.beginTransaction()
.replace(R.id.text_container, one).commit()
isfrag1 = true
supportInvalidateOptionsMenu()
}
return true
} else if (id == R.id.frag2) {
if (isfrag1) {
supportFragmentManager.beginTransaction()
.replace(R.id.text_container, two).commit()
isfrag1 = false
supportInvalidateOptionsMenu()
}
return true
}
return super.onOptionsItemSelected(item)
}
}
|
apache-2.0
|
49e4009c8cb2bb3425c8bfe36d970d0e
| 34.884615 | 86 | 0.613653 | 4.542208 | false | false | false | false |
wenhuiyao/CoroutinesAdapter
|
coroutines-adapter/src/main/kotlin/com/wenhui/coroutines/Action.kt
|
1
|
2101
|
package com.wenhui.coroutines
import kotlinx.coroutines.experimental.CoroutineScope
import kotlinx.coroutines.experimental.runBlocking
internal interface Action<out T> {
/**
* Doing work asynchronously, this will be called from kotlin coroutines
*/
suspend fun runAsync(scope: CoroutineScope): T
/**
* Doing work, block current thread until work is done, then return the result.
* Throw exception if there is any error.
*/
@Throws(Exception::class) fun run(): T
}
/**
* The basic building block for a background work. This can be extended from Java.
*
* Subclass this when there is not coroutine call in action
*/
abstract class BaseAction<out T> : Action<T> {
final override suspend fun runAsync(scope: CoroutineScope): T = run()
}
/**
* Subclass this when there is coroutine call in the action
*/
internal abstract class BaseSuspendableAction<out T> : Action<T> {
/**
* run the action interrupt synchronously, and return the result, throw exception if there is error
*
* @throws [ExecutionException]
* @throws [CancellationException]
*/
final override fun run(): T {
var result: T? = null
var exception: Throwable = CancellationException()
runBlocking { // blocking current thread util have the result
try {
result = runAsync(this)
} catch(e: Throwable) {
if (e is kotlinx.coroutines.experimental.CancellationException) {
exception = CancellationException()
} else {
exception = e
}
}
}
return result ?: throw exception
}
}
/**
* Discontinue current execution by throwing [IgnoreException]
*/
internal fun discontinueExecution(): Nothing = throw IgnoreException()
internal fun shouldReportException(exception: Throwable): Boolean = exception !is IgnoreException
/**
* Exception indicates the operation should be ignored
*/
internal class IgnoreException(message: String = "Ignore the execution") : Exception(message)
|
apache-2.0
|
34b7a6acc99116bb1dc4cca5936bcd2a
| 29.463768 | 103 | 0.663018 | 4.897436 | false | false | false | false |
pnemonic78/RemoveDuplicates
|
duplicates-android/app/src/main/java/com/github/duplicates/contact/ContactComparator.kt
|
1
|
7846
|
/*
* Copyright 2016, Moshe Waisberg
*
* 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.github.duplicates.contact
import android.telephony.PhoneNumberUtils
import android.text.TextUtils
import com.github.duplicates.DuplicateComparator
import java.util.*
/**
* Compare duplicate contacts.
*
* @author moshe.w
*/
class ContactComparator : DuplicateComparator<ContactItem>() {
override fun compare(lhs: ContactItem, rhs: ContactItem): Int {
var c: Int
c = compareData(lhs.emails, rhs.emails)
if (c != SAME) return c
c = compareData(lhs.events, rhs.events)
if (c != SAME) return c
c = compareData(lhs.ims, rhs.ims)
if (c != SAME) return c
c = compareData(lhs.names, rhs.names)
if (c != SAME) return c
c = compareData(lhs.phones, rhs.phones)
return if (c != SAME) c else super.compare(lhs, rhs)
}
override fun difference(lhs: ContactItem, rhs: ContactItem): BooleanArray {
val result = BooleanArray(5)
result[EMAIL] = isDifferentData(lhs.emails, rhs.emails)
result[EVENT] = isDifferentData(lhs.events, rhs.events)
result[IM] = isDifferentData(lhs.ims, rhs.ims)
result[NAME] = isDifferent(lhs.displayName, rhs.displayName)
result[PHONE] = isDifferentData(lhs.phones, rhs.phones)
return result
}
override fun match(lhs: ContactItem, rhs: ContactItem, difference: BooleanArray?): Float {
val different = difference ?: difference(lhs, rhs)
var match = MATCH_SAME
if (different[EMAIL]) {
match *= matchEmails(lhs.emails, rhs.emails)
}
if (different[EVENT]) {
match *= matchEvents(lhs.events, rhs.events)
}
if (different[IM]) {
match *= matchIms(lhs.ims, rhs.ims)
}
if (different[NAME]) {
match *= matchNames(lhs.names, rhs.names)
}
if (different[PHONE]) {
match *= matchPhones(lhs.phones, rhs.phones)
}
return match
}
fun compareData(lhs: Collection<ContactData>, rhs: Collection<ContactData>): Int {
if (lhs.isEmpty()) {
return if (rhs.isEmpty()) SAME else RHS
}
if (rhs.isEmpty()) {
return LHS
}
val set1 = HashSet<String>(lhs.size)
for (datum in lhs) {
set1.add(datum.toString().toLowerCase(locale))
}
val set2 = HashSet<String>(rhs.size)
for (datum in rhs) {
set2.add(datum.toString().toLowerCase(locale))
}
return compare(set1, set2)
}
fun isDifferentData(lhs: Collection<ContactData>, rhs: Collection<ContactData>): Boolean {
return compareData(lhs, rhs) != SAME
}
protected fun matchEmails(lhs: Collection<EmailData>, rhs: Collection<EmailData>): Float {
if (lhs.isEmpty()) {
return if (rhs.isEmpty()) MATCH_SAME else MATCH_DATA
}
if (rhs.isEmpty()) {
return MATCH_DATA
}
var s1: String?
for (d1 in lhs) {
s1 = d1.address
for (d2 in rhs) {
if (compareIgnoreCase(s1, d2.address) == SAME) {
return MATCH_SAME
}
}
}
return MATCH_DATA
}
protected fun matchEvents(lhs: Collection<EventData>, rhs: Collection<EventData>): Float {
if (lhs.isEmpty()) {
return if (rhs.isEmpty()) MATCH_SAME else MATCH_DATA
}
if (rhs.isEmpty()) {
return MATCH_DATA
}
var s1: String?
var t1: Int
for (d1 in lhs) {
s1 = d1.startDate
t1 = d1.type
for (d2 in rhs) {
if (compare(s1, d2.startDate) == SAME && compare(t1, d2.type) == SAME) {
return MATCH_SAME
}
}
}
return MATCH_DATA
}
protected fun matchIms(lhs: Collection<ImData>, rhs: Collection<ImData>): Float {
if (lhs.isEmpty()) {
return if (rhs.isEmpty()) MATCH_SAME else MATCH_DATA
}
if (rhs.isEmpty()) {
return MATCH_DATA
}
var s1: String?
for (d1 in lhs) {
s1 = d1.data
for (d2 in rhs) {
if (compareIgnoreCase(s1, d2.data) == SAME) {
return MATCH_SAME
}
}
}
return MATCH_DATA
}
protected fun matchNames(
lhs: Collection<StructuredNameData>,
rhs: Collection<StructuredNameData>
): Float {
if (lhs.isEmpty() || rhs.isEmpty()) {
return MATCH_NAME
}
var s1: String?
var g1: String?
var m1: String?
var f1: String?
var g2: String?
var m2: String?
var f2: String?
var g1Empty: Boolean
var f1Empty: Boolean
var g2Empty: Boolean
var f2Empty: Boolean
for (d1 in lhs) {
s1 = d1.displayName
g1 = d1.givenName
g1Empty = TextUtils.isEmpty(g1)
m1 = d1.middleName
if (g1Empty) {
g1 = m1
g1Empty = TextUtils.isEmpty(g1)
}
f1 = d1.familyName
f1Empty = TextUtils.isEmpty(f1)
for (d2 in rhs) {
if (compareIgnoreCase(s1, d2.displayName) == SAME) {
return MATCH_SAME
}
g2 = d2.givenName
g2Empty = TextUtils.isEmpty(g2)
m2 = d2.middleName
if (g2Empty) {
g2 = m2
g2Empty = TextUtils.isEmpty(g2)
}
f2 = d2.familyName
f2Empty = TextUtils.isEmpty(f2)
// if (g1 = g2 and f1 = f2) or (g1 = g2 and either f1 is empty or f2 is empty) or (f1 = f2 and either g1 is empty or g2 is empty)
if (compareIgnoreCase(g1, g2) == SAME) {
if (compareIgnoreCase(f1, f2) == SAME) {
return MATCH_SAME
}
if (f1Empty || f2Empty) {
return MATCH_SAME
}
} else if (compareIgnoreCase(f1, f2) == SAME) {
if (g1Empty || g2Empty) {
return MATCH_SAME
}
}
}
}
return MATCH_NAME
}
protected fun matchPhones(lhs: Collection<PhoneData>, rhs: Collection<PhoneData>): Float {
if (lhs.isEmpty()) {
return if (rhs.isEmpty()) MATCH_SAME else MATCH_DATA
}
if (rhs.isEmpty()) {
return MATCH_DATA
}
var s1: String?
for (d1 in lhs) {
s1 = d1.number
for (d2 in rhs) {
if (PhoneNumberUtils.compare(s1, d2.number)) {
return MATCH_SAME
}
}
}
return MATCH_DATA
}
companion object {
const val EMAIL = 0
const val EVENT = 1
const val IM = 2
const val NAME = 3
const val PHONE = 4
private const val MATCH_DATA = 0.85f
private const val MATCH_NAME = 0.8f
}
}
|
apache-2.0
|
2b078b11947feeac44407967b357785b
| 30.258964 | 145 | 0.524344 | 4.105704 | false | false | false | false |
asarkar/spring
|
license-report-kotlin/src/main/kotlin/org/abhijitsarkar/ExcelReportGenerator.kt
|
1
|
6274
|
package org.abhijitsarkar
import org.apache.poi.common.usermodel.HyperlinkType
import org.apache.poi.ss.usermodel.Cell
import org.apache.poi.ss.usermodel.CellStyle
import org.apache.poi.ss.usermodel.Font
import org.apache.poi.ss.usermodel.IndexedColors
import org.apache.poi.ss.usermodel.IndexedColors.RED
import org.apache.poi.ss.usermodel.Row
import org.apache.poi.ss.usermodel.Sheet
import org.apache.poi.ss.usermodel.VerticalAlignment.CENTER
import org.apache.poi.ss.usermodel.VerticalAlignment.TOP
import org.apache.poi.ss.usermodel.Workbook
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import org.slf4j.LoggerFactory
import org.springframework.context.event.EventListener
import java.io.File
import java.io.FileOutputStream
/**
* @author Abhijit Sarkar
*/
class ExcelReportGenerator {
private val headers = arrayOf("License", "License URL", "License URL Status", "Components")
private val licenseReport = "License Report.xlsx"
private val log = LoggerFactory.getLogger(ExcelReportGenerator::class.java)
@EventListener(LicenseGeneratedEvent::class)
fun generateReport(event: LicenseGeneratedEvent): Unit {
log.info("Received LicenseGeneratedEvent.")
val licenses = event.licenses
val workbook = XSSFWorkbook()
val regularCs = newCellStyle(workbook, ColumnFormatting.REGULAR)
val hyperlinkCs = newCellStyle(workbook, ColumnFormatting.HYPERLINK)
val warnCs = newCellStyle(workbook, ColumnFormatting.WARN)
val createHelper = workbook.creationHelper
val headerCs = newCellStyle(workbook, ColumnFormatting.HEADER)
licenses
.forEach { name, license ->
var rowNum = 0
val sheet = workbook.createSheet("$name")
sheet.createRow(rowNum++).let { row ->
(0..headers.size - 1).forEach { col ->
newFormattedCell(sheet, row, headerCs, col)
.setCellValue(headers[col])
}
}
license.forEach { (name, url, components, valid) ->
val row = sheet.createRow(rowNum++).apply {
heightInPoints *= components.size
}
newFormattedCell(sheet, row, regularCs, 0).apply {
setCellValue(name)
}
if (url.isNotEmpty()) {
val link = createHelper.createHyperlink(HyperlinkType.URL).apply {
address = url
}
newFormattedCell(sheet, row, hyperlinkCs, 1).apply {
hyperlink = link
setCellValue(url)
}
}
newFormattedCell(sheet, row, regularCs, 3).apply {
val comp = components.joinToString(System.getProperty("line.separator"))
setCellValue(comp)
}
val cell = newFormattedCell(sheet, row, regularCs, 2)
if (valid) {
cell.setCellValue("Valid")
} else {
log.warn("License link: {} is absent or broken, project: {}.", url, name)
(row.firstCellNum..row.lastCellNum - 1)
.map { row.getCell(it) }
.forEach { it?.setCellStyle(warnCs) }
cell.setCellValue("Invalid")
}
}
}
if (workbook.numberOfSheets == 0) {
log.warn("No license files found; skipping report generation.")
} else {
workbook.use {
val reports = File("build", "reports")
if (reports.exists() && reports.deleteRecursively() || !reports.exists()) {
if (reports.mkdirs()) {
val licenseReport = File(reports, licenseReport)
FileOutputStream(licenseReport).use {
workbook.write(it)
}
log.info("Generated license report at: {}.", licenseReport.absolutePath)
} else {
log.warn("Failed to create reports directory.")
}
} else {
log.warn("Failed to delete reports directory.")
}
}
}
}
private fun newCellStyle(workbook: Workbook, colFormatting: ColumnFormatting): CellStyle {
val cs = workbook.createCellStyle().apply { wrapText = true }
return when (colFormatting) {
ColumnFormatting.HEADER -> {
val headerFont = workbook.createFont().apply {
bold = true
}
cs.apply {
setFont(headerFont)
setVerticalAlignment(CENTER)
}
}
ColumnFormatting.HYPERLINK -> {
val hyperlinkFont = workbook.createFont().apply {
underline = Font.U_SINGLE
color = IndexedColors.BLUE.index
}
cs.apply {
setFont(hyperlinkFont)
setVerticalAlignment(TOP)
}
}
ColumnFormatting.WARN -> {
val warnFont = workbook.createFont().apply {
color = RED.getIndex()
}
cs.apply {
setFont(warnFont)
setVerticalAlignment(TOP)
}
}
else -> cs.apply { setVerticalAlignment(TOP) }
}
}
private fun newFormattedCell(sheet: Sheet, r: Row, cs: CellStyle, colNum: Int): Cell {
sheet.autoSizeColumn(colNum)
return r.createCell(colNum).apply { cellStyle = cs }
}
private enum class ColumnFormatting {
REGULAR, HEADER, HYPERLINK, WARN
}
}
|
gpl-3.0
|
52ecdacf643290399fff851e1e9d88e7
| 37.030303 | 101 | 0.514823 | 5.159539 | false | false | false | false |
b95505017/android-architecture-components
|
PagingWithNetworkSample/app/src/main/java/com/android/example/paging/pagingwithnetwork/reddit/api/RedditApi.kt
|
1
|
2936
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.example.paging.pagingwithnetwork.reddit.api
import android.util.Log
import com.android.example.paging.pagingwithnetwork.reddit.vo.RedditPost
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
/**
* API communication setup
*/
interface RedditApi {
@GET("/r/{subreddit}/hot.json")
fun getTop(
@Path("subreddit") subreddit: String,
@Query("limit") limit: Int): Call<ListingResponse>
// for after/before param, either get from RedditDataResponse.after/before,
// or pass RedditNewsDataResponse.name (though this is technically incorrect)
@GET("/r/{subreddit}/hot.json")
fun getTopAfter(
@Path("subreddit") subreddit: String,
@Query("after") after: String,
@Query("limit") limit: Int): Call<ListingResponse>
@GET("/r/{subreddit}/hot.json")
fun getTopBefore(
@Path("subreddit") subreddit: String,
@Query("before") before: String,
@Query("limit") limit: Int): Call<ListingResponse>
class ListingResponse(val data: ListingData)
class ListingData(
val children: List<RedditChildrenResponse>,
val after: String?,
val before: String?
)
data class RedditChildrenResponse(val data: RedditPost)
companion object {
private const val BASE_URL = "https://www.reddit.com/"
fun create(): RedditApi = create(HttpUrl.parse(BASE_URL)!!)
fun create(httpUrl: HttpUrl): RedditApi {
val logger = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger {
Log.d("API", it)
})
logger.level = HttpLoggingInterceptor.Level.BODY
val client = OkHttpClient.Builder()
.addInterceptor(logger)
.build()
return Retrofit.Builder()
.baseUrl(httpUrl)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(RedditApi::class.java)
}
}
}
|
apache-2.0
|
30462e9ad302b280ea176916990d65d4
| 33.964286 | 81 | 0.655654 | 4.5875 | false | false | false | false |
FarbodSalamat-Zadeh/TimetableApp
|
app/src/main/java/co/timetableapp/ui/components/TimeSelectorHelper.kt
|
1
|
3420
|
/*
* Copyright 2017 Farbod Salamat-Zadeh
*
* 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 co.timetableapp.ui.components
import android.app.Activity
import android.app.TimePickerDialog
import android.support.annotation.IdRes
import android.support.annotation.StringRes
import android.support.v4.content.ContextCompat
import android.widget.TextView
import android.widget.TimePicker
import co.timetableapp.R
import co.timetableapp.util.DateUtils
import org.threeten.bp.LocalTime
/**
* A helper class for setting up a [TextView] to show and change the time.
*/
class TimeSelectorHelper(private val activity: Activity, @IdRes private val textViewResId: Int) {
private val mTextView = activity.findViewById(textViewResId) as TextView
private var mTime: LocalTime? = null
/**
* Sets up this helper class, displaying the date and preparing actions for when the
* [TextView] is clicked.
*
* @param initialTime the time to initially display on the [TextView]. This can be null, in
* which case a hint text will be initially displayed.
* @param onTimeSet a function to be invoked when the time has been changed
*/
fun setup(initialTime: LocalTime?,
onTimeSet: (view: TimePicker, time: LocalTime) -> Unit) {
mTime = initialTime
updateTimeText()
setupOnClick(onTimeSet)
}
private fun setupOnClick(onTimeSet: (TimePicker, LocalTime) -> Unit) = mTextView.setOnClickListener {
val listener = TimePickerDialog.OnTimeSetListener { view, hourOfDay, minute ->
onTimeSet.invoke(view, LocalTime.of(hourOfDay, minute))
}
val displayedTime = mTime ?: LocalTime.of(9, 0)
TimePickerDialog(
activity,
listener,
displayedTime.hour,
displayedTime.minute,
true
).show()
}
/**
* Updates the displayed text according to the [time].
*
* @param time used to update the displayed text. This can be null, in which case a
* 'hint' text is shown.
* @param hintTextRes the string resource used to display the hint text
*/
@JvmOverloads
fun updateTime(time: LocalTime?, @StringRes hintTextRes: Int = R.string.property_time) {
mTime = time
updateTimeText(hintTextRes)
}
private fun updateTimeText(@StringRes hintTextRes: Int = R.string.property_time) {
val time = mTime
if (time == null) {
mTextView.text = activity.getString(hintTextRes)
mTextView.setTextColor(ContextCompat.getColor(activity, R.color.mdu_text_black_secondary))
} else {
mTextView.text = time.format(DateUtils.FORMATTER_TIME)
mTextView.setTextColor(ContextCompat.getColor(activity, R.color.mdu_text_black))
}
}
}
|
apache-2.0
|
3da9955f93dd17e985aa21e8468989e3
| 34.625 | 105 | 0.672222 | 4.535809 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android
|
example/src/main/java/org/wordpress/android/fluxc/example/ui/StoreSelectingFragment.kt
|
2
|
1815
|
package org.wordpress.android.fluxc.example.ui
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.LinearLayout
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_woo_products.*
import org.wordpress.android.fluxc.example.R
import org.wordpress.android.fluxc.example.ui.common.showStoreSelectorDialog
import org.wordpress.android.fluxc.example.utils.toggleSiteDependentButtons
import org.wordpress.android.fluxc.model.SiteModel
abstract class StoreSelectingFragment : DaggerFragment() {
protected var selectedPos: Int = -1
protected var selectedSite: SiteModel? = null
open fun onSiteSelected(site: SiteModel) {}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<LinearLayout>(R.id.buttonContainer).addView(
Button(context).apply {
text = "Select Site"
setOnClickListener {
showStoreSelectorDialog(selectedPos, object : StoreSelectorDialog.Listener {
override fun onSiteSelected(site: SiteModel, pos: Int) {
onSiteSelected(site)
selectedSite = site
selectedPos = pos
buttonContainer.toggleSiteDependentButtons(true)
text = site.name ?: site.displayName
}
})
}
},
0
)
if (selectedSite != null) {
buttonContainer.toggleSiteDependentButtons(true)
onSiteSelected(selectedSite!!)
}
}
}
|
gpl-2.0
|
c98e4c4bc47a72e420ae2108e542e33f
| 39.333333 | 100 | 0.614325 | 5.385757 | false | false | false | false |
SixCan/SixDaily
|
app/src/main/java/ca/six/daily/view/RvViewHolder.kt
|
1
|
1434
|
package ca.six.daily.view
import android.support.v4.util.SparseArrayCompat
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
class RvViewHolder private constructor(private val convertView: View) : RecyclerView.ViewHolder(convertView) {
private val views: SparseArrayCompat<View>
init {
views = SparseArrayCompat<View>()
}
fun <T : View> getView(id: Int): T {
var view: View? = views.get(id)
if (view == null) {
view = convertView.findViewById(id)
views.put(id, view)
}
return view as T
}
// ============================================
fun setText(id: Int, str: String) {
val tv = getView<TextView>(id)
tv.text = str
}
fun setSrc(id: Int, drawId: Int) {
val iv = getView<ImageView>(id)
iv.setImageResource(drawId)
}
fun setBackground(id: Int, bgResId: Int) {
val view = getView<View>(id)
view.setBackgroundResource(bgResId)
}
companion object {
fun createViewHolder(parent: ViewGroup, layoutId: Int): RvViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(layoutId, parent, false)
val holder = RvViewHolder(itemView)
return holder
}
}
}
|
mpl-2.0
|
5c00ea03814eed0292a89f787dfae9d4
| 26.596154 | 110 | 0.622734 | 4.306306 | false | false | false | false |
SimonVT/cathode
|
cathode/src/main/java/net/simonvt/cathode/ui/movie/MovieHistoryViewModel.kt
|
1
|
1767
|
/*
* Copyright (C) 2018 Simon Vig Therkildsen
*
* 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 net.simonvt.cathode.ui.movie
import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import net.simonvt.cathode.api.service.SyncService
import net.simonvt.cathode.common.data.MappedCursorLiveData
import net.simonvt.cathode.entity.Movie
import net.simonvt.cathode.entitymapper.MovieMapper
import net.simonvt.cathode.provider.ProviderSchematic.Movies
import net.simonvt.cathode.provider.helper.MovieDatabaseHelper
import javax.inject.Inject
class MovieHistoryViewModel @Inject constructor(
private val context: Context,
private val syncService: SyncService,
private val movieHelper: MovieDatabaseHelper
) : ViewModel() {
private var movieId = -1L
var movie: LiveData<Movie>? = null
private set
var history: MovieHistoryLiveData? = null
private set
fun setMovieId(movieId: Long) {
if (this.movieId == -1L) {
this.movieId = movieId
movie = MappedCursorLiveData(
context,
Movies.withId(movieId),
MovieMapper.projection,
mapper = MovieMapper
)
history = MovieHistoryLiveData(movieId, syncService, movieHelper)
}
}
}
|
apache-2.0
|
b07bb3c13482e8d05d4f0281fccfc24d
| 30.553571 | 75 | 0.751556 | 4.288835 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA
|
src/nl/hannahsten/texifyidea/run/linuxpdfviewer/InternalPdfViewer.kt
|
1
|
3004
|
package nl.hannahsten.texifyidea.run.linuxpdfviewer
import com.intellij.openapi.util.SystemInfo
import nl.hannahsten.texifyidea.run.linuxpdfviewer.evince.EvinceConversation
import nl.hannahsten.texifyidea.run.linuxpdfviewer.okular.OkularConversation
import nl.hannahsten.texifyidea.run.linuxpdfviewer.skim.SkimConversation
import nl.hannahsten.texifyidea.run.linuxpdfviewer.zathura.ZathuraConversation
import nl.hannahsten.texifyidea.run.pdfviewer.PdfViewer
import nl.hannahsten.texifyidea.run.sumatra.SumatraConversation
import nl.hannahsten.texifyidea.run.sumatra.isSumatraAvailable
import nl.hannahsten.texifyidea.util.runCommand
/**
* List of supported PDF viewers on Linux.
*
* These pdf viewers have their support built-in in TeXiFy.
* @param viewerCommand The command to call the viewer from the command line.
* @param conversation The conversation class needed/used to talk to this viewer.
*/
enum class InternalPdfViewer(
private val viewerCommand: String,
override val displayName: String,
val conversation: ViewerConversation?
) : PdfViewer {
EVINCE("evince", "Evince", EvinceConversation),
OKULAR("okular", "Okular", OkularConversation),
ZATHURA("zathura", "Zathura", ZathuraConversation),
SKIM("skim", "Skim", SkimConversation),
SUMATRA("sumatra", "Sumatra", SumatraConversation()),
NONE("", "No PDF viewer", null);
override fun isAvailable(): Boolean = availability[this] ?: false
/**
* Check if the viewer is installed and available from the path.
*/
fun checkAvailability(): Boolean {
// Using no PDF viewer should always be an option.
return if (this == NONE) {
true
}
else if (SystemInfo.isWindows && this == SUMATRA) {
isSumatraAvailable
}
// Only support Evince and Okular on Linux, although they can be installed on other systems like Mac.
else if (SystemInfo.isLinux) {
// Find out whether the pdf viewer is installed and in PATH, otherwise we can't use it.
val output = "which ${this.viewerCommand}".runCommand()
output?.contains("/${this.viewerCommand}") ?: false
}
else if (SystemInfo.isMac) {
// Check if Skim is installed in applications, otherwise we can't use it.
// Open -Ra returns an error message if application was not found, else empty string
val output = "open -Ra ${this.viewerCommand}".runCommand()
output?.isEmpty() ?: false
}
else {
false
}
}
override fun toString(): String = displayName
companion object {
private val availability: Map<InternalPdfViewer, Boolean> by lazy {
values().associateWith {
it.checkAvailability()
}
}
fun availableSubset(): List<InternalPdfViewer> = values().filter { it.isAvailable() }
fun firstAvailable(): InternalPdfViewer = availableSubset().first()
}
}
|
mit
|
7ee1bc61a981037b4d939f72fdeee97a
| 38.012987 | 109 | 0.682091 | 4.334776 | false | false | false | false |
FHannes/intellij-community
|
platform/testGuiFramework/src/com/intellij/testGuiFramework/generators/Generators.kt
|
1
|
28676
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.generators
import com.intellij.framework.PresentableVersion
import com.intellij.ide.plugins.PluginTable
import com.intellij.ide.projectView.impl.ProjectViewTree
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.actionSystem.impl.ActionMenu
import com.intellij.openapi.actionSystem.impl.ActionMenuItem
import com.intellij.openapi.editor.impl.EditorComponentImpl
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.JBPopupMenu
import com.intellij.openapi.ui.LabeledComponent
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.wm.impl.IdeFrameImpl
import com.intellij.openapi.wm.impl.ToolWindowImpl
import com.intellij.openapi.wm.impl.ToolWindowManagerImpl
import com.intellij.openapi.wm.impl.WindowManagerImpl
import com.intellij.openapi.wm.impl.welcomeScreen.FlatWelcomeFrame
import com.intellij.platform.ProjectTemplate
import com.intellij.testGuiFramework.fixtures.MessageDialogFixture
import com.intellij.testGuiFramework.fixtures.MessagesFixture
import com.intellij.testGuiFramework.fixtures.SettingsTreeFixture
import com.intellij.testGuiFramework.framework.GuiTestUtil
import com.intellij.testGuiFramework.generators.Utils.clicks
import com.intellij.testGuiFramework.generators.Utils.convertSimpleTreeItemToPath
import com.intellij.testGuiFramework.generators.Utils.getBoundedLabel
import com.intellij.testGuiFramework.generators.Utils.getCellText
import com.intellij.testGuiFramework.generators.Utils.getJTreePath
import com.intellij.testGuiFramework.generators.Utils.getJTreePathItemsString
import com.intellij.ui.CheckboxTree
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.JBList
import com.intellij.ui.components.labels.ActionLink
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.ui.messages.SheetController
import com.intellij.ui.popup.PopupFactoryImpl
import com.intellij.ui.treeStructure.SimpleTree
import com.intellij.util.ui.tree.TreeUtil
import org.fest.reflect.core.Reflection.field
import org.fest.swing.core.BasicRobot
import org.fest.swing.core.ComponentMatcher
import org.fest.swing.core.GenericTypeMatcher
import org.fest.swing.exception.ComponentLookupException
import java.awt.Component
import java.awt.Container
import java.awt.Point
import java.awt.event.MouseEvent
import java.io.File
import java.net.URI
import java.nio.file.Paths
import java.util.*
import java.util.jar.JarFile
import javax.swing.*
import javax.swing.plaf.basic.BasicArrowButton
import javax.swing.tree.TreeNode
import javax.swing.tree.TreePath
/**
* @author Sergey Karashevich
*/
//**********COMPONENT GENERATORS**********
private val leftButton = MouseEvent.BUTTON1
private val rightButton = MouseEvent.BUTTON3
private fun MouseEvent.isLeftButton() = (this.button == leftButton)
private fun MouseEvent.isRightButton() = (this.button == rightButton)
class JButtonGenerator : ComponentCodeGenerator<JButton> {
override fun accept(cmp: Component) = cmp is JButton
override fun generate(cmp: JButton, me: MouseEvent, cp: Point) = "button(\"${cmp.text}\").click()"
}
class ActionButtonGenerator : ComponentCodeGenerator<ActionButton> {
override fun accept(cmp: Component) = cmp is ActionButton
override fun generate(cmp: ActionButton, me: MouseEvent, cp: Point) = "actionButton(\"${cmp.action.templatePresentation.text}\").click()"
}
class ActionLinkGenerator : ComponentCodeGenerator<ActionLink> {
override fun priority(): Int = 1
override fun accept(cmp: Component) = cmp is ActionLink
override fun generate(cmp: ActionLink, me: MouseEvent, cp: Point) = "actionLink(\"${cmp.text}\").click()"
}
class JTextFieldGenerator : ComponentCodeGenerator<JTextField> {
override fun accept(cmp: Component) = cmp is JTextField
override fun generate(cmp: JTextField, me: MouseEvent, cp: Point) = "textfield(\"${getBoundedLabel(3, cmp).text.orEmpty()}\").${clicks(
me)}"
}
class JBListGenerator : ComponentCodeGenerator<JBList<*>> {
override fun priority() = 1
override fun accept(cmp: Component) = cmp is JBList<*>
private fun JBList<*>.isPopupList() = this.javaClass.name.toLowerCase().contains("listpopup")
private fun JBList<*>.isFrameworksTree() = this.javaClass.name.toLowerCase().contains("AddSupportForFrameworksPanel".toLowerCase())
override fun generate(cmp: JBList<*>, me: MouseEvent, cp: Point): String {
val cellText = getCellText(cmp, cp).orEmpty()
if (cmp.isPopupList()) return "popupClick(\"$cellText\")"
if (me.button == MouseEvent.BUTTON2) return "jList(\"$cellText\").item(\"$cellText\").rightClick()"
return "jList(\"$cellText\").clickItem(\"$cellText\")"
}
}
class BasicComboPopupGenerator : ComponentCodeGenerator<JList<*>> {
override fun accept(cmp: Component) = cmp is JList<*> && cmp.javaClass.name.contains("BasicComboPopup")
override fun generate(cmp: JList<*>, me: MouseEvent, cp: Point): String {
val cellText = getCellText(cmp, cp).orEmpty()
return ".selectItem(\"$cellText\")" // check that combobox is open
}
}
class CheckboxTreeGenerator : ComponentCodeGenerator<CheckboxTree> {
override fun accept(cmp: Component) = cmp is CheckboxTree
override fun generate(cmp: CheckboxTree, me: MouseEvent, cp: Point) = "selectFramework(\"${cmp.getClosestPathForLocation(cp.x,
cp.y).lastPathComponent}\")"
}
class SimpleTreeGenerator : ComponentCodeGenerator<SimpleTree> {
override fun accept(cmp: Component) = cmp is SimpleTree
private fun SimpleTree.getPath(cp: Point) = convertSimpleTreeItemToPath(this, this.getDeepestRendererComponentAt(cp.x, cp.y).toString())
override fun generate(cmp: SimpleTree, me: MouseEvent, cp: Point): String {
val path = cmp.getPath(cp)
if (me.isRightButton()) return "jTree(\"$path\").rightClickPath(\"$path\")"
return "jTree(\"$path\").selectPath(\"$path\")"
}
}
class JBCheckBoxGenerator : ComponentCodeGenerator<JBCheckBox> {
override fun priority() = 1
override fun accept(cmp: Component) = cmp is JBCheckBox
override fun generate(cmp: JBCheckBox, me: MouseEvent, cp: Point) = "checkbox(\"${cmp.text}\").click()"
}
class JCheckBoxGenerator : ComponentCodeGenerator<JCheckBox> {
override fun accept(cmp: Component) = cmp is JCheckBox
override fun generate(cmp: JCheckBox, me: MouseEvent, cp: Point) = "checkbox(\"${cmp.text}\").click()"
}
class JComboBoxGenerator : ComponentCodeGenerator<JComboBox<*>> {
override fun accept(cmp: Component) = cmp is JComboBox<*>
override fun generate(cmp: JComboBox<*>, me: MouseEvent, cp: Point) = "combobox(\"${getBoundedLabel(3, cmp).text}\")"
}
class BasicArrowButtonDelegatedGenerator : ComponentCodeGenerator<BasicArrowButton> {
override fun priority() = 1 //make sense if we challenge with simple jbutton
override fun accept(cmp: Component) = (cmp is BasicArrowButton) && (cmp.parent is JComboBox<*>)
override fun generate(cmp: BasicArrowButton, me: MouseEvent, cp: Point) = JComboBoxGenerator().generate(cmp.parent as JComboBox<*>, me,
cp)
}
class JRadioButtonGenerator : ComponentCodeGenerator<JRadioButton> {
override fun accept(cmp: Component) = cmp is JRadioButton
override fun generate(cmp: JRadioButton, me: MouseEvent, cp: Point) = "radioButton(\"${cmp.text}\").select()"
}
class LinkLabelGenerator : ComponentCodeGenerator<LinkLabel<*>> {
override fun accept(cmp: Component) = cmp is LinkLabel<*>
override fun generate(cmp: LinkLabel<*>, me: MouseEvent, cp: Point) = "linkLabel(\"${cmp.text}\").click()"
}
class JTreeGenerator : ComponentCodeGenerator<JTree> {
override fun accept(cmp: Component) = cmp is JTree
private fun JTree.getPath(cp: Point) = this.getClosestPathForLocation(cp.x, cp.y)
override fun generate(cmp: JTree, me: MouseEvent, cp: Point): String {
val path = getJTreePath(cmp, cmp.getPath(cp))
if (me.isRightButton()) return "jTree(\"$path\").rightClickPath(\"$path\")"
return "jTree(\"$path\").clickPath(\"$path\")"
}
}
class ProjectViewTreeGenerator : ComponentCodeGenerator<ProjectViewTree> {
override fun priority() = 1
override fun accept(cmp: Component) = cmp is ProjectViewTree
private fun JTree.getPath(cp: Point) = this.getClosestPathForLocation(cp.x, cp.y)
override fun generate(cmp: ProjectViewTree, me: MouseEvent, cp: Point): String {
val path = getJTreePathItemsString(cmp, cmp.getPath(cp))
if (me.isRightButton()) return "path($path).rightClick()"
if (me.clickCount == 2) return "path($path).doubleClick()"
return "path($path).click()"
}
}
class PluginTableGenerator : ComponentCodeGenerator<PluginTable> {
override fun accept(cmp: Component) = cmp is PluginTable
override fun generate(cmp: PluginTable, me: MouseEvent, cp: Point): String {
val row = cmp.rowAtPoint(cp)
val ideaPluginDescriptor = cmp.getObjectAt(row)
return "pluginTable().selectPlugin(\"${ideaPluginDescriptor.name}\")"
}
}
class EditorComponentGenerator : ComponentCodeGenerator<EditorComponentImpl> {
override fun accept(cmp: Component) = cmp is EditorComponentImpl
override fun generate(cmp: EditorComponentImpl, me: MouseEvent, cp: Point): String {
val editor = cmp.editor
val logicalPos = editor.xyToLogicalPosition(cp)
val offset = editor.logicalPositionToOffset(logicalPos)
when (me.button) {
leftButton -> return "moveTo($offset)"
rightButton -> return "rightClick($offset)"
else -> return "//not implemented editor action"
}
}
}
class ActionMenuItemGenerator : ComponentCodeGenerator<ActionMenuItem> {
override fun accept(cmp: Component) = cmp is ActionMenuItem
override fun generate(cmp: ActionMenuItem, me: MouseEvent, cp: Point) =
"popup(${buildPath(activatedActionMenuItem = cmp).joinToString(separator = ", ") { str -> "\"$str\"" }})"
//for buildnig a path of actionMenus and actionMenuItem we need to scan all JBPopup and find a consequence of actions from a tail. Each discovered JBPopupMenu added to hashSet to avoid double sacnning and multiple component finding results
private fun buildPath(activatedActionMenuItem: ActionMenuItem): List<String> {
val jbPopupMenuSet = HashSet<Int>()
jbPopupMenuSet.add(activatedActionMenuItem.parent.hashCode())
val path = ArrayList<String>()
var actionItemName = activatedActionMenuItem.text
path.add(actionItemName)
var window = activatedActionMenuItem.getNextPopupSHeavyWeightWindow()
while (window?.getNextPopupSHeavyWeightWindow() != null) {
window = window!!.getNextPopupSHeavyWeightWindow()
actionItemName = window!!.findJBPopupMenu(jbPopupMenuSet).findParentActionMenu(jbPopupMenuSet)
path.add(0, actionItemName)
}
return path
}
private fun Component.getNextPopupSHeavyWeightWindow(): JWindow? {
if (this.parent == null) return null
var cmp = this.parent
while (cmp != null && !cmp.javaClass.name.endsWith("Popup\$HeavyWeightWindow")) cmp = cmp.parent
if (cmp == null) return null
return cmp as JWindow
}
private fun JWindow.findJBPopupMenu(jbPopupHashSet: MutableSet<Int>): JBPopupMenu {
val robot = BasicRobot.robotWithCurrentAwtHierarchy()
val resultJBPopupMenu = robot.finder().find(this, ComponentMatcher { component ->
(component is JBPopupMenu)
&& component.isShowing
&& component.isVisible
&& !jbPopupHashSet.contains(component.hashCode())
}) as JBPopupMenu
jbPopupHashSet.add(resultJBPopupMenu.hashCode())
robot.cleanUpWithoutDisposingWindows()
return resultJBPopupMenu
}
private fun JBPopupMenu.findParentActionMenu(jbPopupHashSet: MutableSet<Int>): String {
val actionMenu: ActionMenu = this.subElements
.filterIsInstance(ActionMenu::class.java)
.filterNotNull()
.find { actionMenu ->
(actionMenu.subElements != null
&& actionMenu.subElements.isNotEmpty()
&& actionMenu.subElements
.any { menuElement ->
(menuElement is JBPopupMenu && jbPopupHashSet.contains(menuElement.hashCode()))
})
} ?: throw Exception("Unable to find a proper ActionMenu")
return actionMenu.text
}
}
//**********GLOBAL CONTEXT GENERATORS**********
class WelcomeFrameGenerator : GlobalContextCodeGenerator<FlatWelcomeFrame>() {
override fun priority() = 1
override fun accept(cmp: Component) = (cmp as JComponent).rootPane.parent is FlatWelcomeFrame
override fun generate(cmp: FlatWelcomeFrame, me: MouseEvent, cp: Point): String {
return "welcomeFrame {"
}
}
class JDialogGenerator : GlobalContextCodeGenerator<JDialog>() {
override fun accept(cmp: Component) = (cmp as JComponent).rootPane.parent is JDialog
override fun generate(cmp: JDialog, me: MouseEvent, cp: Point) = "dialog(\"${cmp.title}\") {"
}
class IdeFrameGenerator : GlobalContextCodeGenerator<JFrame>() {
override fun accept(cmp: Component): Boolean {
val parent = (cmp as JComponent).rootPane.parent
return (parent is JFrame) && parent.title != "GUI Script Editor"
}
override fun generate(cmp: JFrame, me: MouseEvent, cp: Point) = "ideFrame {"
}
class MacMessageGenerator : ComponentCodeGenerator<JDialog> {
override fun priority() = 1
override fun accept(cmp: Component): Boolean {
if (!(Messages.canShowMacSheetPanel() && (cmp as JComponent).rootPane.parent is JDialog)) return false
val panel = cmp.rootPane.contentPane as JPanel
if (panel.javaClass.name.startsWith(SheetController::class.java.name) && panel.isShowing()) {
val controller = MessagesFixture.findSheetController(panel)
val sheetPanel = field("mySheetPanel").ofType(JPanel::class.java).`in`(controller).get()
if (sheetPanel === panel) {
return true
}
}
return false
}
override fun generate(cmp: JDialog, me: MouseEvent, cp: Point): String {
val panel = cmp.rootPane.contentPane as JPanel
val myRobot = BasicRobot.robotWithCurrentAwtHierarchyWithoutScreenLock()
val title = MessagesFixture.getTitle(panel, myRobot)
myRobot.cleanUpWithoutDisposingWindows()
return "message(\"$title\") {"
}
}
class MessageGenerator : ComponentCodeGenerator<JDialog> {
override fun priority() = 1
override fun accept(cmp: Component): Boolean =
cmp is JDialog && MessageDialogFixture.isMessageDialog(cmp, Ref<DialogWrapper>())
override fun generate(cmp: JDialog, me: MouseEvent, cp: Point): String {
return "message(\"${cmp.title}\") {"
}
}
//**********LOCAL CONTEXT GENERATORS**********
class ProjectViewGenerator : LocalContextCodeGenerator<JPanel>() {
override fun priority() = 1
override fun acceptor(): (Component) -> Boolean = { component -> component.javaClass.name.endsWith("ProjectViewImpl\$MyPanel") }
override fun generate(cmp: JPanel, me: MouseEvent, cp: Point) = "projectView {"
}
class ToolWindowGenerator : LocalContextCodeGenerator<Component>() {
private fun Component.containsLocationOnScreen(locationOnScreen: Point): Boolean {
val rectangle = this.bounds
rectangle.location = this.locationOnScreen
return rectangle.contains(locationOnScreen)
}
private fun Component.centerOnScreen(): Point {
val rectangle = this.bounds
rectangle.location = this.locationOnScreen
return Point(rectangle.centerX.toInt(), rectangle.centerY.toInt())
}
private fun getToolWindow(pointOnScreen: Point): ToolWindowImpl? {
if (WindowManagerImpl.getInstance().findVisibleFrame() !is IdeFrameImpl) return null
val ideFrame = WindowManagerImpl.getInstance().findVisibleFrame() as IdeFrameImpl
ideFrame.project ?: return null
val toolWindowManager = ToolWindowManagerImpl.getInstance(ideFrame.project!!)
val visibleToolWindows = toolWindowManager.toolWindowIds
.map { toolWindowId -> toolWindowManager.getToolWindow(toolWindowId) }
.filter { toolwindow -> toolwindow.isVisible }
val toolwindow: ToolWindowImpl = visibleToolWindows
.filterIsInstance<ToolWindowImpl>()
.find { it.component.containsLocationOnScreen(pointOnScreen) } ?: return null
return toolwindow
}
override fun acceptor(): (Component) -> Boolean = { component ->
val tw = getToolWindow(component.centerOnScreen()); tw != null && component == tw.component
}
override fun generate(cmp: Component, me: MouseEvent, cp: Point): String {
val toolWindow: ToolWindowImpl = getToolWindow(cmp.centerOnScreen())!!
return "toolwindow(id = \"${toolWindow.id}\") {"
}
}
class ToolWindowContextGenerator : LocalContextCodeGenerator<Component>() {
override fun priority() = 1
private fun Component.containsLocationOnScreen(locationOnScreen: Point): Boolean {
val rectangle = this.bounds
rectangle.location = this.locationOnScreen
return rectangle.contains(locationOnScreen)
}
private fun Component.centerOnScreen(): Point {
val rectangle = this.bounds
rectangle.location = this.locationOnScreen
return Point(rectangle.centerX.toInt(), rectangle.centerY.toInt())
}
private fun Component.contains(component: Component): Boolean {
return this.contains(Point(component.bounds.x, component.bounds.y)) &&
this.contains(Point(component.bounds.x + component.width, component.bounds.y + component.height))
}
private fun getToolWindow(pointOnScreen: Point): ToolWindowImpl? {
if (WindowManagerImpl.getInstance().findVisibleFrame() !is IdeFrameImpl) return null
val ideFrame = WindowManagerImpl.getInstance().findVisibleFrame() as IdeFrameImpl
ideFrame.project ?: return null
val toolWindowManager = ToolWindowManagerImpl.getInstance(ideFrame.project!!)
val visibleToolWindows = toolWindowManager.toolWindowIds
.map { toolWindowId -> toolWindowManager.getToolWindow(toolWindowId) }
.filter { toolwindow -> toolwindow.isVisible }
val toolwindow: ToolWindowImpl = visibleToolWindows
.filterIsInstance<ToolWindowImpl>()
.find { it.component.containsLocationOnScreen(pointOnScreen) } ?: return null
return toolwindow
}
override fun acceptor(): (Component) -> Boolean = { component ->
val tw = getToolWindow(component.centerOnScreen()); tw != null && tw.contentManager.selectedContent!!.component == component
}
override fun generate(cmp: Component, me: MouseEvent, cp: Point): String {
val toolWindow: ToolWindowImpl = getToolWindow(cmp.centerOnScreen())!!
val tabName = toolWindow.contentManager.selectedContent?.tabName
return if (tabName != null) "content(tabName = \"${tabName}\") {"
else "content {"
}
}
class EditorGenerator : LocalContextCodeGenerator<EditorComponentImpl>() {
override fun acceptor(): (Component) -> Boolean = { component -> component is EditorComponentImpl }
override fun generate(cmp: EditorComponentImpl, me: MouseEvent, cp: Point) = "editor {"
}
//class JBPopupMenuGenerator: LocalContextCodeGenerator<JBPopupMenu>() {
//
// override fun acceptor(): (Component) -> Boolean = { component -> component is JBPopupMenu}
// override fun generate(cmp: JBPopupMenu, me: MouseEvent, cp: Point) = "popupMenu {"
//}
object Generators {
fun getGenerators(): List<ComponentCodeGenerator<*>> {
val generatorClassPaths = getSiblingsList().filter { path -> path.endsWith("Generator.class") }
val classLoader = Generators.javaClass.classLoader
return generatorClassPaths
.map { clzPath -> classLoader.loadClass("${Generators.javaClass.`package`.name}.${File(clzPath).nameWithoutExtension}") }
.filter { clz -> clz.interfaces.contains(ComponentCodeGenerator::class.java) }
.map(Class<*>::newInstance)
.filterIsInstance(ComponentCodeGenerator::class.java)
}
fun getGlobalContextGenerators(): List<GlobalContextCodeGenerator<*>> {
val generatorClassPaths = getSiblingsList().filter { path -> path.endsWith("Generator.class") }
val classLoader = Generators.javaClass.classLoader
return generatorClassPaths
.map { clzPath -> classLoader.loadClass("${Generators.javaClass.`package`.name}.${File(clzPath).nameWithoutExtension}") }
.filter { clz -> clz.superclass == GlobalContextCodeGenerator::class.java }
.map(Class<*>::newInstance)
.filterIsInstance(GlobalContextCodeGenerator::class.java)
}
fun getLocalContextCodeGenerator(): List<LocalContextCodeGenerator<*>> {
val generatorClassPaths = getSiblingsList().filter { path -> path.endsWith("Generator.class") }
val classLoader = Generators.javaClass.classLoader
return generatorClassPaths
.map { clzPath -> classLoader.loadClass("${Generators.javaClass.`package`.name}.${File(clzPath).nameWithoutExtension}") }
.filter { clz -> clz.superclass == LocalContextCodeGenerator::class.java }
.map(Class<*>::newInstance)
.filterIsInstance(LocalContextCodeGenerator::class.java)
}
fun getSiblingsList(): List<String> {
val path = "/${Generators.javaClass.`package`.name.replace(".", "/")}"
val url = Generators.javaClass.getResource(path)
if (url.path.contains(".jar!")) {
val jarFile = JarFile(Paths.get(URI(url.file.substringBefore(".jar!").plus(".jar"))).toString())
val entries = jarFile.entries()
val genPath = url.path.substringAfter(".jar!").removePrefix("/")
return entries.toList().filter { entry -> entry.name.contains(genPath) }.map { entry -> entry.name }
}
else return File(url.toURI()).listFiles().map { file -> file.toURI().path }
}
}
object Utils {
fun getLabel(container: Container, jTextField: JTextField): JLabel? {
val robot = BasicRobot.robotWithCurrentAwtHierarchyWithoutScreenLock()
return GuiTestUtil.findBoundedLabel(container, jTextField, robot)
}
fun getLabel(jTextField: JTextField): JLabel? {
val parentContainer = jTextField.rootPane.parent
val robot = BasicRobot.robotWithCurrentAwtHierarchyWithoutScreenLock()
return GuiTestUtil.findBoundedLabel(parentContainer, jTextField, robot)
}
fun clicks(me: MouseEvent): String {
if (me.clickCount == 1) return "click()"
if (me.clickCount == 2) return "doubleClick()"
return ""
}
fun getCellText(jbList: JBList<*>, pointOnList: Point): String? {
val index = jbList.locationToIndex(pointOnList)
val cellBounds = jbList.getCellBounds(index, index)
if (cellBounds.contains(pointOnList)) {
val elementAt = jbList.model.getElementAt(index)
when (elementAt) {
is PopupFactoryImpl.ActionItem -> return elementAt.text
is ProjectTemplate -> return elementAt.name
else -> {
val listCellRendererComponent = GuiTestUtil.getListCellRendererComponent(jbList, elementAt, index) as JComponent
if (listCellRendererComponent is JPanel) {
val label = BasicRobot.robotWithNewAwtHierarchyWithoutScreenLock().finder().find(listCellRendererComponent,
ComponentMatcher { it is JLabel })
if (label is JLabel) return label.text
}
return elementAt.toString()
}
}
}
return null
}
fun getCellText(jList: JList<*>, pointOnList: Point): String? {
val index = jList.locationToIndex(pointOnList)
val cellBounds = jList.getCellBounds(index, index)
if (cellBounds.contains(pointOnList)) {
val elementAt = jList.model.getElementAt(index)
val listCellRendererComponent = GuiTestUtil.getListCellRendererComponent(jList, elementAt, index)
when (elementAt) {
is PopupFactoryImpl.ActionItem -> return elementAt.text
is ProjectTemplate -> return elementAt.name
is PresentableVersion -> return elementAt.presentableName
javaClass.canonicalName == "com.intellij.ide.util.frameworkSupport.FrameworkVersion" -> {
val getNameMethod = elementAt.javaClass.getMethod("getVersionName")
val name = getNameMethod.invoke(elementAt)
return name as String
}
else -> {
if (listCellRendererComponent is JPanel) {
if (!listCellRendererComponent.components.isEmpty() && listCellRendererComponent.components[0] is JLabel)
return (listCellRendererComponent.components[0] as JLabel).text
}
else
if (listCellRendererComponent is JLabel)
return listCellRendererComponent.text
return elementAt.toString()
}
}
}
return null
}
fun convertSimpleTreeItemToPath(tree: SimpleTree, itemName: String): String {
val searchableNodeRef = Ref.create<TreeNode>();
val searchableNode: TreeNode?
TreeUtil.traverse(tree.getModel().getRoot() as TreeNode) { node ->
val valueFromNode = SettingsTreeFixture.getValueFromNode(tree, node)
if (valueFromNode != null && valueFromNode == itemName) {
assert(node is TreeNode)
searchableNodeRef.set(node as TreeNode)
}
true
}
searchableNode = searchableNodeRef.get()
val path = TreeUtil.getPathFromRoot(searchableNode!!)
return (0..path.pathCount - 1).map { path.getPathComponent(it).toString() }.filter(String::isNotEmpty).joinToString("/")
}
/**
* @hierarchyLevel: started from 1 to see bounded label for a component itself
*/
fun getBoundedLabel(hierarchyLevel: Int, component: Component): JLabel {
var currentComponent = component
if (hierarchyLevel < 1) throw Exception(
"Hierarchy level (actual is $hierarchyLevel) should starts from 1 to see bounded label for a component itself")
for (i in 1..hierarchyLevel) {
val boundedLabel = findBoundedLabel(currentComponent)
if (boundedLabel != null) return boundedLabel
else {
if (currentComponent.parent == null) break
currentComponent = currentComponent.parent
}
}
throw ComponentLookupException("Unable to find bounded label in ${hierarchyLevel - 1} level(s) from ${component.toString()}")
}
private fun findBoundedLabel(component: Component): JLabel? {
val robot = BasicRobot.robotWithCurrentAwtHierarchyWithoutScreenLock()
var resultLabel: JLabel? = null
if (component is LabeledComponent<*>) return component.label
try {
resultLabel = robot.finder().find(component.parent as Container, object : GenericTypeMatcher<JLabel>(JLabel::class.java) {
override fun isMatching(label: JLabel): Boolean {
return label.labelFor != null && label.labelFor == component
}
})
}
catch(e: ComponentLookupException) {
resultLabel = null
}
return resultLabel
}
fun getJTreePath(cmp: JTree, path: TreePath): String {
val stringBuilder = getJTreePathArray(cmp, path)
return StringUtil.join(stringBuilder, "/")
}
fun getJTreePathItemsString(cmp: JTree, path: TreePath): String {
return getJTreePathArray(cmp, path)
.map { StringUtil.wrapWithDoubleQuote(it) }
.reduceRight({ s, s1 -> "$s, $s1" })
}
private fun getJTreePathArray(cmp: JTree, path: TreePath): ArrayList<String> {
var treePath = path
val result = ArrayList<String>()
val bcr = org.fest.swing.driver.BasicJTreeCellReader()
while (treePath.pathCount != 1 || (cmp.isRootVisible && treePath.pathCount == 1)) {
val valueAt = bcr.valueAt(cmp, treePath.lastPathComponent) ?: "null"
result.add(0, valueAt)
if (treePath.pathCount == 1) break
else treePath = treePath.parentPath
}
return result
}
}
|
apache-2.0
|
ff2d7dfbff3238f20c54e2c79ff5326a
| 42.317221 | 241 | 0.711536 | 4.815449 | false | false | false | false |
NextFaze/dev-fun
|
test/src/testData/kotlin/tested/kapt_and_compile/simple_jvm_static_functions_in_nested_objects/SimpleJvmStaticFunctionsInNestedObjects.kt
|
1
|
8013
|
@file:Suppress("unused", "PackageName")
package tested.kapt_and_compile.simple_jvm_static_functions_in_nested_objects
import com.nextfaze.devfun.function.DeveloperFunction
annotation class SimpleJvmStaticFunctionsInNestedObjects
object SimpleObject {
fun someFun() = Unit
internal fun someInternalFun() = Unit
private fun somePrivateFun() = Unit
@DeveloperFunction
fun publicFun() = Unit
@DeveloperFunction
internal fun internalFun() = Unit
@DeveloperFunction
private fun privateFun() = Unit
object SimpleObjectPublicNested {
fun someFun() = Unit
internal fun someInternalFun() = Unit
private fun somePrivateFun() = Unit
object NestedObject {
@DeveloperFunction
fun publicFun() = Unit
@DeveloperFunction
internal fun internalFun() = Unit
@DeveloperFunction
private fun privateFun() = Unit
@JvmStatic
@DeveloperFunction
fun jvmStaticPublicFun() = Unit
@JvmStatic
@DeveloperFunction
internal fun jvmStaticInternalFun() = Unit
@JvmStatic
@DeveloperFunction
private fun jvmStaticPrivateFun() = Unit
}
}
object SimpleObjectInternalNested {
fun someFun() = Unit
internal fun someInternalFun() = Unit
private fun somePrivateFun() = Unit
internal object NestedObject {
@DeveloperFunction
fun publicFun() = Unit
@DeveloperFunction
internal fun internalFun() = Unit
@DeveloperFunction
private fun privateFun() = Unit
@JvmStatic
@DeveloperFunction
fun jvmStaticPublicFun() = Unit
@JvmStatic
@DeveloperFunction
internal fun jvmStaticInternalFun() = Unit
@JvmStatic
@DeveloperFunction
private fun jvmStaticPrivateFun() = Unit
}
}
object SimpleObjectPrivateNested {
fun someFun() = Unit
internal fun someInternalFun() = Unit
private fun somePrivateFun() = Unit
private object NestedObject {
@DeveloperFunction
fun publicFun() = Unit
@DeveloperFunction
internal fun internalFun() = Unit
@DeveloperFunction
private fun privateFun() = Unit
@JvmStatic
@DeveloperFunction
fun jvmStaticPublicFun() = Unit
@JvmStatic
@DeveloperFunction
internal fun jvmStaticInternalFun() = Unit
@JvmStatic
@DeveloperFunction
private fun jvmStaticPrivateFun() = Unit
}
}
}
internal object InternalSimpleObject {
fun someFun() = Unit
internal fun someInternalFun() = Unit
private fun somePrivateFun() = Unit
@DeveloperFunction
fun publicFun() = Unit
@DeveloperFunction
internal fun internalFun() = Unit
@DeveloperFunction
private fun privateFun() = Unit
internal object InternalSimpleObjectPublicNested {
fun someFun() = Unit
internal fun someInternalFun() = Unit
private fun somePrivateFun() = Unit
object NestedObject {
@DeveloperFunction
fun publicFun() = Unit
@DeveloperFunction
internal fun internalFun() = Unit
@DeveloperFunction
private fun privateFun() = Unit
@JvmStatic
@DeveloperFunction
fun jvmStaticPublicFun() = Unit
@JvmStatic
@DeveloperFunction
internal fun jvmStaticInternalFun() = Unit
@JvmStatic
@DeveloperFunction
private fun jvmStaticPrivateFun() = Unit
}
}
internal object InternalSimpleObjectInternalNested {
fun someFun() = Unit
internal fun someInternalFun() = Unit
private fun somePrivateFun() = Unit
internal object NestedObject {
@DeveloperFunction
fun publicFun() = Unit
@DeveloperFunction
internal fun internalFun() = Unit
@DeveloperFunction
private fun privateFun() = Unit
@JvmStatic
@DeveloperFunction
fun jvmStaticPublicFun() = Unit
@JvmStatic
@DeveloperFunction
internal fun jvmStaticInternalFun() = Unit
@JvmStatic
@DeveloperFunction
private fun jvmStaticPrivateFun() = Unit
}
}
internal object InternalSimpleObjectPrivateNested {
fun someFun() = Unit
internal fun someInternalFun() = Unit
private fun somePrivateFun() = Unit
private object NestedObject {
@DeveloperFunction
fun publicFun() = Unit
@DeveloperFunction
internal fun internalFun() = Unit
@DeveloperFunction
private fun privateFun() = Unit
@JvmStatic
@DeveloperFunction
fun jvmStaticPublicFun() = Unit
@JvmStatic
@DeveloperFunction
internal fun jvmStaticInternalFun() = Unit
@JvmStatic
@DeveloperFunction
private fun jvmStaticPrivateFun() = Unit
}
}
}
private object PrivateSimpleObject {
fun someFun() = Unit
internal fun someInternalFun() = Unit
private fun somePrivateFun() = Unit
@DeveloperFunction
fun publicFun() = Unit
@DeveloperFunction
internal fun internalFun() = Unit
@DeveloperFunction
private fun privateFun() = Unit
private object PrivateSimpleObjectPublicNested {
fun someFun() = Unit
internal fun someInternalFun() = Unit
private fun somePrivateFun() = Unit
object NestedObject {
@DeveloperFunction
fun publicFun() = Unit
@DeveloperFunction
internal fun internalFun() = Unit
@DeveloperFunction
private fun privateFun() = Unit
@JvmStatic
@DeveloperFunction
fun jvmStaticPublicFun() = Unit
@JvmStatic
@DeveloperFunction
internal fun jvmStaticInternalFun() = Unit
@JvmStatic
@DeveloperFunction
private fun jvmStaticPrivateFun() = Unit
}
}
private object PrivateSimpleObjectInternalNested {
fun someFun() = Unit
internal fun someInternalFun() = Unit
private fun somePrivateFun() = Unit
internal object NestedObject {
@DeveloperFunction
fun publicFun() = Unit
@DeveloperFunction
internal fun internalFun() = Unit
@DeveloperFunction
private fun privateFun() = Unit
@JvmStatic
@DeveloperFunction
fun jvmStaticPublicFun() = Unit
@JvmStatic
@DeveloperFunction
internal fun jvmStaticInternalFun() = Unit
@JvmStatic
@DeveloperFunction
private fun jvmStaticPrivateFun() = Unit
}
}
private object PrivateSimpleObjectPrivateNested {
fun someFun() = Unit
internal fun someInternalFun() = Unit
private fun somePrivateFun() = Unit
private object NestedObject {
@DeveloperFunction
fun publicFun() = Unit
@DeveloperFunction
internal fun internalFun() = Unit
@DeveloperFunction
private fun privateFun() = Unit
@JvmStatic
@DeveloperFunction
fun jvmStaticPublicFun() = Unit
@JvmStatic
@DeveloperFunction
internal fun jvmStaticInternalFun() = Unit
@JvmStatic
@DeveloperFunction
private fun jvmStaticPrivateFun() = Unit
}
}
}
|
apache-2.0
|
019a31cb32bed10d816622c8537d4e4b
| 24.600639 | 77 | 0.582054 | 6.10747 | false | false | false | false |
tasks/tasks
|
app/src/main/java/org/tasks/etebase/EtebaseClientProvider.kt
|
1
|
2063
|
package org.tasks.etebase
import android.content.Context
import com.etebase.client.Account
import com.etebase.client.Client
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import org.tasks.data.CaldavAccount
import org.tasks.data.CaldavDao
import org.tasks.http.HttpClientFactory
import org.tasks.security.KeyStoreEncryption
import java.security.KeyManagementException
import java.security.NoSuchAlgorithmException
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class EtebaseClientProvider @Inject constructor(
@ApplicationContext private val context: Context,
private val encryption: KeyStoreEncryption,
private val caldavDao: CaldavDao,
private val httpClientFactory: HttpClientFactory,
) {
@Throws(NoSuchAlgorithmException::class, KeyManagementException::class)
suspend fun forAccount(account: CaldavAccount): EtebaseClient = forUrl(
account.url!!,
account.username!!,
null,
account.getPassword(encryption))
@Throws(KeyManagementException::class, NoSuchAlgorithmException::class)
suspend fun forUrl(url: String, username: String, password: String?, session: String? = null, foreground: Boolean = false): EtebaseClient = withContext(Dispatchers.IO) {
val httpClient = createHttpClient(foreground)
val client = Client.create(httpClient, url)
val etebase = session
?.let { Account.restore(client, it, null) }
?: Account.login(client, username, password!!)
EtebaseClient(context, username, etebase, caldavDao)
}
private suspend fun createHttpClient(foreground: Boolean): OkHttpClient {
return httpClientFactory.newClient(foreground = foreground) { builder ->
builder
.connectTimeout(15, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(120, TimeUnit.SECONDS)
}
}
}
|
gpl-3.0
|
7760a37481dfa6d8e360f2eb84e1a713
| 40.28 | 173 | 0.726127 | 4.842723 | false | false | false | false |
nickthecoder/paratask
|
paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/parameters/FileParameter.kt
|
1
|
5307
|
/*
ParaTask Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.paratask.parameters
import javafx.util.StringConverter
import uk.co.nickthecoder.paratask.parameters.fields.FileField
import uk.co.nickthecoder.paratask.util.FileLister
import uk.co.nickthecoder.paratask.util.currentDirectory
import uk.co.nickthecoder.paratask.util.uncamel
import java.io.File
open class FileParameter(
name: String,
label: String = name.uncamel(),
description: String = "",
hint: String = "",
required: Boolean = true,
val expectFile: Boolean? = true, // false=expect Directory, null=expect either
val mustExist: Boolean? = true, // false=must NOT exist, null=MAY exist
value: File? = if (expectFile == false && mustExist == true) currentDirectory else null,
var baseDirectory: File? = null,
val baseDirectoryP: FileParameter? = null,
val extensions: List<String>? = null)
: AbstractValueParameter<File?>(
name = name,
label = label,
description = description,
hint = hint,
value = value,
required = required) {
override val converter = object : StringConverter<File?>() {
override fun fromString(str: String): File? {
if (str == "") return null
return File(str)
}
override fun toString(file: File?): String {
if (file == null) {
return ""
}
// Should we put a trailing "/" to indicate it is a directory?
val suffix = if (file.isDirectory && file.path != File.separator) File.separator else ""
baseDirectory?.let {
file.relativeToOrNull(it)?.let {
return it.path + suffix
}
}
return file.path + suffix
}
}
init {
if (baseDirectoryP != null) {
baseDirectoryP.listen {
baseDirectory = baseDirectoryP.value
}
baseDirectory = baseDirectoryP.value
}
}
override fun errorMessage(v: File?): String? {
val resolvedValue = resolver().resolveValue(this, v) as File? ?: v
if (isProgrammingMode()) return null
if (resolvedValue == null) {
return super.errorMessage(resolvedValue)
}
if (mustExist != null) {
if (resolvedValue.exists() && mustExist == false) {
return "File already exists"
} else if (!resolvedValue.exists() && mustExist == true) {
return "File does not exist"
}
}
if (expectFile != null) {
if (expectFile && resolvedValue.isDirectory) {
return "Expected a file, but is a directory"
} else if (!expectFile && resolvedValue.isFile) {
return "Expected a directory, but is a file"
}
}
extensions?.let { list ->
if (!list.contains(resolvedValue.extension)) {
return "Incorrect file extension. Expected : $list"
}
}
return null
}
fun createFileChoicesParameter(
fileLister: FileLister,
name: String = "file",
hideExtension: Boolean = true)
: ChoiceParameter<String?> {
val oldValue = value // Needed?
val filenameP = ChoiceParameter<String?>(name, value = null)
listen {
filenameP.clear()
val directory = value
if (directory?.isDirectory == true) {
fileLister.listFiles(directory).forEach { file ->
filenameP.addChoice(file.name, file.name, if (hideExtension) file.nameWithoutExtension else file.name)
}
}
}
// TODO Hmm, this looks odd, why are we firing a value changed???
parameterListeners.fireValueChanged(this, oldValue)
return filenameP
}
override fun coerce(v: Any?) {
if (v is File?) {
value = v
return
}
super.coerce(v)
}
override fun isStretchy(): Boolean = true
override fun createField() = FileField(this).build() as FileField
override fun toString() = "File" + super.toString()
override fun copy() = FileParameter(name = name, label = label, description = description, hint = hint,
value = value, required = required,
mustExist = mustExist, baseDirectory = baseDirectory, expectFile = expectFile, extensions = extensions)
companion object {
var showDragIcon: Boolean = true
var showOpenButton: Boolean = false
}
}
|
gpl-3.0
|
efbf4db7728b0808c81720b1dd3295db
| 31.962733 | 122 | 0.596382 | 4.729947 | false | false | false | false |
groupdocs-comparison/GroupDocs.Comparison-for-Java
|
Demos/Ktor/src/main/kotlin/com/groupdocs/ui/modules/home/HomeTemplate.kt
|
1
|
1479
|
package com.groupdocs.ui.modules.home
import io.ktor.server.html.*
import kotlinx.html.*
class HomeTemplate : Template<HTML> {
val pageTitle = Placeholder<TITLE>()
override fun HTML.apply() {
lang = "en"
head {
meta {
charset = "utf-8"
}
title {
insert(pageTitle)
}
base {
href = "/"
}
meta {
name = "viewport"
content = "width=device-width, initial-scale=1"
}
link(rel = "icon", type = "image/x-icon", href = "static/favicon.ico")
}
body {
HTMLTag(
tagName = "client-root",
consumer = consumer,
inlineTag = false,
emptyTag = false,
initialAttributes = emptyMap()
).visit { }
script { src = "/static/runtime-es2015.js" }
script { src = "/static/polyfills-es2015.js" }
script { src = "/static/runtime-es5.js" }
script { src = "/static/polyfills-es5.js" }
script { src = "/static/styles-es2015.js" }
script { src = "/static/styles-es5.js" }
script { src = "/static/vendor-es2015.js" }
script { src = "/static/main-es2015.js" }
script { src = "/static/vendor-es5.js" }
script { src = "/static/main-es5.js" }
}
}
}
|
mit
|
0f36bcd1142efa6cb949084a9408ea4b
| 29.204082 | 82 | 0.458418 | 4.07438 | false | false | false | false |
ojacquemart/spring-kotlin-euro-bets
|
src/main/kotlin/org/ojacquemart/eurobets/firebase/management/table/TableRow.kt
|
2
|
1310
|
package org.ojacquemart.eurobets.firebase.management.table
data class TableRow(val position: Int = 0,
val uid: String = "",
val displayName: String = "",
val profileImageURL: String = "",
val evolution: Int? = 0,
val points: Int = 0,
val bets: Int = 0,
val perfects: Int = 0,
val goods: Int = 0,
val goodGaps: Int = 0,
val bads: Int = 0,
val percentage: Int = 0,
val winner: Winner? = null,
val recents: Array<Int> = arrayOf()) {
companion object {
fun percentage(tableRow1: TableRow, tableRow2: TableRow): Int {
val nbBets = tableRow1.bets + tableRow2.bets
val sumOfPerfectOrGoodsBets = tableRow1.goods + tableRow1.perfects + tableRow2.goods + tableRow2.perfects
return (sumOfPerfectOrGoodsBets.toFloat().div(nbBets) * 100).toInt();
}
fun getPositions(tableRows: List<TableRow>): List<Int> {
return tableRows.groupBy { it.points }
.toList()
.map { pair -> pair.first }
.sortedDescending()
}
}
}
|
unlicense
|
0a3ec522ae93c9fc106400f7437b46f1
| 36.428571 | 117 | 0.49313 | 4.612676 | false | false | false | false |
soywiz/korge
|
korge/src/commonMain/kotlin/com/soywiz/korge/ui/UIView.kt
|
1
|
2736
|
package com.soywiz.korge.ui
import com.soywiz.kds.*
import com.soywiz.klock.TimeSpan
import com.soywiz.korge.baseview.*
import com.soywiz.korge.component.*
import com.soywiz.korge.input.*
import com.soywiz.korge.internal.*
import com.soywiz.korge.render.*
import com.soywiz.korge.view.*
import com.soywiz.korim.bitmap.*
import com.soywiz.korma.geom.*
import kotlin.math.*
import kotlin.reflect.*
private val View._defaultUiSkin: UISkin by extraProperty { UISkin("defaultUiSkin") { } }
var View.uiSkin: UISkin? by extraProperty { null }
val View.realUiSkin: UISkin get() = uiSkin ?: parent?.realUiSkin ?: root._defaultUiSkin
open class UIView(
width: Double = 90.0,
height: Double = 32.0
) : FixedSizeContainer(width, height), UISkinable {
private val skinProps = FastStringMap<Any?>()
override fun <T> setSkinProperty(property: KProperty<*>, value: T) { skinProps[property.name] = value }
override fun <T> getSkinPropertyOrNull(property: KProperty<*>): T? = (skinProps[property.name] as? T?) ?: realUiSkin.getSkinPropertyOrNull(property)
override var width: Double by uiObservable(width) { onSizeChanged() }
override var height: Double by uiObservable(height) { onSizeChanged() }
override fun getLocalBoundsInternal(out: Rectangle) {
out.setTo(0.0, 0.0, width, height)
}
var enabled
get() = mouseEnabled
set(value) {
mouseEnabled = value
updateState()
}
fun enable(set: Boolean = true) {
enabled = set
}
fun disable() {
enabled = false
}
protected open fun onSizeChanged() {
}
open fun updateState() {
}
override fun renderInternal(ctx: RenderContext) {
registerUISupportOnce()
super.renderInternal(ctx)
}
private var registered = false
private fun registerUISupportOnce() {
if (registered) return
val stage = stage ?: return
registered = true
if (stage.getExtra("uiSupport") == true) return
stage.setExtra("uiSupport", true)
stage.keys {
}
stage.getOrCreateComponentUpdateWithViews<DummyUpdateComponentWithViews> { stage ->
DummyUpdateComponentWithViews(stage)
}
}
companion object {
fun fitIconInRect(iconView: Image, bmp: BmpSlice, width: Double, height: Double, anchor: Anchor) {
val iconScaleX = width / bmp.width
val iconScaleY = height / bmp.height
val iconScale = min(iconScaleX, iconScaleY)
iconView.bitmap = bmp
iconView.anchor(anchor)
iconView.position(width * anchor.sx, height * anchor.sy)
iconView.scale(iconScale, iconScale)
}
}
}
internal class DummyUpdateComponentWithViews(override val view: BaseView) : UpdateComponentWithViews {
override fun update(views: Views, dt: TimeSpan) {
}
}
|
apache-2.0
|
02a67871f82e647d1abe19a126d6f174
| 28.106383 | 152 | 0.700658 | 3.697297 | false | false | false | false |
bozaro/git-as-svn
|
src/main/kotlin/svnserver/repository/git/GitWriter.kt
|
1
|
17577
|
/*
* This file is part of git-as-svn. It is subject to the license terms
* in the LICENSE file found in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn,
* including this file, may be copied, modified, propagated, or distributed
* except according to the terms contained in the LICENSE file.
*/
package svnserver.repository.git
import org.eclipse.jgit.lib.*
import org.eclipse.jgit.revwalk.RevCommit
import org.eclipse.jgit.revwalk.RevTree
import org.eclipse.jgit.revwalk.RevWalk
import org.slf4j.Logger
import org.tmatesoft.svn.core.SVNErrorCode
import org.tmatesoft.svn.core.SVNErrorMessage
import org.tmatesoft.svn.core.SVNException
import org.tmatesoft.svn.core.SVNProperty
import svnserver.Loggers
import svnserver.ReferenceLink
import svnserver.StringHelper
import svnserver.auth.User
import svnserver.repository.Depth
import svnserver.repository.VcsConsumer
import svnserver.repository.git.prop.PropertyMapping
import svnserver.repository.git.push.GitPusher
import svnserver.repository.locks.LockDesc
import svnserver.repository.locks.LockStorage
import java.io.IOException
import java.util.*
/**
* Git commit writer.
*
* @author Artem V. Navrotskiy <[email protected]>
*/
class GitWriter internal constructor(val branch: GitBranch, private val pusher: GitPusher, private val pushLock: Any, private val user: User) : AutoCloseable {
val inserter: ObjectInserter = branch.repository.git.newObjectInserter()
@Throws(IOException::class)
fun createFile(parent: GitEntry, name: String): GitDeltaConsumer {
return GitDeltaConsumer(this, parent.createChild(name, false), null, user)
}
@Throws(IOException::class)
fun modifyFile(parent: GitEntry, name: String, file: GitFile): GitDeltaConsumer {
return GitDeltaConsumer(this, parent.createChild(name, false), file, user)
}
@Throws(IOException::class)
fun createCommitBuilder(lockManager: LockStorage, locks: Map<String, String>): GitCommitBuilder {
return GitCommitBuilder(lockManager, locks)
}
override fun close() {
inserter.use { }
}
private abstract class CommitAction(root: GitFile) {
private val treeStack: Deque<GitFile>
val element: GitFile
get() {
return treeStack.element()
}
@Throws(IOException::class)
fun openDir(name: String) {
val file: GitFile = treeStack.element().getEntry(name) ?: throw IllegalStateException("Invalid state: can't find file $name in created commit.")
treeStack.push(file)
}
@Throws(IOException::class)
abstract fun checkProperties(name: String?, props: Map<String, String>, deltaConsumer: GitDeltaConsumer?)
fun closeDir() {
treeStack.pop()
}
init {
treeStack = ArrayDeque()
treeStack.push(root)
}
}
private class GitFilterMigration(root: GitFile) : CommitAction(root) {
private var migrateCount: Int = 0
@Throws(IOException::class)
override fun checkProperties(name: String?, props: Map<String, String>, deltaConsumer: GitDeltaConsumer?) {
val dir: GitFile = element
val node: GitFile = (if (name == null) dir else dir.getEntry(name)) ?: throw IllegalStateException("Invalid state: can't find entry $name in created commit.")
if (deltaConsumer != null) {
assert((node.filter != null))
if (deltaConsumer.migrateFilter(node.filter)) {
migrateCount++
}
}
}
fun done(): Int {
return migrateCount
}
}
private class GitPropertyValidator(root: GitFile) : CommitAction(root) {
private val propertyMismatch = TreeMap<String, MutableSet<String>>()
private var errorCount = 0
@Throws(IOException::class)
override fun checkProperties(name: String?, props: Map<String, String>, deltaConsumer: GitDeltaConsumer?) {
val dir: GitFile = element
val node: GitFile = (if (name == null) dir else dir.getEntry(name)) ?: throw IllegalStateException("Invalid state: can't find entry $name in created commit.")
if (deltaConsumer != null) {
assert((node.filter != null))
if (node.filter!!.name != deltaConsumer.filterName) {
throw IllegalStateException(
("Invalid writer filter:\n"
+ "Expected: " + node.filter!!.name + "\n"
+ "Actual: " + deltaConsumer.filterName)
)
}
}
val expected: Map<String, String> = node.properties
if (props != expected) {
if (errorCount < MAX_PROPERTY_ERRORS) {
val delta: StringBuilder = StringBuilder()
delta.append("Expected:\n")
for (entry in expected.entries) {
delta.append(" ").append(entry.key).append(" = \"").append(entry.value).append("\"\n")
}
delta.append("Actual:\n")
for (entry in props.entries) {
delta.append(" ").append(entry.key).append(" = \"").append(entry.value).append("\"\n")
}
propertyMismatch.compute(delta.toString()) { _, _value ->
var value = _value
if (value == null) {
value = TreeSet()
}
value.add(node.fullPath)
value
}
errorCount++
}
}
}
@Throws(SVNException::class)
fun done() {
if (propertyMismatch.isNotEmpty()) {
val message: StringBuilder = StringBuilder()
for (entry: Map.Entry<String, Set<String>> in propertyMismatch.entries) {
if (message.isNotEmpty()) {
message.append("\n")
}
message.append("Invalid svn properties on files:\n")
for (path: String? in entry.value) {
message.append(" ").append(path).append("\n")
}
message.append(entry.key)
}
message.append(
("\n"
+ "----------------\n" +
"Subversion properties must be consistent with Git config files:\n")
)
for (configFile: String? in PropertyMapping.registeredFiles) {
message.append(" ").append(configFile).append('\n')
}
message.append(
"\n" +
"For more detailed information, see:"
).append("\n").append(ReferenceLink.InvalidSvnProps.link)
throw SVNException(SVNErrorMessage.create(SVNErrorCode.REPOS_HOOK_FAILURE, message.toString()))
}
}
}
inner class GitCommitBuilder internal constructor(private val lockManager: LockStorage, private val locks: Map<String, String>) {
private val treeStack: Deque<GitTreeUpdate>
private val revision = branch.latestRevision
private val commitActions = ArrayList<VcsConsumer<CommitAction>>()
@get:Throws(IOException::class)
private val originalTree: Iterable<GitTreeEntry>
get() {
val commit: RevCommit = revision.gitNewCommit ?: return emptyList()
return branch.repository.loadTree(GitTreeEntry(branch.repository.git, FileMode.TREE, commit.tree, ""))
}
@Throws(SVNException::class, IOException::class)
fun addDir(name: String, sourceDir: GitFile?) {
val current: GitTreeUpdate = treeStack.element()
if (current.entries.containsKey(name)) {
throw SVNException(SVNErrorMessage.create(SVNErrorCode.FS_ALREADY_EXISTS, getFullPath(name)))
}
commitActions.add(VcsConsumer { action: CommitAction -> action.openDir(name) })
treeStack.push(GitTreeUpdate(name, branch.repository.loadTree(sourceDir?.treeEntry)))
}
private fun getFullPath(name: String): String {
val fullPath: StringBuilder = StringBuilder()
val iter: Iterator<GitTreeUpdate> = treeStack.descendingIterator()
while (iter.hasNext()) {
fullPath.append(iter.next().name).append('/')
}
fullPath.append(name)
return fullPath.toString()
}
@Throws(SVNException::class, IOException::class)
fun openDir(name: String) {
val current: GitTreeUpdate = treeStack.element()
val originalDir: GitTreeEntry? = current.entries.remove(name)
if ((originalDir == null) || (originalDir.fileMode != FileMode.TREE)) {
throw SVNException(SVNErrorMessage.create(SVNErrorCode.ENTRY_NOT_FOUND, getFullPath(name)))
}
commitActions.add(VcsConsumer { action: CommitAction -> action.openDir(name) })
treeStack.push(GitTreeUpdate(name, branch.repository.loadTree(originalDir)))
}
fun checkDirProperties(props: Map<String, String>) {
commitActions.add(VcsConsumer { action: CommitAction -> action.checkProperties(null, props, null) })
}
@Throws(SVNException::class, IOException::class)
fun closeDir() {
val last: GitTreeUpdate = treeStack.pop()
val current: GitTreeUpdate = treeStack.element()
val fullPath: String = getFullPath(last.name)
if (last.entries.isEmpty()) {
if (branch.repository.emptyDirs.autoCreateKeepFile()) {
val keepFile = GitTreeEntry(
branch.repository.git,
FileMode.REGULAR_FILE,
inserter.insert(Constants.OBJ_BLOB, keepFileContents),
keepFileName
)
last.entries[keepFile.fileName] = keepFile
} else {
throw SVNException(SVNErrorMessage.create(SVNErrorCode.CANCELLED, "Empty directories are not supported: $fullPath"))
}
} else if (branch.repository.emptyDirs.autoDeleteKeepFile() && last.entries.containsKey(keepFileName) && (last.entries.size > 1)) {
// remove keep file if it is not the only file in the directory
// would be good to also validate the content
last.entries.remove(keepFileName)
}
val subtreeId: ObjectId = last.buildTree(inserter)
log.debug("Create tree {} for dir: {}", subtreeId.name(), fullPath)
if (current.entries.put(last.name, GitTreeEntry(FileMode.TREE, GitObject(branch.repository.git, subtreeId), last.name)) != null) {
throw SVNException(SVNErrorMessage.create(SVNErrorCode.FS_ALREADY_EXISTS, fullPath))
}
commitActions.add(VcsConsumer { it.closeDir() })
}
@Throws(SVNException::class, IOException::class)
fun saveFile(name: String, deltaConsumer: GitDeltaConsumer, modify: Boolean) {
val gitDeltaConsumer: GitDeltaConsumer = deltaConsumer
val current: GitTreeUpdate = treeStack.element()
val entry: GitTreeEntry? = current.entries[name]
val originalId: GitObject<ObjectId>? = gitDeltaConsumer.originalId
if (modify xor (entry != null)) {
throw SVNException(SVNErrorMessage.create(SVNErrorCode.WC_NOT_UP_TO_DATE, "Working copy is not up-to-date: " + getFullPath(name)))
}
val objectId: GitObject<ObjectId>? = gitDeltaConsumer.getObjectId()
if (objectId == null) {
// Content not updated.
if (originalId == null) {
throw SVNException(SVNErrorMessage.create(SVNErrorCode.INCOMPLETE_DATA, "Added file without content: " + getFullPath(name)))
}
return
}
current.entries[name] = GitTreeEntry(getFileMode(gitDeltaConsumer.properties), objectId, name)
commitActions.add(VcsConsumer { action: CommitAction -> action.checkProperties(name, gitDeltaConsumer.properties, gitDeltaConsumer) })
}
private fun getFileMode(props: Map<String, String>): FileMode {
if (props.containsKey(SVNProperty.SPECIAL)) return FileMode.SYMLINK
if (props.containsKey(SVNProperty.EXECUTABLE)) return FileMode.EXECUTABLE_FILE
return FileMode.REGULAR_FILE
}
@Throws(SVNException::class)
fun delete(name: String) {
val current = treeStack.element()
current.entries.remove(name) ?: throw SVNException(SVNErrorMessage.create(SVNErrorCode.ENTRY_NOT_FOUND, getFullPath(name)))
}
@Throws(SVNException::class, IOException::class)
fun commit(userInfo: User, message: String): GitRevision? {
val root: GitTreeUpdate = treeStack.element()
val treeId: ObjectId = root.buildTree(inserter)
log.debug("Create tree {} for commit.", treeId.name())
val commitBuilder = CommitBuilder()
val ident: PersonIdent = createIdent(userInfo)
commitBuilder.author = ident
commitBuilder.committer = ident
commitBuilder.message = message
val parentCommit: RevCommit? = revision.gitNewCommit
if (parentCommit != null) {
commitBuilder.setParentId(parentCommit.id)
}
commitBuilder.setTreeId(treeId)
val commitId: ObjectId = inserter.insert(commitBuilder)
inserter.flush()
log.info("Create commit {}: {}", commitId.name(), StringHelper.getFirstLine(message))
if (filterMigration(RevWalk(branch.repository.git).parseTree(treeId)) != 0) {
log.info("Need recreate tree after filter migration.")
return null
}
synchronized(pushLock) {
log.info("Validate properties")
validateProperties(RevWalk(branch.repository.git).parseTree(treeId))
log.info("Try to push commit in branch: {}", branch)
if (!pusher.push(branch.repository.git, commitId, branch.gitBranch, userInfo)) {
log.info("Non fast forward push rejected")
return null
}
log.info("Commit is pushed")
branch.updateRevisions()
return branch.getRevision(commitId)
}
}
private fun createIdent(userInfo: User): PersonIdent {
return PersonIdent(userInfo.realName, userInfo.email ?: "")
}
@Throws(IOException::class, SVNException::class)
private fun filterMigration(tree: RevTree): Int {
val root: GitFile = GitFileTreeEntry.create(branch, tree, 0)
val validator = GitFilterMigration(root)
for (validateAction: VcsConsumer<CommitAction> in commitActions) {
validateAction.accept(validator)
}
return validator.done()
}
@Throws(IOException::class, SVNException::class)
private fun validateProperties(tree: RevTree) {
val root: GitFile = GitFileTreeEntry.create(branch, tree, 0)
val validator = GitPropertyValidator(root)
for (validateAction: VcsConsumer<CommitAction> in commitActions) {
validateAction.accept(validator)
}
validator.done()
}
@Throws(SVNException::class, IOException::class)
fun checkUpToDate(path: String, rev: Int) {
val file: GitFile? = revision.getFile(path)
if (file == null) {
throw SVNException(SVNErrorMessage.create(SVNErrorCode.ENTRY_NOT_FOUND, path))
} else if (file.lastChange.id > rev) {
throw SVNException(SVNErrorMessage.create(SVNErrorCode.WC_NOT_UP_TO_DATE, "Working copy is not up-to-date: $path"))
}
}
@Throws(SVNException::class, IOException::class)
fun checkLock(path: String) {
val iter: Iterator<LockDesc> = lockManager.getLocks(user, branch, path, Depth.Infinity)
while (iter.hasNext()) checkLockDesc(iter.next())
}
@Throws(SVNException::class)
private fun checkLockDesc(lockDesc: LockDesc?) {
if (lockDesc != null) {
val token: String? = locks[lockDesc.path]
if (lockDesc.token != token) throw SVNException(SVNErrorMessage.create(SVNErrorCode.FS_BAD_LOCK_TOKEN, String.format("Cannot verify lock on path '%s'; no matching lock-token available", lockDesc.path)))
}
}
init {
treeStack = ArrayDeque()
treeStack.push(GitTreeUpdate("", originalTree))
}
}
companion object {
const val keepFileName: String = ".keep"
val keepFileContents: ByteArray = GitRepository.emptyBytes
private const val MAX_PROPERTY_ERRORS: Int = 50
private val log: Logger = Loggers.git
}
}
|
gpl-2.0
|
bd25366276f9c95159b343fcc18c1a4a
| 44.773438 | 218 | 0.594641 | 4.719925 | false | false | false | false |
stripe/stripe-android
|
payments-core/src/main/java/com/stripe/android/model/parsers/NextActionDataParser.kt
|
1
|
9654
|
package com.stripe.android.model.parsers
import android.net.Uri
import com.stripe.android.core.model.StripeJsonUtils
import com.stripe.android.core.model.StripeJsonUtils.optString
import com.stripe.android.core.model.parsers.ModelJsonParser
import com.stripe.android.model.MicrodepositType
import com.stripe.android.model.StripeIntent
import com.stripe.android.model.WeChat
import org.json.JSONObject
internal class NextActionDataParser : ModelJsonParser<StripeIntent.NextActionData> {
override fun parse(
json: JSONObject
): StripeIntent.NextActionData? {
val nextActionType = StripeIntent.NextActionType.fromCode(
json.optString(FIELD_NEXT_ACTION_TYPE)
)
val parser = when (nextActionType) {
StripeIntent.NextActionType.DisplayOxxoDetails -> DisplayOxxoDetailsJsonParser()
StripeIntent.NextActionType.RedirectToUrl -> RedirectToUrlParser()
StripeIntent.NextActionType.UseStripeSdk -> SdkDataJsonParser()
StripeIntent.NextActionType.AlipayRedirect -> AlipayRedirectParser()
StripeIntent.NextActionType.BlikAuthorize -> BlikAuthorizeParser()
StripeIntent.NextActionType.WeChatPayRedirect -> WeChatPayRedirectParser()
StripeIntent.NextActionType.VerifyWithMicrodeposits -> VerifyWithMicrodepositsParser()
StripeIntent.NextActionType.UpiAwaitNotification -> UpiAwaitNotificationParser()
null -> return null
}
return parser.parse(json.optJSONObject(nextActionType.code) ?: JSONObject())
}
private class DisplayOxxoDetailsJsonParser :
ModelJsonParser<StripeIntent.NextActionData.DisplayOxxoDetails> {
override fun parse(
json: JSONObject
): StripeIntent.NextActionData.DisplayOxxoDetails {
return StripeIntent.NextActionData.DisplayOxxoDetails(
expiresAfter = json.optInt(FIELD_EXPIRES_AFTER),
number = optString(json, FIELD_NUMBER),
hostedVoucherUrl = optString(json, FIELD_HOSTED_VOUCHER_URL)
)
}
private companion object {
private const val FIELD_EXPIRES_AFTER = "expires_after"
private const val FIELD_NUMBER = "number"
private const val FIELD_HOSTED_VOUCHER_URL = "hosted_voucher_url"
}
}
internal class RedirectToUrlParser :
ModelJsonParser<StripeIntent.NextActionData.RedirectToUrl> {
override fun parse(
json: JSONObject
): StripeIntent.NextActionData.RedirectToUrl? {
return when {
json.has(FIELD_URL) ->
StripeIntent.NextActionData.RedirectToUrl(
Uri.parse(json.getString(FIELD_URL)),
json.optString(FIELD_RETURN_URL)
)
else -> null
}
}
private companion object {
const val FIELD_URL = "url"
const val FIELD_RETURN_URL = "return_url"
}
}
internal class AlipayRedirectParser :
ModelJsonParser<StripeIntent.NextActionData.AlipayRedirect> {
override fun parse(
json: JSONObject
): StripeIntent.NextActionData.AlipayRedirect {
return StripeIntent.NextActionData.AlipayRedirect(
json.getString(FIELD_NATIVE_DATA),
json.getString(FIELD_URL),
optString(json, FIELD_RETURN_URL)
)
}
private companion object {
const val FIELD_NATIVE_DATA = "native_data"
const val FIELD_RETURN_URL = "return_url"
const val FIELD_URL = "url"
}
}
private class SdkDataJsonParser : ModelJsonParser<StripeIntent.NextActionData.SdkData> {
override fun parse(json: JSONObject): StripeIntent.NextActionData.SdkData? {
return when (optString(json, FIELD_TYPE)) {
TYPE_3DS1 -> StripeIntent.NextActionData.SdkData.Use3DS1(
json.optString(FIELD_STRIPE_JS)
)
TYPE_3DS2 -> StripeIntent.NextActionData.SdkData.Use3DS2(
json.optString(FIELD_THREE_D_SECURE_2_SOURCE),
json.optString(FIELD_DIRECTORY_SERVER_NAME),
json.optString(FIELD_SERVER_TRANSACTION_ID),
parseDirectoryServerEncryption(
json.optJSONObject(FIELD_DIRECTORY_SERVER_ENCRYPTION)
?: JSONObject()
),
optString(json, FIELD_THREE_D_SECURE_2_INTENT),
optString(json, FIELD_PUBLISHABLE_KEY)
)
else -> null
}
}
private fun parseDirectoryServerEncryption(
json: JSONObject
): StripeIntent.NextActionData.SdkData.Use3DS2.DirectoryServerEncryption {
val rootCert =
StripeJsonUtils.jsonArrayToList(json.optJSONArray(FIELD_ROOT_CAS))
?.fold(emptyList<String>()) { acc, entry ->
if (entry is String) {
acc.plus(entry)
} else {
acc
}
} ?: emptyList()
return StripeIntent.NextActionData.SdkData.Use3DS2.DirectoryServerEncryption(
json.optString(FIELD_DIRECTORY_SERVER_ID),
json.optString(FIELD_CERTIFICATE),
rootCert,
json.optString(FIELD_KEY_ID)
)
}
private companion object {
private const val FIELD_TYPE = "type"
private const val TYPE_3DS2 = "stripe_3ds2_fingerprint"
private const val TYPE_3DS1 = "three_d_secure_redirect"
private const val FIELD_THREE_D_SECURE_2_SOURCE = "three_d_secure_2_source"
private const val FIELD_DIRECTORY_SERVER_NAME = "directory_server_name"
private const val FIELD_SERVER_TRANSACTION_ID = "server_transaction_id"
private const val FIELD_DIRECTORY_SERVER_ENCRYPTION = "directory_server_encryption"
private const val FIELD_DIRECTORY_SERVER_ID = "directory_server_id"
private const val FIELD_CERTIFICATE = "certificate"
private const val FIELD_KEY_ID = "key_id"
private const val FIELD_ROOT_CAS = "root_certificate_authorities"
private const val FIELD_THREE_D_SECURE_2_INTENT = "three_d_secure_2_intent"
private const val FIELD_PUBLISHABLE_KEY = "publishable_key"
private const val FIELD_STRIPE_JS = "stripe_js"
}
}
internal class BlikAuthorizeParser :
ModelJsonParser<StripeIntent.NextActionData.BlikAuthorize> {
override fun parse(json: JSONObject): StripeIntent.NextActionData.BlikAuthorize {
return StripeIntent.NextActionData.BlikAuthorize
}
}
internal class WeChatPayRedirectParser :
ModelJsonParser<StripeIntent.NextActionData.WeChatPayRedirect> {
override fun parse(json: JSONObject): StripeIntent.NextActionData.WeChatPayRedirect {
return StripeIntent.NextActionData.WeChatPayRedirect(
WeChat(
appId = json.optString(APP_ID),
nonce = json.optString(NONCE_STR),
packageValue = json.optString(
PACKAGE
),
partnerId = json.optString(PARTNER_ID),
prepayId = json.optString(
PREPAY_ID
),
timestamp = json.optString(TIMESTAMP),
sign = json.optString(SIGN)
)
)
}
private companion object {
private const val APP_ID = "app_id"
private const val NONCE_STR = "nonce_str"
private const val PACKAGE = "package"
private const val PARTNER_ID = "partner_id"
private const val PREPAY_ID = "prepay_id"
private const val TIMESTAMP = "timestamp"
private const val SIGN = "sign"
}
}
internal class VerifyWithMicrodepositsParser :
ModelJsonParser<StripeIntent.NextActionData.VerifyWithMicrodeposits> {
override fun parse(json: JSONObject): StripeIntent.NextActionData.VerifyWithMicrodeposits {
return StripeIntent.NextActionData.VerifyWithMicrodeposits(
arrivalDate = json.optLong(ARRIVAL_DATE),
hostedVerificationUrl = json.optString(HOSTED_VERIFICATION_URL),
microdepositType = parseMicrodepositType(json)
)
}
private fun parseMicrodepositType(json: JSONObject): MicrodepositType {
return MicrodepositType.values().find {
it.value == json.optString(MICRODEPOSIT_TYPE)
} ?: MicrodepositType.UNKNOWN
}
private companion object {
private const val ARRIVAL_DATE = "arrival_date"
private const val HOSTED_VERIFICATION_URL = "hosted_verification_url"
private const val MICRODEPOSIT_TYPE = "microdeposit_type"
}
}
internal class UpiAwaitNotificationParser :
ModelJsonParser<StripeIntent.NextActionData.UpiAwaitNotification> {
override fun parse(json: JSONObject): StripeIntent.NextActionData.UpiAwaitNotification {
return StripeIntent.NextActionData.UpiAwaitNotification
}
}
private companion object {
private const val FIELD_NEXT_ACTION_TYPE = "type"
}
}
|
mit
|
e032389d5c7d7a3c1a1ad52b399e733d
| 41.342105 | 99 | 0.613424 | 5.057098 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.