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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
da1z/intellij-community | platform/credential-store/src/kdbx/KdbxHeader.kt | 4 | 6089 | /*
* Copyright 2015 Jo Rabin
*
* 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.credentialStore.kdbx
import org.bouncycastle.crypto.engines.AESEngine
import org.bouncycastle.crypto.engines.AESFastEngine
import org.bouncycastle.crypto.io.CipherInputStream
import org.bouncycastle.crypto.io.CipherOutputStream
import org.bouncycastle.crypto.modes.CBCBlockCipher
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher
import org.bouncycastle.crypto.params.KeyParameter
import org.bouncycastle.crypto.params.ParametersWithIV
import java.io.InputStream
import java.io.OutputStream
import java.nio.ByteBuffer
import java.security.MessageDigest
import java.security.SecureRandom
import java.util.*
/**
* This class represents the header portion of a KeePass KDBX file or stream. The header is received in
* plain text and describes the encryption and compression of the remainder of the file.
* It is a factory for encryption and decryption streams and contains a hash of its own serialization.
* While KDBX streams are Little-Endian, data is passed to and from this class in standard Java byte order.
* @author jo
*/
/**
* This UUID denotes that AES Cipher is in use. No other values are known.
*/
private val AES_CIPHER = UUID.fromString("31C1F2E6-BF71-4350-BE58-05216AFC5AFF")
internal class KdbxHeader {
/**
* The ordinal 0 represents uncompressed and 1 GZip compressed
*/
enum class CompressionFlags {
NONE, GZIP
}
/**
* The ordinals represent various types of encryption that may be applied to fields within the unencrypted data
*/
enum class ProtectedStreamAlgorithm {
NONE, ARC_FOUR, SALSA_20
}
/* the cipher in use */
var cipherUuid = AES_CIPHER!!
private set
/* whether the data is compressed */
var compressionFlags = CompressionFlags.GZIP
private set
var masterSeed: ByteArray
var transformSeed: ByteArray
var transformRounds: Long = 6000
var encryptionIv: ByteArray
var protectedStreamKey: ByteArray
var protectedStreamAlgorithm = ProtectedStreamAlgorithm.SALSA_20
private set
/* these bytes appear in cipher text immediately following the header */
var streamStartBytes = ByteArray(32)
/* not transmitted as part of the header, used in the XML payload, so calculated
* on transmission or receipt */
var headerHash: ByteArray? = null
init {
val random = SecureRandom()
masterSeed = random.generateSeed(32)
transformSeed = random.generateSeed(32)
encryptionIv = random.generateSeed(16)
protectedStreamKey = random.generateSeed(32)
}
/**
* Create a decrypted input stream using supplied digest and this header
* apply decryption to the passed encrypted input stream
*/
fun createDecryptedStream(digest: ByteArray, inputStream: InputStream): InputStream {
val finalKeyDigest = getFinalKeyDigest(digest, masterSeed, transformSeed, transformRounds)
return getDecryptedInputStream(inputStream, finalKeyDigest, encryptionIv)
}
/**
* Create an unencrypted output stream using the supplied digest and this header
* and use the supplied output stream to write encrypted data.
*/
fun createEncryptedStream(digest: ByteArray, outputStream: OutputStream): OutputStream {
val finalKeyDigest = getFinalKeyDigest(digest, masterSeed, transformSeed, transformRounds)
return getEncryptedOutputStream(outputStream, finalKeyDigest, encryptionIv)
}
fun setCipherUuid(uuid: ByteArray) {
val b = ByteBuffer.wrap(uuid)
val incoming = UUID(b.long, b.getLong(8))
if (incoming != AES_CIPHER) {
throw IllegalStateException("Unknown Cipher UUID $incoming")
}
this.cipherUuid = incoming
}
fun setCompressionFlags(flags: Int) {
this.compressionFlags = CompressionFlags.values()[flags]
}
fun setInnerRandomStreamId(innerRandomStreamId: Int) {
this.protectedStreamAlgorithm = ProtectedStreamAlgorithm.values()[innerRandomStreamId]
}
}
private fun getFinalKeyDigest(key: ByteArray, masterSeed: ByteArray, transformSeed: ByteArray, transformRounds: Long): ByteArray {
val engine = AESEngine()
engine.init(true, KeyParameter(transformSeed))
// copy input key
val transformedKey = ByteArray(key.size)
System.arraycopy(key, 0, transformedKey, 0, transformedKey.size)
// transform rounds times
for (rounds in 0 until transformRounds) {
engine.processBlock(transformedKey, 0, transformedKey, 0)
engine.processBlock(transformedKey, 16, transformedKey, 16)
}
val md = sha256MessageDigest()
val transformedKeyDigest = md.digest(transformedKey)
md.update(masterSeed)
return md.digest(transformedKeyDigest)
}
fun sha256MessageDigest(): MessageDigest = MessageDigest.getInstance("SHA-256")
/**
* Create a decrypted input stream from an encrypted one
*/
private fun getDecryptedInputStream(encryptedInputStream: InputStream, keyData: ByteArray, ivData: ByteArray): InputStream {
val keyAndIV = ParametersWithIV(KeyParameter(keyData), ivData)
val pbbc = PaddedBufferedBlockCipher(CBCBlockCipher(AESFastEngine()))
pbbc.init(false, keyAndIV)
return CipherInputStream(encryptedInputStream, pbbc)
}
/**
* Create an encrypted output stream from an unencrypted output stream
*/
private fun getEncryptedOutputStream(decryptedOutputStream: OutputStream, keyData: ByteArray, ivData: ByteArray): OutputStream {
val keyAndIV = ParametersWithIV(KeyParameter(keyData), ivData)
val pbbc = PaddedBufferedBlockCipher(CBCBlockCipher(AESFastEngine()))
pbbc.init(true, keyAndIV)
return CipherOutputStream(decryptedOutputStream, pbbc)
} | apache-2.0 | 4b027691f3599d9f3f68b33bb02b8036 | 35.686747 | 130 | 0.768106 | 4.306223 | false | false | false | false |
jgrandja/spring-security | config/src/test/kotlin/org/springframework/security/config/web/servlet/OAuth2ResourceServerDslTests.kt | 2 | 9235 | /*
* Copyright 2002-2021 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
*
* 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 org.springframework.security.config.web.servlet
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.verify
import javax.servlet.http.HttpServletRequest
import org.assertj.core.api.Assertions
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.BeanCreationException
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.authentication.AuthenticationManagerResolver
import org.springframework.security.authentication.TestingAuthenticationToken
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.config.test.SpringTestContext
import org.springframework.security.config.test.SpringTestContextExtension
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.SUB
import org.springframework.security.oauth2.jwt.Jwt
import org.springframework.security.oauth2.jwt.JwtDecoder
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken
import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver
import org.springframework.security.oauth2.server.resource.web.DefaultBearerTokenResolver
import org.springframework.security.web.AuthenticationEntryPoint
import org.springframework.security.web.access.AccessDeniedHandler
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.get
/**
* Tests for [OAuth2ResourceServerDsl]
*
* @author Eleftheria Stein
*/
@ExtendWith(SpringTestContextExtension::class)
class OAuth2ResourceServerDslTests {
@JvmField
val spring = SpringTestContext(this)
@Autowired
lateinit var mockMvc: MockMvc
private val JWT: Jwt = Jwt.withTokenValue("token")
.header("alg", "none")
.claim(SUB, "user")
.build()
@Test
fun `oauth2Resource server when custom entry point then entry point used`() {
this.spring.register(EntryPointConfig::class.java).autowire()
mockkObject(EntryPointConfig.ENTRY_POINT)
every { EntryPointConfig.ENTRY_POINT.commence(any(), any(), any()) } returns Unit
this.mockMvc.get("/")
verify(exactly = 1) { EntryPointConfig.ENTRY_POINT.commence(any(), any(), any()) }
}
@EnableWebSecurity
open class EntryPointConfig : WebSecurityConfigurerAdapter() {
companion object {
val ENTRY_POINT: AuthenticationEntryPoint = AuthenticationEntryPoint { _, _, _ -> }
}
override fun configure(http: HttpSecurity) {
http {
authorizeRequests {
authorize(anyRequest, authenticated)
}
oauth2ResourceServer {
authenticationEntryPoint = ENTRY_POINT
jwt { }
}
}
}
@Bean
open fun jwtDecoder(): JwtDecoder = mockk()
}
@Test
fun `oauth2Resource server when custom bearer token resolver then resolver used`() {
this.spring.register(BearerTokenResolverConfig::class.java).autowire()
mockkObject(BearerTokenResolverConfig.RESOLVER)
mockkObject(BearerTokenResolverConfig.DECODER)
every { BearerTokenResolverConfig.RESOLVER.resolve(any()) } returns "anything"
every { BearerTokenResolverConfig.DECODER.decode(any()) } returns JWT
this.mockMvc.get("/")
verify(exactly = 1) { BearerTokenResolverConfig.RESOLVER.resolve(any()) }
}
@EnableWebSecurity
open class BearerTokenResolverConfig : WebSecurityConfigurerAdapter() {
companion object {
val RESOLVER: BearerTokenResolver = DefaultBearerTokenResolver()
val DECODER: JwtDecoder = JwtDecoder {
Jwt.withTokenValue("token")
.header("alg", "none")
.claim(SUB, "user")
.build()
}
}
override fun configure(http: HttpSecurity) {
http {
authorizeRequests {
authorize(anyRequest, authenticated)
}
oauth2ResourceServer {
bearerTokenResolver = RESOLVER
jwt { }
}
}
}
@Bean
open fun jwtDecoder(): JwtDecoder = DECODER
}
@Test
fun `oauth2Resource server when custom access denied handler then handler used`() {
this.spring.register(AccessDeniedHandlerConfig::class.java).autowire()
mockkObject(AccessDeniedHandlerConfig.DENIED_HANDLER)
mockkObject(AccessDeniedHandlerConfig.DECODER)
every {
AccessDeniedHandlerConfig.DECODER.decode(any())
} returns JWT
every {
AccessDeniedHandlerConfig.DENIED_HANDLER.handle(any(), any(), any())
} returns Unit
this.mockMvc.get("/") {
header("Authorization", "Bearer token")
}
verify(exactly = 1) { AccessDeniedHandlerConfig.DENIED_HANDLER.handle(any(), any(), any()) }
}
@EnableWebSecurity
open class AccessDeniedHandlerConfig : WebSecurityConfigurerAdapter() {
companion object {
val DECODER: JwtDecoder = JwtDecoder { _ ->
Jwt.withTokenValue("token")
.header("alg", "none")
.claim(SUB, "user")
.build()
}
val DENIED_HANDLER: AccessDeniedHandler = AccessDeniedHandler { _, _, _ -> }
}
override fun configure(http: HttpSecurity) {
http {
authorizeRequests {
authorize(anyRequest, denyAll)
}
oauth2ResourceServer {
accessDeniedHandler = DENIED_HANDLER
jwt { }
}
}
}
@Bean
open fun jwtDecoder(): JwtDecoder = DECODER
}
@Test
fun `oauth2Resource server when custom authentication manager resolver then resolver used`() {
this.spring.register(AuthenticationManagerResolverConfig::class.java).autowire()
mockkObject(AuthenticationManagerResolverConfig.RESOLVER)
every {
AuthenticationManagerResolverConfig.RESOLVER.resolve(any())
} returns AuthenticationManager {
JwtAuthenticationToken(JWT)
}
this.mockMvc.get("/") {
header("Authorization", "Bearer token")
}
verify(exactly = 1) { AuthenticationManagerResolverConfig.RESOLVER.resolve(any()) }
}
@EnableWebSecurity
open class AuthenticationManagerResolverConfig : WebSecurityConfigurerAdapter() {
companion object {
val RESOLVER: AuthenticationManagerResolver<HttpServletRequest> =
AuthenticationManagerResolver {
AuthenticationManager {
TestingAuthenticationToken("a,", "b", "c")
}
}
}
override fun configure(http: HttpSecurity) {
http {
authorizeRequests {
authorize(anyRequest, authenticated)
}
oauth2ResourceServer {
authenticationManagerResolver = RESOLVER
}
}
}
}
@Test
fun `oauth2Resource server when custom authentication manager resolver and opaque then exception`() {
Assertions.assertThatExceptionOfType(BeanCreationException::class.java)
.isThrownBy { spring.register(AuthenticationManagerResolverAndOpaqueConfig::class.java).autowire() }
.withMessageContaining("authenticationManagerResolver")
}
@EnableWebSecurity
open class AuthenticationManagerResolverAndOpaqueConfig : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http {
authorizeRequests {
authorize(anyRequest, authenticated)
}
oauth2ResourceServer {
authenticationManagerResolver = mockk()
opaqueToken { }
}
}
}
}
}
| apache-2.0 | f7b35d2cdc6d0065b632f338597a93d1 | 35.501976 | 116 | 0.649486 | 5.372309 | false | true | false | false |
Maccimo/intellij-community | platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/EntityStorageSerializationTest.kt | 1 | 7700 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage
import com.intellij.workspaceModel.storage.bridgeEntities.api.LibraryTableId
import com.intellij.workspaceModel.storage.bridgeEntities.addLibraryEntity
import com.intellij.workspaceModel.storage.entities.test.addSampleEntity
import com.intellij.workspaceModel.storage.entities.test.api.MySource
import com.intellij.workspaceModel.storage.impl.EntityStorageSerializerImpl
import com.intellij.workspaceModel.storage.impl.MutableEntityStorageImpl
import com.intellij.workspaceModel.storage.impl.url.VirtualFileUrlManagerImpl
import junit.framework.Assert.*
import org.junit.Test
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
class EntityStorageSerializationTest {
@Test
fun `simple model serialization`() {
val builder = createEmptyBuilder()
builder.addSampleEntity("MyEntity")
SerializationRoundTripChecker.verifyPSerializationRoundTrip(builder.toSnapshot(), VirtualFileUrlManagerImpl())
}
@Test
fun `entity properties serialization`() {
val builder = createEmptyBuilder()
builder.addSampleEntity(stringProperty = "MyEntity",
stringListProperty = mutableListOf("a", "b"),
stringSetProperty = mutableSetOf("c", "d"))
SerializationRoundTripChecker.verifyPSerializationRoundTrip(builder.toSnapshot(), VirtualFileUrlManagerImpl())
}
@Test
fun `serialization with version changing`() {
val builder = createEmptyBuilder()
builder.addSampleEntity("MyEntity")
val serializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), VirtualFileUrlManagerImpl())
val deserializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), VirtualFileUrlManagerImpl())
.also { it.serializerDataFormatVersion = "XYZ" }
val stream = ByteArrayOutputStream()
serializer.serializeCache(stream, builder.toSnapshot())
val byteArray = stream.toByteArray()
val deserialized = (deserializer.deserializeCache(ByteArrayInputStream(byteArray)) as? MutableEntityStorageImpl)?.toSnapshot()
assertNull(deserialized)
}
@Test
fun `serializer version`() {
val serializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), VirtualFileUrlManagerImpl())
val kryo = serializer.createKryo()
val registration = (10..1_000).mapNotNull { kryo.getRegistration(it) }.joinToString(separator = "\n")
assertEquals("Have you changed kryo registration? Update the version number! (And this test)", expectedKryoRegistration, registration)
}
@Test
fun `serialize empty lists`() {
val virtualFileManager = VirtualFileUrlManagerImpl()
val serializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), virtualFileManager)
val builder = createEmptyBuilder()
// Do not replace ArrayList() with emptyList(). This must be a new object for this test
builder.addLibraryEntity("myName", LibraryTableId.ProjectLibraryTableId, ArrayList(), ArrayList(), MySource)
val stream = ByteArrayOutputStream()
serializer.serializeCache(stream, builder.toSnapshot())
}
@Test
fun `serialize abstract`() {
val virtualFileManager = VirtualFileUrlManagerImpl()
val serializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), virtualFileManager)
val builder = createEmptyBuilder()
builder.addSampleEntity("myString")
val stream = ByteArrayOutputStream()
val result = serializer.serializeCache(stream, builder.toSnapshot())
assertTrue(result is SerializationResult.Success)
}
@Test
fun `read broken cache`() {
val virtualFileManager = VirtualFileUrlManagerImpl()
val serializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), virtualFileManager)
val builder = createEmptyBuilder()
builder.addSampleEntity("myString")
val stream = ByteArrayOutputStream()
serializer.serializeCache(stream, builder.toSnapshot())
// Remove random byte from a serialised store
val inputStream = stream.toByteArray().filterIndexed { i, _ -> i != 3 }.toByteArray().inputStream()
val result = serializer.deserializeCache(inputStream)
assertNull(result)
}
}
// Kotlin tip: Use the ugly ${'$'} to insert the $ into the multiline string
private val expectedKryoRegistration = """
[10, com.google.common.collect.HashMultimap]
[11, com.intellij.workspaceModel.storage.impl.ConnectionId]
[12, com.intellij.workspaceModel.storage.impl.ImmutableEntitiesBarrel]
[13, com.intellij.workspaceModel.storage.impl.ChildEntityId]
[14, com.intellij.workspaceModel.storage.impl.ParentEntityId]
[15, it.unimi.dsi.fastutil.objects.ObjectOpenHashSet]
[16, com.intellij.workspaceModel.storage.impl.EntityStorageSerializerImpl${'$'}TypeInfo]
[17, java.util.ArrayList]
[18, java.util.HashMap]
[19, com.intellij.util.SmartList]
[20, java.util.LinkedHashMap]
[21, com.intellij.workspaceModel.storage.impl.containers.BidirectionalMap]
[22, com.intellij.workspaceModel.storage.impl.containers.BidirectionalSetMap]
[23, java.util.HashSet]
[24, com.intellij.util.containers.BidirectionalMultiMap]
[25, com.google.common.collect.HashBiMap]
[26, com.intellij.workspaceModel.storage.impl.containers.LinkedBidirectionalMap]
[27, it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap]
[28, it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap]
[29, java.util.Arrays${'$'}ArrayList]
[30, byte[]]
[31, com.intellij.workspaceModel.storage.impl.ImmutableEntityFamily]
[32, com.intellij.workspaceModel.storage.impl.RefsTable]
[33, com.intellij.workspaceModel.storage.impl.containers.ImmutableNonNegativeIntIntBiMap]
[34, com.intellij.workspaceModel.storage.impl.containers.ImmutableIntIntUniqueBiMap]
[35, com.intellij.workspaceModel.storage.impl.indices.VirtualFileIndex]
[36, com.intellij.workspaceModel.storage.impl.indices.EntityStorageInternalIndex]
[37, com.intellij.workspaceModel.storage.impl.indices.PersistentIdInternalIndex]
[38, com.intellij.workspaceModel.storage.impl.containers.ImmutableNonNegativeIntIntMultiMap${'$'}ByList]
[39, int[]]
[40, kotlin.Pair]
[41, com.intellij.workspaceModel.storage.impl.indices.MultimapStorageIndex]
[42, com.intellij.workspaceModel.storage.impl.EntityStorageSerializerImpl${'$'}SerializableEntityId]
[43, com.intellij.workspaceModel.storage.impl.ChangeEntry${'$'}AddEntity]
[44, com.intellij.workspaceModel.storage.impl.ChangeEntry${'$'}RemoveEntity]
[45, com.intellij.workspaceModel.storage.impl.ChangeEntry${'$'}ReplaceEntity]
[46, com.intellij.workspaceModel.storage.impl.ChangeEntry${'$'}ChangeEntitySource]
[47, com.intellij.workspaceModel.storage.impl.ChangeEntry${'$'}ReplaceAndChangeSource]
[48, java.util.LinkedHashSet]
[49, java.util.Collections${'$'}UnmodifiableCollection]
[50, java.util.Collections${'$'}UnmodifiableSet]
[51, java.util.Collections${'$'}UnmodifiableRandomAccessList]
[52, java.util.Collections${'$'}UnmodifiableMap]
[53, java.util.Collections${'$'}EmptyList]
[54, java.util.Collections${'$'}EmptyMap]
[55, java.util.Collections${'$'}EmptySet]
[56, java.util.Collections${'$'}SingletonList]
[57, java.util.Collections${'$'}SingletonMap]
[58, java.util.Collections${'$'}SingletonSet]
[59, com.intellij.util.containers.ContainerUtilRt${'$'}EmptyList]
[60, com.intellij.util.containers.MostlySingularMultiMap${'$'}EmptyMap]
[61, com.intellij.util.containers.MultiMap${'$'}EmptyMap]
[62, kotlin.collections.EmptyMap]
[63, kotlin.collections.EmptyList]
[64, kotlin.collections.EmptySet]
[65, Object[]]
""".trimIndent()
| apache-2.0 | 7b00df3b016aa202dd4126d6eb5d2be9 | 43.767442 | 140 | 0.768312 | 4.744301 | false | true | false | false |
bajdcc/jMiniLang | src/main/kotlin/com/bajdcc/util/lexer/algorithm/impl/NumberTokenizer.kt | 1 | 1980 | package com.bajdcc.util.lexer.algorithm.impl
import com.bajdcc.util.lexer.algorithm.TokenAlgorithm
import com.bajdcc.util.lexer.error.RegexException
import com.bajdcc.util.lexer.regex.IRegexStringIterator
import com.bajdcc.util.lexer.token.Token
import com.bajdcc.util.lexer.token.TokenType
import java.math.BigDecimal
/**
* 数字解析
*
* @author bajdcc
*/
class NumberTokenizer @Throws(RegexException::class)
constructor() : TokenAlgorithm(regexString, null) {
override val greedMode: Boolean
get() = true
/*
* (非 Javadoc)
*
* @see
* com.bajdcc.lexer.algorithm.ITokenAlgorithm#getToken(java.lang.String,
* com.bajdcc.lexer.token.Token)
*/
override fun getToken(string: String, token: Token, iterator: IRegexStringIterator): Token? {
if (string.startsWith("0x")) {
try {
token.obj = java.lang.Long.parseLong(string.substring(2).toLowerCase(), 0x10)
token.type = TokenType.INTEGER
} catch (e: NumberFormatException) {
e.printStackTrace()
return null
}
} else {
try {
val decimal = BigDecimal(string)
token.obj = decimal
if (string.indexOf('.') == -1) {
token.obj = decimal.toBigIntegerExact().toLong()
token.type = TokenType.INTEGER
} else {
token.obj = decimal.toDouble()
token.type = TokenType.DECIMAL
}
} catch (e: ArithmeticException) {
e.printStackTrace()
return null
} catch (e: NumberFormatException) {
e.printStackTrace()
return null
}
}
return token
}
companion object {
val regexString: String
get() = "[+-]?(\\d*\\.?\\d+|\\d+\\.?\\d*|0x[0-9ABCDEFabcdef]{1,4})([eE][+-]?\\d+)?"
}
}
| mit | 4d8d857722cb7a27f34f002f273e8284 | 28.787879 | 97 | 0.556968 | 4.339956 | false | false | false | false |
chengpo/number-speller | ocr/src/main/java/com/monkeyapp/numbers/ocrcapture/CameraSourcePreview.kt | 1 | 5100 | /*
MIT License
Copyright (c) 2017 - 2021 Po Cheng
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.monkeyapp.numbers.ocrcapture
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import androidx.core.app.ActivityCompat
import android.util.AttributeSet
import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.ViewGroup
import com.google.android.gms.common.images.Size
import com.monkeyapp.numbers.apphelpers.isPortraitMode
import java.io.IOException
private const val TAG = "CameraSourcePreview"
private const val DEFAULT_VIEW_WIDTH = 320
private const val DEFAULT_VIEW_HEIGHT = 240
@JvmField val DEFAULT_VIEW_SIZE = Size(DEFAULT_VIEW_WIDTH, DEFAULT_VIEW_HEIGHT)
class CameraSourcePreview @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
: ViewGroup(context, attrs, defStyleAttr) {
private val surfaceView = SurfaceView(context)
private var cameraSource: CameraSource? = null
private var isSurfaceAvailable: Boolean = false
private var isStartRequested: Boolean = false
init {
surfaceView.holder.addCallback(object: SurfaceHolder.Callback {
override fun surfaceCreated(holder: SurfaceHolder) {
isSurfaceAvailable = true
startIfReady()
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
isSurfaceAvailable = false
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
}
})
addView(surfaceView)
}
fun setCameraSource(_cameraSource: CameraSource?) {
if (_cameraSource == null) {
return
}
cameraSource = _cameraSource
isStartRequested = true
startIfReady()
}
@SuppressLint("MissingPermission")
fun startIfReady() {
try {
val permissions = ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA)
if (permissions == PackageManager.PERMISSION_GRANTED) {
if (isStartRequested and isSurfaceAvailable) {
cameraSource!!.start(surfaceView.holder)
isStartRequested = false
}
}
} catch (e: IOException) {
Log.e(TAG, "Failed to setCameraSource camera due to IOException")
} catch (e: SecurityException) {
Log.e(TAG, "Failed to setCameraSource camera due to SecurityException")
}
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
val size = cameraSource?.previewSize ?: DEFAULT_VIEW_SIZE
var previewWidth = size.width
var previewHeight = size.height
if (isPortraitMode) {
val tmp = previewWidth
previewWidth = previewHeight
previewHeight = tmp
}
val viewWidth = right - left
val viewHeight = bottom - top
val widthRatio = viewWidth.toFloat() / previewWidth.toFloat()
val heightRatio = viewHeight.toFloat() / previewHeight.toFloat()
val childWidth: Int
val childHeight: Int
val childXOffset: Int
val childYOffset: Int
if (widthRatio > heightRatio) {
childWidth = viewWidth
childHeight= (previewHeight * widthRatio).toInt()
childXOffset = 0
childYOffset = (childHeight - viewHeight) / 2
} else {
childWidth = (previewWidth * heightRatio).toInt()
childHeight = viewHeight
childXOffset = (childWidth - viewWidth) / 2
childYOffset = 0
}
for (i in 0 until childCount) {
getChildAt(i)
.layout(-1 * childXOffset,
-1 * childYOffset,
childWidth - childXOffset,
childHeight - childYOffset)
}
startIfReady()
}
}
| mit | ed8d137018d7ac4f92bbc4d648e58be1 | 33.931507 | 121 | 0.663333 | 5.024631 | false | false | false | false |
KotlinNLP/SimpleDNN | src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/attention/scaleddot/ScaledDotAttentionLayerParameters.kt | 1 | 2815 | /* Copyright 2020-present Simone Cangialosi. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.core.layers.models.attention.scaleddot
import com.kotlinnlp.simplednn.core.arrays.ParamsArray
import com.kotlinnlp.simplednn.core.functionalities.initializers.GlorotInitializer
import com.kotlinnlp.simplednn.core.functionalities.initializers.Initializer
import com.kotlinnlp.simplednn.core.layers.LayerParameters
import com.kotlinnlp.simplednn.core.layers.models.LinearParams
import kotlin.math.sqrt
/**
* The parameters of the Scaled-Dot Attention Layer.
*
* @property inputSize the size of each element of the input sequence
* @property attentionSize the size of each element of the attention sequence
* @property outputSize the size of each element of the output sequence
* @param weightsInitializer the initializer of the weights (zeros if null, default: Glorot)
* @param biasesInitializer the initializer of the biases (zeros if null, default: Glorot)
*/
class ScaledDotAttentionLayerParameters(
inputSize: Int,
val attentionSize: Int,
outputSize: Int,
weightsInitializer: Initializer? = GlorotInitializer(),
biasesInitializer: Initializer? = GlorotInitializer()
) : LayerParameters(
inputSize = inputSize,
outputSize = outputSize,
weightsInitializer = weightsInitializer,
biasesInitializer = biasesInitializer
) {
companion object {
/**
* Private val used to serialize the class (needed by Serializable).
*/
@Suppress("unused")
private const val serialVersionUID: Long = 1L
}
/**
* The multiplying factor of the attention calculation.
*/
internal val attentionFactor: Double = 1.0 / sqrt(this.attentionSize.toDouble())
/**
* The queries trainable parameter.
*/
val queries = LinearParams(inputSize = inputSize, outputSize = this.attentionSize)
/**
* The keys trainable parameter.
*/
val keys = LinearParams(inputSize = inputSize, outputSize = this.attentionSize)
/**
* The values trainable parameter.
*/
val values = LinearParams(inputSize = inputSize, outputSize = this.outputSize)
/**
* The list of weights parameters.
*/
override val weightsList: List<ParamsArray> = listOf(
this.queries.weights,
this.keys.weights,
this.values.weights
)
/**
* The list of biases parameters.
*/
override val biasesList: List<ParamsArray> = listOf(
this.queries.biases,
this.keys.biases,
this.values.biases
)
/**
* Initialize all parameters values.
*/
init {
this.initialize()
}
}
| mpl-2.0 | fa383501a5d7b53d753dcd64dccd561d | 29.597826 | 92 | 0.716163 | 4.454114 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/PreviewModeSelectorPopup.kt | 1 | 1705 | package org.wordpress.android.ui
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.view.Gravity
import android.view.View
import androidx.appcompat.widget.ListPopupWindow
import com.google.android.material.elevation.ElevationOverlayProvider
import org.wordpress.android.R.dimen
/**
* Implements the preview mode popup
*/
class PreviewModeSelectorPopup(val context: Context, val button: View) : ListPopupWindow(context) {
init {
val resources = context.resources
val popupOffset = resources.getDimensionPixelSize(dimen.margin_extra_large)
width = resources.getDimensionPixelSize(dimen.web_preview_mode_popup_width)
setDropDownGravity(Gravity.END)
anchorView = button
horizontalOffset = -popupOffset
verticalOffset = popupOffset
isModal = true
val popupBackgroundColor = ElevationOverlayProvider(context).compositeOverlayWithThemeSurfaceColorIfNeeded(
resources.getDimension(dimen.popup_over_toolbar_elevation)
)
setBackgroundDrawable(ColorDrawable(popupBackgroundColor))
}
fun show(handler: PreviewModeHandler) {
button.post(Runnable {
setAdapter(PreviewModeMenuAdapter(context, handler.selectedPreviewMode()))
setOnItemClickListener { parent, _, position, _ ->
dismiss()
val adapter = parent.adapter as PreviewModeMenuAdapter
val selected = adapter.getItem(position)
if (selected !== handler.selectedPreviewMode()) {
handler.onPreviewModeChanged(selected)
}
}
show()
})
}
}
| gpl-2.0 | c980f9191222cf80845f211e979683e5 | 37.75 | 115 | 0.68915 | 5.166667 | false | false | false | false |
DiUS/pact-jvm | core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/RequestMatchResult.kt | 1 | 1691 | package au.com.dius.pact.core.matchers
data class RequestMatchResult(
val method: MethodMismatch?,
val path: PathMismatch?,
val query: List<QueryMatchResult>,
val cookie: CookieMismatch?,
val headers: List<HeaderMatchResult>,
val body: BodyMatchResult
) {
val mismatches: List<Mismatch>
get() {
val list = mutableListOf<Mismatch>()
if (method != null) {
list.add(method)
}
if (path != null) {
list.add(path)
}
list.addAll(query.flatMap { it.result })
if (cookie != null) {
list.add(cookie)
}
list.addAll(headers.flatMap { it.result })
list.addAll(body.mismatches)
return list
}
fun matchedOk() = method == null && path == null && query.all { it.result.isEmpty() } && cookie == null &&
headers.all { it.result.isEmpty() } && body.matchedOk()
fun matchedMethodAndPath() = method == null && path == null
fun calculateScore(): Int {
var score = 0
if (method == null) {
score += 1
} else {
score -= 1
}
if (path == null) {
score += 1
} else {
score -= 1
}
query.forEach {
if (it.result.isEmpty()) {
score += 1
} else {
score -= 1
}
}
if (cookie == null) {
score += 1
} else {
score -= 1
}
headers.forEach {
if (it.result.isEmpty()) {
score += 1
} else {
score -= 1
}
}
if (body.typeMismatch != null) {
score -= 1
} else {
body.bodyResults.forEach {
if (it.result.isEmpty()) {
score += 1
} else {
score -= 1
}
}
}
return score
}
}
| apache-2.0 | 9d396ceb87083accc131222e0623aab8 | 20.679487 | 108 | 0.51508 | 3.808559 | false | false | false | false |
mvysny/vaadin-on-kotlin | vok-util-vaadin/src/main/kotlin/eu/vaadinonkotlin/vaadin/Session.kt | 1 | 4311 | package eu.vaadinonkotlin.vaadin
import com.vaadin.flow.server.VaadinRequest
import com.vaadin.flow.server.VaadinResponse
import com.vaadin.flow.server.VaadinService
import com.vaadin.flow.server.VaadinSession
import java.io.Serializable
import javax.servlet.http.Cookie
import kotlin.reflect.KClass
/**
* A namespace object for attaching your session objects.
*
* WARNING: you can only read the property while holding the Vaadin UI lock (that is, there is current session available).
*/
public object Session {
/**
* Returns the current [VaadinSession]; fails if there is no session, most probably since we are not in the UI thread.
*/
public val current: VaadinSession get() = VaadinSession.getCurrent() ?: throw IllegalStateException("Not in UI thread")
/**
* Returns the attribute stored in this session under given key.
* @param key the key
* @return the attribute value, may be null
*/
public operator fun get(key: String): Any? = current.getAttribute(key)
/**
* Returns the attribute stored in this session under given key.
* @param key the key
* @return the attribute value, may be null
*/
public operator fun <T: Any> get(key: KClass<T>): T? = current.getAttribute(key.java)
/**
* Stores given value under given key in a session. Removes the mapping if value is null
* @param key the key
* @param value the value to store, may be null if
*/
public operator fun set(key: String, value: Any?) {
current.setAttribute(key, value)
}
/**
* Stores given value under given key in a session. Removes the mapping if value is null
* @param key the key
* @param value the value to store, may be null if
*/
public operator fun <T: Any> set(key: KClass<T>, value: T?) {
current.setAttribute(key.java, value)
}
@Deprecated("The service is stored under the key T, however it's up to Kotlin to guess the value of T. Please use the other getOrPut() function and specify T explicitly")
public inline fun <reified T: Serializable> getOrPut(noinline defaultValue: () -> T): T = getOrPut(T::class, defaultValue)
/**
* Retrieves the class stored under its class name as the [key] from the session; if it's not yet there calls [defaultValue] block to create it.
* @return the session-bound instance
*/
public fun <T: Serializable> getOrPut(key: KClass<T>, defaultValue: ()->T): T {
val value: T? = get(key)
return if (value == null) {
val answer: T = defaultValue()
set(key, answer)
answer
} else {
value
}
}
}
public val currentRequest: VaadinRequest get() = VaadinService.getCurrentRequest() ?: throw IllegalStateException("No current request")
public val currentResponse: VaadinResponse get() = VaadinService.getCurrentResponse() ?: throw IllegalStateException("No current response")
/**
* You can use `Cookies["mycookie"]` to retrieve a cookie named "mycookie" (or null if no such cookie exists.
* You can also use `Cookies += cookie` to add a pre-created cookie to a session.
*/
public object Cookies {
/**
* Finds a cookie by name.
* @param name cookie name
* @return cookie or null if there is no such cookie.
*/
public operator fun get(name: String): Cookie? = currentRequest.cookies?.firstOrNull { it.name == name }
/**
* Overwrites given cookie, or deletes it.
* @param name cookie name
* @param cookie the cookie to overwrite. If null, the cookie is deleted.
*/
public operator fun set(name: String, cookie: Cookie?) {
if (cookie == null) {
val newCookie = Cookie(name, null)
newCookie.maxAge = 0 // delete immediately
newCookie.path = "/"
currentResponse.addCookie(newCookie)
} else {
currentResponse.addCookie(cookie)
}
}
/**
* Deletes cookie with given [name]. Does nothing if there is no such cookie.
*/
public fun delete(name: String) {
set(name, null)
}
}
public infix operator fun Cookies.plusAssign(cookie: Cookie) {
set(cookie.name, cookie)
}
public infix operator fun Cookies.minusAssign(cookie: Cookie) {
set(cookie.name, null)
}
| mit | 0bc65f1890ac3d939aa43a4e1629b6eb | 35.226891 | 174 | 0.661563 | 4.226471 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/pullUpConflictsUtils.kt | 1 | 13612 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.pullUp
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.RefactoringBundle
import com.intellij.util.containers.MultiMap
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.refactoring.checkConflictsInteractively
import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberInfo
import org.jetbrains.kotlin.idea.refactoring.memberInfo.getChildrenToAnalyze
import org.jetbrains.kotlin.idea.refactoring.memberInfo.resolveToDescriptorWrapperAware
import org.jetbrains.kotlin.idea.references.KtReference
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.references.resolveToDescriptors
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.resolve.languageVersionSettings
import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest
import org.jetbrains.kotlin.idea.search.declarationsSearch.searchInheritors
import org.jetbrains.kotlin.idea.base.util.useScope
import org.jetbrains.kotlin.idea.util.*
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.renderer.ParameterNameRenderingPolicy
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.util.findCallableMemberBySignature
fun checkConflicts(
project: Project,
sourceClass: KtClassOrObject,
targetClass: PsiNamedElement,
memberInfos: List<KotlinMemberInfo>,
onShowConflicts: () -> Unit = {},
onAccept: () -> Unit
) {
val conflicts = MultiMap<PsiElement, String>()
val conflictsCollected = runProcessWithProgressSynchronously(RefactoringBundle.message("detecting.possible.conflicts"), project) {
runReadAction { collectConflicts(sourceClass, targetClass, memberInfos, conflicts) }
}
if (conflictsCollected) {
project.checkConflictsInteractively(conflicts, onShowConflicts, onAccept)
} else {
onShowConflicts()
}
}
private fun runProcessWithProgressSynchronously(
progressTitle: @NlsContexts.ProgressTitle String,
project: Project?,
process: Runnable,
): Boolean = ProgressManager.getInstance().runProcessWithProgressSynchronously(process, progressTitle, true, project)
private fun collectConflicts(
sourceClass: KtClassOrObject,
targetClass: PsiNamedElement,
memberInfos: List<KotlinMemberInfo>,
conflicts: MultiMap<PsiElement, String>
) {
val pullUpData = KotlinPullUpData(sourceClass,
targetClass,
memberInfos.mapNotNull { it.member })
with(pullUpData) {
for (memberInfo in memberInfos) {
val member = memberInfo.member
val memberDescriptor = member.resolveToDescriptorWrapperAware(resolutionFacade)
checkClashWithSuperDeclaration(member, memberDescriptor, conflicts)
checkAccidentalOverrides(member, memberDescriptor, conflicts)
checkInnerClassToInterface(member, memberDescriptor, conflicts)
checkVisibility(memberInfo, memberDescriptor, conflicts, resolutionFacade.languageVersionSettings)
}
}
checkVisibilityInAbstractedMembers(memberInfos, pullUpData.resolutionFacade, conflicts)
}
internal fun checkVisibilityInAbstractedMembers(
memberInfos: List<KotlinMemberInfo>,
resolutionFacade: ResolutionFacade,
conflicts: MultiMap<PsiElement, String>
) {
val membersToMove = ArrayList<KtNamedDeclaration>()
val membersToAbstract = ArrayList<KtNamedDeclaration>()
for (memberInfo in memberInfos) {
val member = memberInfo.member ?: continue
(if (memberInfo.isToAbstract) membersToAbstract else membersToMove).add(member)
}
for (member in membersToAbstract) {
val memberDescriptor = member.resolveToDescriptorWrapperAware(resolutionFacade)
member.forEachDescendantOfType<KtSimpleNameExpression> {
val target = it.mainReference.resolve() as? KtNamedDeclaration ?: return@forEachDescendantOfType
if (!willBeMoved(target, membersToMove)) return@forEachDescendantOfType
if (target.hasModifier(KtTokens.PRIVATE_KEYWORD)) {
val targetDescriptor = target.resolveToDescriptorWrapperAware(resolutionFacade)
val memberText = memberDescriptor.renderForConflicts()
val targetText = targetDescriptor.renderForConflicts()
val message = KotlinBundle.message("text.0.uses.1.which.will.not.be.accessible.from.subclass", memberText, targetText)
conflicts.putValue(target, message.capitalize())
}
}
}
}
internal fun willBeMoved(element: PsiElement, membersToMove: Collection<KtNamedDeclaration>) =
element.parentsWithSelf.any { it in membersToMove }
internal fun willBeUsedInSourceClass(
member: PsiElement,
sourceClass: KtClassOrObject,
membersToMove: Collection<KtNamedDeclaration>
): Boolean {
return !ReferencesSearch
.search(member, LocalSearchScope(sourceClass), false)
.all { willBeMoved(it.element, membersToMove) }
}
private val CALLABLE_RENDERER = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.withOptions {
parameterNameRenderingPolicy = ParameterNameRenderingPolicy.NONE
modifiers = emptySet()
startFromName = false
}
@Nls
fun DeclarationDescriptor.renderForConflicts(): String {
return when (this) {
is ClassDescriptor -> {
@NlsSafe val text = "${DescriptorRenderer.getClassifierKindPrefix(this)} " +
IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(this)
text
}
is FunctionDescriptor -> {
KotlinBundle.message("text.function.in.ticks.0", CALLABLE_RENDERER.render(this))
}
is PropertyDescriptor -> {
KotlinBundle.message("text.property.in.ticks.0", CALLABLE_RENDERER.render(this))
}
is PackageFragmentDescriptor -> {
@NlsSafe val text = fqName.asString()
text
}
is PackageViewDescriptor -> {
@NlsSafe val text = fqName.asString()
text
}
else -> {
""
}
}
}
internal fun KotlinPullUpData.getClashingMemberInTargetClass(memberDescriptor: CallableMemberDescriptor): CallableMemberDescriptor? {
val memberInSuper = memberDescriptor.substitute(sourceToTargetClassSubstitutor) ?: return null
return targetClassDescriptor.findCallableMemberBySignature(memberInSuper as CallableMemberDescriptor)
}
private fun KotlinPullUpData.checkClashWithSuperDeclaration(
member: KtNamedDeclaration,
memberDescriptor: DeclarationDescriptor,
conflicts: MultiMap<PsiElement, String>
) {
val message = KotlinBundle.message(
"text.class.0.already.contains.member.1",
targetClassDescriptor.renderForConflicts(),
memberDescriptor.renderForConflicts()
)
if (member is KtParameter) {
if (((targetClass as? KtClass)?.primaryConstructorParameters ?: emptyList()).any { it.name == member.name }) {
conflicts.putValue(member, message.capitalize())
}
return
}
if (memberDescriptor !is CallableMemberDescriptor) return
val clashingSuper = getClashingMemberInTargetClass(memberDescriptor) ?: return
if (clashingSuper.modality == Modality.ABSTRACT) return
if (clashingSuper.kind != CallableMemberDescriptor.Kind.DECLARATION) return
conflicts.putValue(member, message.capitalize())
}
private fun PsiClass.isSourceOrTarget(data: KotlinPullUpData): Boolean {
var element = unwrapped
if (element is KtObjectDeclaration && element.isCompanion()) element = element.containingClassOrObject
return element == data.sourceClass || element == data.targetClass
}
private fun KotlinPullUpData.checkAccidentalOverrides(
member: KtNamedDeclaration,
memberDescriptor: DeclarationDescriptor,
conflicts: MultiMap<PsiElement, String>
) {
if (memberDescriptor is CallableDescriptor && !member.hasModifier(KtTokens.PRIVATE_KEYWORD)) {
val memberDescriptorInTargetClass = memberDescriptor.substitute(sourceToTargetClassSubstitutor)
if (memberDescriptorInTargetClass != null) {
val sequence = HierarchySearchRequest<PsiElement>(targetClass, targetClass.useScope())
.searchInheritors()
.asSequence()
.filterNot { it.isSourceOrTarget(this) }
.mapNotNull { it.unwrapped as? KtClassOrObject }
for (it in sequence) {
val subClassDescriptor = it.resolveToDescriptorWrapperAware(resolutionFacade) as ClassDescriptor
val substitution = getTypeSubstitution(targetClassDescriptor.defaultType, subClassDescriptor.defaultType).orEmpty()
val memberDescriptorInSubClass = memberDescriptorInTargetClass.substitute(substitution) as? CallableMemberDescriptor
val clashingMemberDescriptor = memberDescriptorInSubClass?.let {
subClassDescriptor.findCallableMemberBySignature(it)
} ?: continue
val clashingMember = clashingMemberDescriptor.source.getPsi() ?: continue
val message = KotlinBundle.message(
"text.member.0.in.super.class.will.clash.with.existing.member.of.1",
memberDescriptor.renderForConflicts(),
it.resolveToDescriptorWrapperAware(resolutionFacade).renderForConflicts()
)
conflicts.putValue(clashingMember, message.capitalize())
}
}
}
}
private fun KotlinPullUpData.checkInnerClassToInterface(
member: KtNamedDeclaration,
memberDescriptor: DeclarationDescriptor,
conflicts: MultiMap<PsiElement, String>
) {
if (isInterfaceTarget && memberDescriptor is ClassDescriptor && memberDescriptor.isInner) {
val message = KotlinBundle.message("text.inner.class.0.cannot.be.moved.to.intefrace", memberDescriptor.renderForConflicts())
conflicts.putValue(member, message.capitalize())
}
}
private fun KotlinPullUpData.checkVisibility(
memberInfo: KotlinMemberInfo,
memberDescriptor: DeclarationDescriptor,
conflicts: MultiMap<PsiElement, String>,
languageVersionSettings: LanguageVersionSettings
) {
fun reportConflictIfAny(targetDescriptor: DeclarationDescriptor, languageVersionSettings: LanguageVersionSettings) {
if (targetDescriptor in memberDescriptors.values) return
val target = (targetDescriptor as? DeclarationDescriptorWithSource)?.source?.getPsi() ?: return
if (targetDescriptor is DeclarationDescriptorWithVisibility
&& !DescriptorVisibilityUtils.isVisibleIgnoringReceiver(targetDescriptor, targetClassDescriptor, languageVersionSettings)
) {
val message = RefactoringBundle.message(
"0.uses.1.which.is.not.accessible.from.the.superclass",
memberDescriptor.renderForConflicts(),
targetDescriptor.renderForConflicts()
)
conflicts.putValue(target, message.capitalize())
}
}
val member = memberInfo.member
val childrenToCheck = memberInfo.getChildrenToAnalyze()
if (memberInfo.isToAbstract && member is KtCallableDeclaration) {
if (member.typeReference == null) {
(memberDescriptor as CallableDescriptor).returnType?.let { returnType ->
val typeInTargetClass = sourceToTargetClassSubstitutor.substitute(returnType, Variance.INVARIANT)
val descriptorToCheck = typeInTargetClass?.constructor?.declarationDescriptor as? ClassDescriptor
if (descriptorToCheck != null) {
reportConflictIfAny(descriptorToCheck, languageVersionSettings)
}
}
}
}
childrenToCheck.forEach { children ->
children.accept(
object : KtTreeVisitorVoid() {
override fun visitReferenceExpression(expression: KtReferenceExpression) {
super.visitReferenceExpression(expression)
val context = resolutionFacade.analyze(expression)
expression.references
.flatMap { (it as? KtReference)?.resolveToDescriptors(context) ?: emptyList() }
.forEach { reportConflictIfAny(it, languageVersionSettings) }
}
}
)
}
}
| apache-2.0 | 16617200ccd4c082f9c538860f2acf07 | 43.338762 | 158 | 0.725022 | 5.497577 | false | false | false | false |
dholmes215/JToyCalc | src/main/java/us/dholmes/toycalc/kotlin/KotlinSwingCalculator.kt | 1 | 4630 | /**
* Copyright (C) 2018 David A Holmes Jr
*
* This file is part of JToyCalc.
*
* JToyCalc 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.
*
* JToyCalc 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 JToyCalc. If not, see <http://www.gnu.org/licenses/>.
*/
package us.dholmes.toycalc.kotlin
import us.dholmes.toycalc.Calculator
import java.awt.Component
import java.awt.Container
import java.awt.GridBagConstraints
import java.awt.GridBagLayout
import java.awt.event.ActionEvent
import java.util.ArrayList
import javax.swing.*
private fun createAndShowGui() {
val calculator = Calculator()
val layout = GridBagLayout()
val frame = JFrame("Kotlin Swing Calculator")
frame.layout = layout
frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
val displayLabel = JLabel(calculator.displayString)
displayLabel.font = displayLabel.font.deriveFont(48.0f)
displayLabel.horizontalAlignment = SwingConstants.RIGHT
calculator.addDisplayListener { s: String -> displayLabel.text = s }
addComponentWithConstraints(frame, displayLabel, 0, 0, 4, 1)
val digitButtons = ArrayList<JButton>()
for (i in 0..9) {
digitButtons.add(createDigitButton(i, calculator))
}
addComponentWithConstraints(frame, digitButtons[0], 0, 4, 2, 1)
addComponentWithConstraints(frame, digitButtons[1], 0, 3, 1, 1)
addComponentWithConstraints(frame, digitButtons[2], 1, 3, 1, 1)
addComponentWithConstraints(frame, digitButtons[3], 2, 3, 1, 1)
addComponentWithConstraints(frame, digitButtons[4], 0, 2, 1, 1)
addComponentWithConstraints(frame, digitButtons[5], 1, 2, 1, 1)
addComponentWithConstraints(frame, digitButtons[6], 2, 2, 1, 1)
addComponentWithConstraints(frame, digitButtons[7], 0, 1, 1, 1)
addComponentWithConstraints(frame, digitButtons[8], 1, 1, 1, 1)
addComponentWithConstraints(frame, digitButtons[9], 2, 1, 1, 1)
val addButton = createButton("+", 32.0f,
{ _: ActionEvent -> calculator.pressOperation(Calculator.Operation.Add) })
val subButton = createButton("-", 32.0f,
{ _: ActionEvent -> calculator.pressOperation(Calculator.Operation.Subtract) })
val mulButton = createButton("\u00d7", 32.0f,
{ _: ActionEvent -> calculator.pressOperation(Calculator.Operation.Multiply) })
val difButton = createButton("\u00f7", 32.0f,
{ _: ActionEvent -> calculator.pressOperation(Calculator.Operation.Divide) })
val eqButton = createButton("=", 32.0f,
{ _: ActionEvent -> calculator.pressEquals() })
addComponentWithConstraints(frame, addButton, 3, 1, 1, 1)
addComponentWithConstraints(frame, subButton, 3, 2, 1, 1)
addComponentWithConstraints(frame, mulButton, 3, 3, 1, 1)
addComponentWithConstraints(frame, difButton, 3, 4, 1, 1)
addComponentWithConstraints(frame, eqButton, 2, 4, 1, 1)
frame.setSize(300, 300)
frame.isVisible = true
}
private fun addComponentWithConstraints(container: Container,
component: Component, x: Int, y: Int, width: Int, height: Int) {
val constraints = GridBagConstraints()
constraints.fill = GridBagConstraints.BOTH
constraints.gridx = x
constraints.gridy = y
constraints.gridwidth = width
constraints.gridheight = height
constraints.weightx = 0.5
constraints.weighty = 0.5
container.add(component, constraints)
}
private fun createButton(text: String, fontSize: Float,
listener: (ActionEvent) -> Unit): JButton {
val button = JButton(text)
button.addActionListener(listener)
button.font = button.font.deriveFont(fontSize)
return button
}
private fun createDigitButton(digit: Int, calc: Calculator): JButton {
return createButton("" + digit, 32.0f,
{ _: ActionEvent -> calc.pressDigit(digit) })
}
/**
* @param args Command-line arguments.
*/
fun main(args: Array<String>) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
} catch (e: Exception) {
System.err.println("Error setting look-and-feel: $e")
}
SwingUtilities.invokeLater { createAndShowGui() }
}
| gpl-3.0 | 4a96b8f0e7e4752f75667c40a8c3c2f8 | 36.33871 | 104 | 0.700648 | 4.057844 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/challenge/usecase/FindNextDateForChallengeUseCase.kt | 1 | 1074 | package io.ipoli.android.challenge.usecase
import io.ipoli.android.challenge.entity.Challenge
import io.ipoli.android.common.UseCase
import io.ipoli.android.quest.data.persistence.QuestRepository
import org.threeten.bp.LocalDate
/**
* Created by Polina Zhelyazkova <[email protected]>
* on 3/13/18.
*/
class FindNextDateForChallengeUseCase(private val questRepository: QuestRepository) :
UseCase<FindNextDateForChallengeUseCase.Params, Challenge> {
override fun execute(parameters: Params): Challenge {
val challenge = parameters.challenge
val currentDate = parameters.currentDate
val nextScheduled =
questRepository.findNextScheduledNotCompletedForChallenge(challenge.id, currentDate)
?: return challenge
return challenge.copy(
nextDate = nextScheduled.scheduledDate!!,
nextStartTime = nextScheduled.startTime,
nextDuration = nextScheduled.duration
)
}
data class Params(val challenge: Challenge, val currentDate: LocalDate = LocalDate.now())
} | gpl-3.0 | 3ae6f75e76d98f704f6364b837b98962 | 33.677419 | 96 | 0.729981 | 4.794643 | false | false | false | false |
JetBrains/teamcity-nuget-support | nuget-feed/src/jetbrains/buildServer/nuget/feed/server/packages/NuGetIndexerFeature.kt | 1 | 3665 | package jetbrains.buildServer.nuget.feed.server.packages
import jetbrains.buildServer.controllers.BaseController
import jetbrains.buildServer.controllers.admin.projects.BuildTypeForm
import jetbrains.buildServer.nuget.feed.server.NuGetFeedConstants
import jetbrains.buildServer.nuget.feed.server.NuGetUtils
import jetbrains.buildServer.nuget.feed.server.index.NuGetFeedData
import jetbrains.buildServer.serverSide.*
import jetbrains.buildServer.serverSide.packages.impl.RepositoryManager
import jetbrains.buildServer.web.openapi.PluginDescriptor
import jetbrains.buildServer.web.openapi.WebControllerManager
import org.springframework.web.servlet.ModelAndView
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
class NuGetIndexerFeature(pluginDescriptor: PluginDescriptor,
web: WebControllerManager,
private val myProjectManager: ProjectManager,
private val myRepositoryManager: RepositoryManager) : BuildFeature() {
private val myEditParametersUrl: String
init {
val jsp = pluginDescriptor.getPluginResourcesPath("editNuGetIndexerFeature.jsp")
val html = pluginDescriptor.getPluginResourcesPath("nugetIndexerSettings.html")
web.registerController(html, object : BaseController() {
override fun doHandle(request: HttpServletRequest, response: HttpServletResponse): ModelAndView? {
val modelAndView = ModelAndView(jsp)
val model = modelAndView.model
val project = getProject(request)
model["feeds"] = myRepositoryManager.getRepositories(project, true)
.filterIsInstance<NuGetRepository>()
.mapNotNull { repository ->
myProjectManager.findProjectById(repository.projectId)?.let {
ProjectFeed(repository, it)
}
}
return modelAndView
}
})
myEditParametersUrl = html
}
override fun getType() = NuGetFeedConstants.NUGET_INDEXER_TYPE
override fun getDisplayName() = "NuGet packages indexer"
override fun getEditParametersUrl() = myEditParametersUrl
override fun isMultipleFeaturesPerBuildTypeAllowed(): Boolean {
return true
}
override fun isRequiresAgent() = false
private fun getProject(request: HttpServletRequest): SProject {
val buildTypeForm = request.getAttribute("buildForm") as BuildTypeForm
return buildTypeForm.project
}
override fun describeParameters(parameters: MutableMap<String, String>): String {
val feedName = parameters[NuGetFeedConstants.NUGET_INDEXER_FEED]?.let {
NuGetUtils.feedIdToData(it)?.let { feed ->
myProjectManager.findProjectByExternalId(feed.first)?.let {
if (feed.second == NuGetFeedData.DEFAULT_FEED_ID) "\"${it.name}\" project" else "\"${it.name}/${feed.second}\""
}
}
} ?: "<Unknown>"
return "Indexing packages into $feedName NuGet feed"
}
override fun getParametersProcessor(): PropertiesProcessor? {
return PropertiesProcessor { parameters ->
val invalidProperties = arrayListOf<InvalidProperty>()
NuGetFeedConstants.NUGET_INDEXER_FEED.apply {
if (parameters[this].isNullOrEmpty()) {
invalidProperties.add(InvalidProperty(this, "NuGet feed should not be empty"))
}
}
return@PropertiesProcessor invalidProperties
}
}
}
| apache-2.0 | e9e31aeb5670ec30b05b7714b83b2073 | 40.647727 | 131 | 0.674761 | 5.350365 | false | false | false | false |
GunoH/intellij-community | platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/library/ProjectModifiableLibraryTableBridgeImpl.kt | 2 | 6003 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide.impl.legacyBridge.library
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectModelExternalSource
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.LibraryProperties
import com.intellij.openapi.roots.libraries.PersistentLibraryKind
import com.intellij.openapi.util.Disposer
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.ide.impl.JpsEntitySourceFactory
import com.intellij.workspaceModel.ide.impl.legacyBridge.LegacyBridgeModifiableBase
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.findLibraryEntity
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.libraryMap
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.mutableLibraryMap
import com.intellij.workspaceModel.ide.legacyBridge.ProjectModifiableLibraryTableBridge
import com.intellij.workspaceModel.storage.CachedValue
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.addLibraryEntity
import com.intellij.workspaceModel.storage.bridgeEntities.addLibraryPropertiesEntity
import com.intellij.workspaceModel.storage.bridgeEntities.LibraryEntity
import com.intellij.workspaceModel.storage.bridgeEntities.LibraryId
import com.intellij.workspaceModel.storage.bridgeEntities.LibraryTableId
import org.jetbrains.jps.model.serialization.library.JpsLibraryTableSerializer
internal class ProjectModifiableLibraryTableBridgeImpl(
originalStorage: EntityStorage,
private val libraryTable: ProjectLibraryTableBridgeImpl,
private val project: Project,
diff: MutableEntityStorage = MutableEntityStorage.from(originalStorage),
cacheStorageResult: Boolean = true
) : LegacyBridgeModifiableBase(diff, cacheStorageResult), ProjectModifiableLibraryTableBridge {
private val myAddedLibraries = mutableListOf<LibraryBridgeImpl>()
private val librariesArrayValue = CachedValue<Array<Library>> { storage ->
storage.entities(LibraryEntity::class.java).filter { it.tableId == LibraryTableId.ProjectLibraryTableId }
.mapNotNull { storage.libraryMap.getDataByEntity(it) }
.toList().toTypedArray()
}
private val librariesArray: Array<Library>
get() = entityStorageOnDiff.cachedValue(librariesArrayValue)
override fun createLibrary(name: String?): Library = createLibrary(name = name, type = null)
override fun createLibrary(name: String?, type: PersistentLibraryKind<out LibraryProperties<*>>?): Library =
createLibrary(name = name, type = type, externalSource = null)
override fun createLibrary(name: String?,
type: PersistentLibraryKind<out LibraryProperties<*>>?,
externalSource: ProjectModelExternalSource?): Library {
if (name.isNullOrBlank()) error("Project Library must have a name")
assertModelIsLive()
val libraryTableId = LibraryTableId.ProjectLibraryTableId
val libraryEntity = diff.addLibraryEntity(
roots = emptyList(),
tableId = LibraryTableId.ProjectLibraryTableId,
name = name,
excludedRoots = emptyList(),
source = JpsEntitySourceFactory.createEntitySourceForProjectLibrary(project, externalSource)
)
if (type != null) {
diff.addLibraryPropertiesEntity(
library = libraryEntity,
libraryType = type.kindId,
propertiesXmlTag = serializeComponentAsString(JpsLibraryTableSerializer.PROPERTIES_TAG, type.createDefaultProperties())
)
}
val library = LibraryBridgeImpl(
libraryTable = libraryTable,
project = project,
initialId = LibraryId(name, libraryTableId),
initialEntityStorage = entityStorageOnDiff,
targetBuilder = this.diff
)
myAddedLibraries.add(library)
diff.mutableLibraryMap.addMapping(libraryEntity, library)
return library
}
override fun removeLibrary(library: Library) {
assertModelIsLive()
val libraryEntity = entityStorageOnDiff.current.findLibraryEntity(library as LibraryBridge)
if (libraryEntity != null) {
diff.removeEntity(libraryEntity)
if (myAddedLibraries.remove(library)) {
Disposer.dispose(library)
}
}
}
override fun commit() {
prepareForCommit()
WorkspaceModel.getInstance(project).updateProjectModel("Project library table commit") {
it.addDiff(diff)
}
}
override fun prepareForCommit() {
assertModelIsLive()
modelIsCommittedOrDisposed = true
val storage = WorkspaceModel.getInstance(project).entityStorage.current
myAddedLibraries.forEach { library ->
if (library.libraryId in storage) {
// it may happen that actual library table already has a library with such name (e.g. when multiple projects are imported in parallel)
// in such case we need to skip the new library to avoid exceptions.
diff.removeEntity(diff.libraryMap.getEntities(library).first())
Disposer.dispose(library)
}
library.clearTargetBuilder()
}
}
override fun getLibraryIterator(): Iterator<Library> = librariesArray.iterator()
override fun getLibraryByName(name: String): Library? {
val libraryEntity = diff.resolve(LibraryId(name, LibraryTableId.ProjectLibraryTableId)) ?: return null
return diff.libraryMap.getDataByEntity(libraryEntity)
}
override fun getLibraries(): Array<Library> = librariesArray
override fun dispose() {
modelIsCommittedOrDisposed = true
myAddedLibraries.forEach { Disposer.dispose(it) }
myAddedLibraries.clear()
}
override fun isChanged(): Boolean = diff.hasChanges()
}
| apache-2.0 | 07e2d13ab94c0346016b500370549818 | 41.878571 | 158 | 0.775779 | 5.251969 | false | false | false | false |
GunoH/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/injection/MarkdownCodeFenceUtils.kt | 7 | 5765 | // 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.injection
import com.intellij.lang.ASTNode
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.templateLanguages.OuterLanguageElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.elementType
import com.intellij.psi.util.siblings
import org.intellij.plugins.markdown.lang.MarkdownTokenTypeSets
import org.intellij.plugins.markdown.lang.MarkdownTokenTypes
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownCodeFence
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownCodeFenceImpl
import org.intellij.plugins.markdown.lang.psi.util.hasType
import org.intellij.plugins.markdown.lang.psi.util.parents
import org.intellij.plugins.markdown.util.MarkdownPsiUtil
/**
* Utility functions used to work with Markdown Code Fences
*/
object MarkdownCodeFenceUtils {
/** Check if [node] is of CODE_FENCE type */
fun isCodeFence(node: ASTNode) = node.hasType(MarkdownTokenTypeSets.CODE_FENCE)
/** Check if [node] inside CODE_FENCE */
fun inCodeFence(node: ASTNode) = node.parents(withSelf = false).any { it.hasType(MarkdownTokenTypeSets.CODE_FENCE) }
/**
* Consider using [MarkdownCodeFence.obtainFenceContent] since it caches its result.
*
* Get content of code fence as list of [PsiElement]
*
* @param withWhitespaces defines if whitespaces (including blockquote chars `>`) should be
* included in returned list. Otherwise, only new-line would be added.
*
* @return non-empty list of elements or null
*/
@JvmStatic
@Deprecated("Use getContent(MarkdownCodeFence) instead.")
fun getContent(host: MarkdownCodeFenceImpl, withWhitespaces: Boolean): List<PsiElement>? {
val children = host.firstChild?.siblings(forward = true, withSelf = true) ?: return null
var elements = children.filter {
(it !is OuterLanguageElement
&& (it.node.elementType == MarkdownTokenTypes.CODE_FENCE_CONTENT
|| (MarkdownPsiUtil.WhiteSpaces.isNewLine(it))
//WHITE_SPACES may also include `>`
|| (withWhitespaces && MarkdownTokenTypeSets.WHITE_SPACES.contains(it.elementType))
)
)
}.toList()
//drop new line right after code fence lang definition
if (elements.isNotEmpty() && MarkdownPsiUtil.WhiteSpaces.isNewLine(elements.first())) {
elements = elements.drop(1)
}
//drop new right before code fence end
if (elements.isNotEmpty() && MarkdownPsiUtil.WhiteSpaces.isNewLine(elements.last())) {
elements = elements.dropLast(1)
}
return elements.takeIf { it.isNotEmpty() }
}
/**
* Consider using [MarkdownCodeFence.obtainFenceContent], since it caches its result.
*/
@JvmStatic
fun getContent(host: MarkdownCodeFence, withWhitespaces: Boolean): List<PsiElement>? {
@Suppress("DEPRECATION")
return getContent(host as MarkdownCodeFenceImpl, withWhitespaces)
}
/**
* Check that code fence is reasonably formatted to accept injections
*
* Basically, it means that it has start and end code fence and at least
* one line (even empty) of text.
*/
@JvmStatic
@Deprecated("Use isAbleToAcceptInjections(MarkdownCodeFence) instead.")
fun isAbleToAcceptInjections(host: MarkdownCodeFenceImpl): Boolean {
if (host.children.all { !it.hasType(MarkdownTokenTypes.CODE_FENCE_END) }
|| host.children.all { !it.hasType(MarkdownTokenTypes.CODE_FENCE_START) }) {
return false
}
val newlines = host.children.count { MarkdownPsiUtil.WhiteSpaces.isNewLine(it) }
return newlines >= 2
}
@JvmStatic
fun isAbleToAcceptInjections(host: MarkdownCodeFence): Boolean {
@Suppress("DEPRECATION")
return isAbleToAcceptInjections(host as MarkdownCodeFenceImpl)
}
/**
* Get valid empty range (in terms of Injection) for this code fence.
*
* Note, that this function should be used only if [getContent]
* returns null
*/
@JvmStatic
@Deprecated("Use getEmptyRange(MarkdownCodeFence) instead.")
fun getEmptyRange(host: MarkdownCodeFenceImpl): TextRange {
val start = host.children.find { it.hasType(MarkdownTokenTypes.FENCE_LANG) }
?: host.children.find { it.hasType(MarkdownTokenTypes.CODE_FENCE_START) }
return TextRange.from(start!!.startOffsetInParent + start.textLength + 1, 0)
}
fun getEmptyRange(host: MarkdownCodeFence): TextRange {
@Suppress("DEPRECATION")
return getEmptyRange(host as MarkdownCodeFenceImpl)
}
/**
* Get code fence if [element] is part of it.
*
* Would also work for injected elements.
*/
fun getCodeFence(element: PsiElement): MarkdownCodeFence? {
return InjectedLanguageManager.getInstance(element.project).getInjectionHost(element) as? MarkdownCodeFence?
?: PsiTreeUtil.getParentOfType(element, MarkdownCodeFence::class.java)
}
/**
* Get indent for this code fence.
*
* If code-fence is blockquoted indent may include `>` char.
* Note that indent should be used only for non top-level fences,
* top-level fences should use indentation from formatter.
*/
@JvmStatic
fun getIndent(element: MarkdownCodeFence): String? {
val document = PsiDocumentManager.getInstance(element.project).getDocument(element.containingFile) ?: return null
val offset = element.textOffset
val lineStartOffset = document.getLineStartOffset(document.getLineNumber(offset))
return document.getText(TextRange.create(lineStartOffset, offset)).replace("[^> ]".toRegex(), " ")
}
} | apache-2.0 | b6b38b20bee42bd0aae199331a469c5f | 39.321678 | 140 | 0.736167 | 4.427803 | false | false | false | false |
himikof/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/RustPsiImplUtil.kt | 1 | 1203 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.stubs.RsVisibilityStub
/**
* Mixin methods to implement PSI interfaces without copy pasting and
* introducing monster base classes. Can be simplified when Kotlin supports
* default methods in interfaces with mixed Kotlin-Java hierarchies (KT-9073 ).
*/
object RustPsiImplUtil {
fun isPublic(psi: RsVisibilityOwner, stub: RsVisibilityStub?): Boolean =
stub?.isPublic ?: isPublicNonStubbed(psi)
fun isPublicNonStubbed(element: RsVisibilityOwner): Boolean =
element.vis != null
fun crateRelativePath(element: RsNamedElement): String? {
val name = element.name ?: return null
val qualifier = element.containingMod.crateRelativePath ?: return null
return "$qualifier::$name"
}
fun modCrateRelativePath(mod: RsMod): String? {
val segments = mod.superMods.asReversed().drop(1).map {
it.modName ?: return null
}
if (segments.isEmpty()) return ""
return "::" + segments.joinToString("::")
}
}
| mit | 8c4ab05f53ac7a01b8ba544b30201697 | 31.513514 | 79 | 0.686617 | 4.34296 | false | false | false | false |
seirion/code | google/2019/round1_a/2/main.kt | 1 | 744 | import java.util.*
fun main(args: Array<String>) {
val (T, N, M) = readLine()!!.split("\\s".toRegex()).map { s -> s.toInt() }
repeat(T) { solve(N, M) }
}
val prime = arrayListOf(5, 7, 9, 11, 13, 16, 17)
fun solve(night: Int, max: Int) {
val response = ArrayList<Int>()
repeat(prime.size) { index ->
println(IntArray(18) { prime[index] }.joinToString(" "))
val v = readLine()!!.split("\\s".toRegex()).map { s -> s.toInt() }.sum() % prime[index]
response.add(v)
}
println(calculate(response, max))
readLine()
}
fun calculate(response: List<Int>, max: Int): Int {
for (v in 1..max) {
if ((0 until prime.size).all { v % prime[it] == response[it] }) return v
}
return 0
}
| apache-2.0 | eee927eaa627121c8d449dc4c8ef7da1 | 26.555556 | 95 | 0.556452 | 3.112971 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/util/system/ImageUtil.kt | 2 | 14969 | package eu.kanade.tachiyomi.util.system
import android.content.Context
import android.content.res.Configuration
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.Rect
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.os.Build
import androidx.core.graphics.alpha
import androidx.core.graphics.applyCanvas
import androidx.core.graphics.blue
import androidx.core.graphics.createBitmap
import androidx.core.graphics.green
import androidx.core.graphics.red
import tachiyomi.decoder.Format
import tachiyomi.decoder.ImageDecoder
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.net.URLConnection
import kotlin.math.abs
object ImageUtil {
fun isImage(name: String, openStream: (() -> InputStream)? = null): Boolean {
val contentType = try {
URLConnection.guessContentTypeFromName(name)
} catch (e: Exception) {
null
} ?: openStream?.let { findImageType(it)?.mime }
return contentType?.startsWith("image/") ?: false
}
fun findImageType(openStream: () -> InputStream): ImageType? {
return openStream().use { findImageType(it) }
}
fun findImageType(stream: InputStream): ImageType? {
try {
return when (getImageType(stream)?.format) {
Format.Avif -> ImageType.AVIF
Format.Gif -> ImageType.GIF
Format.Heif -> ImageType.HEIF
Format.Jpeg -> ImageType.JPEG
Format.Jxl -> ImageType.JXL
Format.Png -> ImageType.PNG
Format.Webp -> ImageType.WEBP
else -> null
}
} catch (e: Exception) {
}
return null
}
fun isAnimatedAndSupported(stream: InputStream): Boolean {
try {
val type = getImageType(stream) ?: return false
return when (type.format) {
Format.Gif -> true
// Coil supports animated WebP on Android 9.0+
// https://coil-kt.github.io/coil/getting_started/#supported-image-formats
Format.Webp -> type.isAnimated && Build.VERSION.SDK_INT >= Build.VERSION_CODES.P
else -> false
}
} catch (e: Exception) {
}
return false
}
private fun getImageType(stream: InputStream): tachiyomi.decoder.ImageType? {
val bytes = ByteArray(32)
val length = if (stream.markSupported()) {
stream.mark(bytes.size)
stream.read(bytes, 0, bytes.size).also { stream.reset() }
} else {
stream.read(bytes, 0, bytes.size)
}
if (length == -1) {
return null
}
return ImageDecoder.findType(bytes)
}
enum class ImageType(val mime: String, val extension: String) {
AVIF("image/avif", "avif"),
GIF("image/gif", "gif"),
HEIF("image/heif", "heif"),
JPEG("image/jpeg", "jpg"),
JXL("image/jxl", "jxl"),
PNG("image/png", "png"),
WEBP("image/webp", "webp"),
}
/**
* Check whether the image is a double-page spread
* @return true if the width is greater than the height
*/
fun isDoublePage(imageStream: InputStream): Boolean {
imageStream.mark(imageStream.available() + 1)
val imageBytes = imageStream.readBytes()
val options = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size, options)
imageStream.reset()
return options.outWidth > options.outHeight
}
/**
* Extract the 'side' part from imageStream and return it as InputStream.
*/
fun splitInHalf(imageStream: InputStream, side: Side): InputStream {
val imageBytes = imageStream.readBytes()
val imageBitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
val height = imageBitmap.height
val width = imageBitmap.width
val singlePage = Rect(0, 0, width / 2, height)
val half = createBitmap(width / 2, height)
val part = when (side) {
Side.RIGHT -> Rect(width - width / 2, 0, width, height)
Side.LEFT -> Rect(0, 0, width / 2, height)
}
half.applyCanvas {
drawBitmap(imageBitmap, part, singlePage, null)
}
val output = ByteArrayOutputStream()
half.compress(Bitmap.CompressFormat.JPEG, 100, output)
return ByteArrayInputStream(output.toByteArray())
}
/**
* Split the image into left and right parts, then merge them into a new image.
*/
fun splitAndMerge(imageStream: InputStream, upperSide: Side): InputStream {
val imageBytes = imageStream.readBytes()
val imageBitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
val height = imageBitmap.height
val width = imageBitmap.width
val result = createBitmap(width / 2, height * 2)
result.applyCanvas {
// right -> upper
val rightPart = when (upperSide) {
Side.RIGHT -> Rect(width - width / 2, 0, width, height)
Side.LEFT -> Rect(0, 0, width / 2, height)
}
val upperPart = Rect(0, 0, width / 2, height)
drawBitmap(imageBitmap, rightPart, upperPart, null)
// left -> bottom
val leftPart = when (upperSide) {
Side.LEFT -> Rect(width - width / 2, 0, width, height)
Side.RIGHT -> Rect(0, 0, width / 2, height)
}
val bottomPart = Rect(0, height, width / 2, height * 2)
drawBitmap(imageBitmap, leftPart, bottomPart, null)
}
val output = ByteArrayOutputStream()
result.compress(Bitmap.CompressFormat.JPEG, 100, output)
return ByteArrayInputStream(output.toByteArray())
}
enum class Side {
RIGHT, LEFT
}
/**
* Algorithm for determining what background to accompany a comic/manga page
*/
fun chooseBackground(context: Context, imageStream: InputStream): Drawable {
val decoder = ImageDecoder.newInstance(imageStream)
val image = decoder?.decode()
decoder?.recycle()
val whiteColor = Color.WHITE
if (image == null) return ColorDrawable(whiteColor)
if (image.width < 50 || image.height < 50) {
return ColorDrawable(whiteColor)
}
val top = 5
val bot = image.height - 5
val left = (image.width * 0.0275).toInt()
val right = image.width - left
val midX = image.width / 2
val midY = image.height / 2
val offsetX = (image.width * 0.01).toInt()
val leftOffsetX = left - offsetX
val rightOffsetX = right + offsetX
val topLeftPixel = image.getPixel(left, top)
val topRightPixel = image.getPixel(right, top)
val midLeftPixel = image.getPixel(left, midY)
val midRightPixel = image.getPixel(right, midY)
val topCenterPixel = image.getPixel(midX, top)
val botLeftPixel = image.getPixel(left, bot)
val bottomCenterPixel = image.getPixel(midX, bot)
val botRightPixel = image.getPixel(right, bot)
val topLeftIsDark = topLeftPixel.isDark()
val topRightIsDark = topRightPixel.isDark()
val midLeftIsDark = midLeftPixel.isDark()
val midRightIsDark = midRightPixel.isDark()
val topMidIsDark = topCenterPixel.isDark()
val botLeftIsDark = botLeftPixel.isDark()
val botRightIsDark = botRightPixel.isDark()
var darkBG = (topLeftIsDark && (botLeftIsDark || botRightIsDark || topRightIsDark || midLeftIsDark || topMidIsDark)) ||
(topRightIsDark && (botRightIsDark || botLeftIsDark || midRightIsDark || topMidIsDark))
val topAndBotPixels = listOf(topLeftPixel, topCenterPixel, topRightPixel, botRightPixel, bottomCenterPixel, botLeftPixel)
val isNotWhiteAndCloseTo = topAndBotPixels.mapIndexed { index, color ->
val other = topAndBotPixels[(index + 1) % topAndBotPixels.size]
!color.isWhite() && color.isCloseTo(other)
}
if (isNotWhiteAndCloseTo.all { it }) {
return ColorDrawable(topLeftPixel)
}
val cornerPixels = listOf(topLeftPixel, topRightPixel, botLeftPixel, botRightPixel)
val numberOfWhiteCorners = cornerPixels.map { cornerPixel -> cornerPixel.isWhite() }
.filter { it }
.size
if (numberOfWhiteCorners > 2) {
darkBG = false
}
var blackColor = when {
topLeftIsDark -> topLeftPixel
topRightIsDark -> topRightPixel
botLeftIsDark -> botLeftPixel
botRightIsDark -> botRightPixel
else -> whiteColor
}
var overallWhitePixels = 0
var overallBlackPixels = 0
var topBlackStreak = 0
var topWhiteStreak = 0
var botBlackStreak = 0
var botWhiteStreak = 0
outer@ for (x in intArrayOf(left, right, leftOffsetX, rightOffsetX)) {
var whitePixelsStreak = 0
var whitePixels = 0
var blackPixelsStreak = 0
var blackPixels = 0
var blackStreak = false
var whiteStreak = false
val notOffset = x == left || x == right
inner@ for ((index, y) in (0 until image.height step image.height / 25).withIndex()) {
val pixel = image.getPixel(x, y)
val pixelOff = image.getPixel(x + (if (x < image.width / 2) -offsetX else offsetX), y)
if (pixel.isWhite()) {
whitePixelsStreak++
whitePixels++
if (notOffset) {
overallWhitePixels++
}
if (whitePixelsStreak > 14) {
whiteStreak = true
}
if (whitePixelsStreak > 6 && whitePixelsStreak >= index - 1) {
topWhiteStreak = whitePixelsStreak
}
} else {
whitePixelsStreak = 0
if (pixel.isDark() && pixelOff.isDark()) {
blackPixels++
if (notOffset) {
overallBlackPixels++
}
blackPixelsStreak++
if (blackPixelsStreak >= 14) {
blackStreak = true
}
continue@inner
}
}
if (blackPixelsStreak > 6 && blackPixelsStreak >= index - 1) {
topBlackStreak = blackPixelsStreak
}
blackPixelsStreak = 0
}
if (blackPixelsStreak > 6) {
botBlackStreak = blackPixelsStreak
} else if (whitePixelsStreak > 6) {
botWhiteStreak = whitePixelsStreak
}
when {
blackPixels > 22 -> {
if (x == right || x == rightOffsetX) {
blackColor = when {
topRightIsDark -> topRightPixel
botRightIsDark -> botRightPixel
else -> blackColor
}
}
darkBG = true
overallWhitePixels = 0
break@outer
}
blackStreak -> {
darkBG = true
if (x == right || x == rightOffsetX) {
blackColor = when {
topRightIsDark -> topRightPixel
botRightIsDark -> botRightPixel
else -> blackColor
}
}
if (blackPixels > 18) {
overallWhitePixels = 0
break@outer
}
}
whiteStreak || whitePixels > 22 -> darkBG = false
}
}
val topIsBlackStreak = topBlackStreak > topWhiteStreak
val bottomIsBlackStreak = botBlackStreak > botWhiteStreak
if (overallWhitePixels > 9 && overallWhitePixels > overallBlackPixels) {
darkBG = false
}
if (topIsBlackStreak && bottomIsBlackStreak) {
darkBG = true
}
val isLandscape = context.resources.configuration?.orientation == Configuration.ORIENTATION_LANDSCAPE
if (isLandscape) {
return when {
darkBG -> ColorDrawable(blackColor)
else -> ColorDrawable(whiteColor)
}
}
val botCornersIsWhite = botLeftPixel.isWhite() && botRightPixel.isWhite()
val topCornersIsWhite = topLeftPixel.isWhite() && topRightPixel.isWhite()
val topCornersIsDark = topLeftIsDark && topRightIsDark
val botCornersIsDark = botLeftIsDark && botRightIsDark
val topOffsetCornersIsDark = image.getPixel(leftOffsetX, top).isDark() && image.getPixel(rightOffsetX, top).isDark()
val botOffsetCornersIsDark = image.getPixel(leftOffsetX, bot).isDark() && image.getPixel(rightOffsetX, bot).isDark()
val gradient = when {
darkBG && botCornersIsWhite -> {
intArrayOf(blackColor, blackColor, whiteColor, whiteColor)
}
darkBG && topCornersIsWhite -> {
intArrayOf(whiteColor, whiteColor, blackColor, blackColor)
}
darkBG -> {
return ColorDrawable(blackColor)
}
topIsBlackStreak || (topCornersIsDark && topOffsetCornersIsDark && (topMidIsDark || overallBlackPixels > 9)) -> {
intArrayOf(blackColor, blackColor, whiteColor, whiteColor)
}
bottomIsBlackStreak || (botCornersIsDark && botOffsetCornersIsDark && (bottomCenterPixel.isDark() || overallBlackPixels > 9)) -> {
intArrayOf(whiteColor, whiteColor, blackColor, blackColor)
}
else -> {
return ColorDrawable(whiteColor)
}
}
return GradientDrawable(
GradientDrawable.Orientation.TOP_BOTTOM,
gradient
)
}
private fun Int.isDark(): Boolean =
red < 40 && blue < 40 && green < 40 && alpha > 200
private fun Int.isCloseTo(other: Int): Boolean =
abs(red - other.red) < 30 && abs(green - other.green) < 30 && abs(blue - other.blue) < 30
private fun Int.isWhite(): Boolean =
red + blue + green > 740
}
| apache-2.0 | 4c8100cad475effb12d6763f91a1b479 | 36.896203 | 142 | 0.566036 | 4.744532 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/browse/source/filter/SeparatorItem.kt | 3 | 1395 | package eu.kanade.tachiyomi.ui.browse.source.filter
import android.annotation.SuppressLint
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.R
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.davidea.flexibleadapter.items.AbstractHeaderItem
import eu.davidea.flexibleadapter.items.IFlexible
import eu.davidea.viewholders.FlexibleViewHolder
import eu.kanade.tachiyomi.source.model.Filter
class SeparatorItem(val filter: Filter.Separator) : AbstractHeaderItem<SeparatorItem.Holder>() {
@SuppressLint("PrivateResource")
override fun getLayoutRes(): Int {
return R.layout.design_navigation_item_separator
}
override fun createViewHolder(view: View, adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>): Holder {
return Holder(view, adapter)
}
override fun bindViewHolder(adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>, holder: Holder, position: Int, payloads: List<Any?>?) {
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
return filter == (other as SeparatorItem).filter
}
override fun hashCode(): Int {
return filter.hashCode()
}
class Holder(view: View, adapter: FlexibleAdapter<*>) : FlexibleViewHolder(view, adapter)
}
| apache-2.0 | b3cd6cc5c158b2d8b1ea6c269f51d622 | 35.710526 | 149 | 0.750538 | 4.665552 | false | false | false | false |
taskworld/KxAndroid | kxandroid-formatter/src/main/kotlin/com/taskworld/kxandroid/formatter/FileSizeFormatter.kt | 1 | 880 | package com.taskworld.kxandroid.formatter
import com.taskworld.kxandroid.rounded
val BYTE_UNIT_VALUE = 1024.0
enum class ByteUnit(open val unitString: String) {
KILO_BYTE("KB"),
MEGA_BYTE("MB"),
GIGA_BYTE("GB");
val divider: Double
get() = Math.pow(BYTE_UNIT_VALUE, (this.ordinal + 1).toDouble())
}
fun Int.toFileSizeString(): String {
return this.toDouble().toFileSizeString()
}
fun Double.toFileSizeString(): String {
val (converted, unit) = convertToFileSizeFormat(this)
return "${converted.rounded(2)} ${unit.unitString}"
}
private fun convertToFileSizeFormat(value: Double): Pair<Double, ByteUnit> {
var convertedValue = 0.0
val unit = ByteUnit.values().reversed().find {
convertedValue = value / it.divider
convertedValue > 1.0
} ?: ByteUnit.values().last()
return Pair(convertedValue, unit)
}
| mit | 747c37aa9fb65fd4cff46471514ad154 | 22.783784 | 76 | 0.679545 | 3.636364 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/test/java/org/hisp/dhis/android/core/organisationunit/OrganisationUnitServiceShould.kt | 1 | 4522 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.organisationunit
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import org.hisp.dhis.android.core.common.BaseIdentifiableObject
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito
class OrganisationUnitServiceShould {
private val organisationUnitUid: String = "organisationUnitUid"
private val organisationUnit: OrganisationUnit = mock()
private val organisationUnitRepository: OrganisationUnitCollectionRepository =
mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS)
private val organisationUnitService = OrganisationUnitService(organisationUnitRepository)
// Dates
private val firstJanuary = BaseIdentifiableObject.DATE_FORMAT.parse("2020-01-01T00:00:00.000")
private val secondJanuary = BaseIdentifiableObject.DATE_FORMAT.parse("2020-01-02T00:00:00.000")
private val thirdJanuary = BaseIdentifiableObject.DATE_FORMAT.parse("2020-01-03T00:00:00.000")
@Before
fun setUp() {
whenever(organisationUnitRepository.uid(organisationUnitUid).blockingGet()) doReturn organisationUnit
whenever(organisationUnit.uid()) doReturn organisationUnitUid
}
@Test
fun `Should return true if date within orgunit range`() {
whenever(organisationUnit.openingDate()) doReturn null
whenever(organisationUnit.closedDate()) doReturn null
assertTrue(organisationUnitService.blockingIsDateInOrgunitRange(organisationUnitUid, secondJanuary))
whenever(organisationUnit.openingDate()) doReturn firstJanuary
whenever(organisationUnit.closedDate()) doReturn null
assertTrue(organisationUnitService.blockingIsDateInOrgunitRange(organisationUnitUid, secondJanuary))
whenever(organisationUnit.openingDate()) doReturn null
whenever(organisationUnit.closedDate()) doReturn thirdJanuary
assertTrue(organisationUnitService.blockingIsDateInOrgunitRange(organisationUnitUid, secondJanuary))
whenever(organisationUnit.openingDate()) doReturn firstJanuary
whenever(organisationUnit.closedDate()) doReturn thirdJanuary
assertTrue(organisationUnitService.blockingIsDateInOrgunitRange(organisationUnitUid, secondJanuary))
}
@Test
fun `Should return false if date out of orgunit range`() {
whenever(organisationUnit.openingDate()) doReturn thirdJanuary
whenever(organisationUnit.closedDate()) doReturn null
assertFalse(organisationUnitService.blockingIsDateInOrgunitRange(organisationUnitUid, secondJanuary))
whenever(organisationUnit.openingDate()) doReturn null
whenever(organisationUnit.closedDate()) doReturn firstJanuary
assertFalse(organisationUnitService.blockingIsDateInOrgunitRange(organisationUnitUid, secondJanuary))
}
}
| bsd-3-clause | 2466ab538f03d66adb7356fae1ae3481 | 48.152174 | 109 | 0.781291 | 5.06383 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/git-features-trainer/src/git4idea/ift/lesson/GitProjectHistoryLesson.kt | 6 | 8816 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.ift.lesson
import com.intellij.diff.tools.util.SimpleDiffPanel
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.vcs.changes.VcsEditorTabFilesManager
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.openapi.wm.ToolWindowId
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.ui.SearchTextField
import com.intellij.util.ui.UIUtil
import com.intellij.vcs.log.VcsLogBundle
import com.intellij.vcs.log.impl.VcsProjectLog
import com.intellij.vcs.log.ui.details.CommitDetailsListPanel
import com.intellij.vcs.log.ui.filter.BranchFilterPopupComponent
import com.intellij.vcs.log.ui.filter.UserFilterPopupComponent
import com.intellij.vcs.log.ui.frame.MainFrame
import com.intellij.vcs.log.ui.table.GraphTableModel
import com.intellij.vcs.log.ui.table.VcsLogGraphTable
import git4idea.ift.GitLessonsBundle
import git4idea.ift.GitLessonsUtil.highlightLatestCommitsFromBranch
import git4idea.ift.GitLessonsUtil.highlightSubsequentCommitsInGitLog
import git4idea.ift.GitLessonsUtil.resetGitLogWindow
import git4idea.ift.GitLessonsUtil.showWarningIfGitWindowClosed
import git4idea.ui.branch.dashboard.CHANGE_LOG_FILTER_ON_BRANCH_SELECTION_PROPERTY
import git4idea.ui.branch.dashboard.SHOW_GIT_BRANCHES_LOG_PROPERTY
import org.assertj.swing.fixture.JPanelFixture
import org.assertj.swing.fixture.JTableFixture
import training.dsl.*
import training.ui.LearningUiHighlightingManager
import training.ui.LearningUiUtil.findComponentWithTimeout
import training.util.LessonEndInfo
import java.util.regex.Pattern
class GitProjectHistoryLesson : GitLesson("Git.ProjectHistory", GitLessonsBundle.message("git.project.history.lesson.name")) {
override val sampleFilePath = "git/sphinx_cat.yml"
override val branchName = "feature"
private val textToFind = "sphinx"
private var showGitBranchesBackup: Boolean? = null
override val testScriptProperties = TaskTestContext.TestScriptProperties(40)
override val lessonContent: LessonContext.() -> Unit = {
task("ActivateVersionControlToolWindow") {
text(GitLessonsBundle.message("git.project.history.open.git.window", action(it)))
stateCheck {
val toolWindowManager = ToolWindowManager.getInstance(project)
toolWindowManager.getToolWindow(ToolWindowId.VCS)?.isVisible == true
}
test { actions(it) }
}
resetGitLogWindow()
prepareRuntimeTask l@{
val property = SHOW_GIT_BRANCHES_LOG_PROPERTY
val logUiProperties = VcsProjectLog.getInstance(project).mainLogUi?.properties ?: return@l
showGitBranchesBackup = logUiProperties[property]
logUiProperties[property] = true
}
task {
text(GitLessonsBundle.message("git.project.history.commits.tree.explanation"))
highlightLatestCommitsFromBranch(branchName)
showWarningIfGitWindowClosed()
proceedLink()
}
task {
var selectionCleared = false
triggerAndFullHighlight().treeItem { tree, path ->
(path.pathCount > 1 && path.getPathComponent(1).toString() == "HEAD_NODE").also {
if (!selectionCleared) {
tree.clearSelection()
selectionCleared = true
}
}
}
}
task {
val logUiProperties = VcsProjectLog.getInstance(project).mainLogUi?.properties
val choice = if (logUiProperties == null || !logUiProperties[CHANGE_LOG_FILTER_ON_BRANCH_SELECTION_PROPERTY]) 1 else 0
text(GitLessonsBundle.message("git.project.history.apply.branch.filter", choice))
text(GitLessonsBundle.message("git.project.history.click.head.tooltip", choice),
LearningBalloonConfig(Balloon.Position.above, 250))
triggerUI().component { ui: BranchFilterPopupComponent ->
ui.currentText?.contains("HEAD") == true
}
showWarningIfGitWindowClosed(restoreTaskWhenResolved = true)
test {
ideFrame {
val fixture = jTree { path -> path.getPathComponent(path.pathCount - 1).toString() == "HEAD_NODE" }
fixture.doubleClickPath("HEAD_NODE")
}
}
}
task {
triggerAndFullHighlight().component { _: UserFilterPopupComponent -> true }
}
val meFilterText = VcsLogBundle.message("vcs.log.user.filter.me")
task {
text(GitLessonsBundle.message("git.project.history.apply.user.filter"))
text(GitLessonsBundle.message("git.project.history.click.filter.tooltip"),
LearningBalloonConfig(Balloon.Position.above, 0))
triggerAndBorderHighlight().listItem { item ->
item.toString().contains(meFilterText)
}
showWarningIfGitWindowClosed(restoreTaskWhenResolved = true)
test {
ideFrame {
val panel: UserFilterPopupComponent = findComponentWithTimeout(defaultTimeout)
JPanelFixture(robot, panel).click()
}
}
}
task {
text(GitLessonsBundle.message("git.project.history.select.me", strong(meFilterText)))
triggerUI().component { ui: UserFilterPopupComponent ->
ui.currentText?.contains(meFilterText) == true
}
restoreByUi(delayMillis = defaultRestoreDelay)
test {
ideFrame {
jList(meFilterText).clickItem(meFilterText)
}
}
}
task {
text(GitLessonsBundle.message("git.project.history.apply.message.filter", code(textToFind), LessonUtil.rawEnter()))
triggerAndFullHighlight().component { ui: SearchTextField ->
(UIUtil.getParentOfType(MainFrame::class.java, ui) != null).also {
if (it) IdeFocusManager.getInstance(project).requestFocus(ui, true)
}
}
triggerUI().component l@{ ui: VcsLogGraphTable ->
val model = ui.model as? GraphTableModel ?: return@l false
model.rowCount > 0 && model.getCommitMetadata(0).fullMessage.contains(textToFind)
}
showWarningIfGitWindowClosed()
test {
Thread.sleep(500)
type(textToFind)
invokeActionViaShortcut("ENTER")
}
}
task {
text(GitLessonsBundle.message("git.project.history.select.commit"))
highlightSubsequentCommitsInGitLog(0)
triggerUI().component { ui: VcsLogGraphTable ->
ui.selectedRow == 0
}
restoreState {
val vcsLogUi = VcsProjectLog.getInstance(project).mainLogUi ?: return@restoreState false
vcsLogUi.filterUi.textFilterComponent.text == ""
}
showWarningIfGitWindowClosed()
test {
ideFrame {
val table: VcsLogGraphTable = findComponentWithTimeout(defaultTimeout)
JTableFixture(robot, table).cell(Pattern.compile(""".*$textToFind.*""")).click()
}
}
}
task {
text(GitLessonsBundle.message("git.project.history.commit.details.explanation"))
proceedLink()
triggerAndBorderHighlight { usePulsation = true }.component { _: CommitDetailsListPanel -> true }
showWarningIfGitWindowClosed()
}
task {
before {
LearningUiHighlightingManager.clearHighlights()
}
text(GitLessonsBundle.message("git.project.history.click.changed.file"))
triggerAndFullHighlight().treeItem { _, path ->
path.getPathComponent(path.pathCount - 1).toString().contains(".yml")
}
triggerUI().component { _: SimpleDiffPanel -> true }
showWarningIfGitWindowClosed()
test {
ideFrame {
val treeNodeText = sampleFilePath
val fixture = jTree { path -> path.getPathComponent(path.pathCount - 1).toString().contains(treeNodeText) }
val row = invokeAndWaitIfNeeded {
val tree = fixture.target()
(0 until tree.rowCount).find { fixture.valueAt(it).toString().contains(treeNodeText) }
} ?: error("Failed to find row with text '$treeNodeText'")
fixture.doubleClickRow(row)
}
}
}
if (VcsEditorTabFilesManager.getInstance().shouldOpenInNewWindow) {
task("EditorEscape") {
text(GitLessonsBundle.message("git.project.history.close.diff", action(it)))
stateCheck { previous.ui?.isShowing != true }
test { invokeActionViaShortcut("ESCAPE") }
}
}
text(GitLessonsBundle.message("git.project.history.invitation.to.commit.lesson"))
}
override fun onLessonEnd(project: Project, lessonEndInfo: LessonEndInfo) {
if (showGitBranchesBackup != null) {
val logUiProperties = VcsProjectLog.getInstance(project).mainLogUi?.properties ?: error("Failed to get MainVcsLogUiProperties")
logUiProperties[SHOW_GIT_BRANCHES_LOG_PROPERTY] = showGitBranchesBackup!!
}
}
} | apache-2.0 | 9037ed63408931e36a42f3c5c33d7e63 | 38.895928 | 140 | 0.708371 | 4.711919 | false | true | false | false |
dahlstrom-g/intellij-community | platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/sync/gitUtils.kt | 7 | 14065 | // 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.jetbrains.intellij.build.images.sync
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.util.stream.Collectors
import java.util.stream.Stream
import kotlin.math.max
internal val GIT = (System.getenv("TEAMCITY_GIT_PATH") ?: System.getenv("GIT") ?: "git").also {
val noGitFound = "Git is not found, please specify path to git executable in TEAMCITY_GIT_PATH or GIT or add it to PATH"
try {
val gitVersion = execute(null, it, "--version")
if (gitVersion.isBlank()) error(noGitFound)
log(gitVersion)
}
catch (e: IOException) {
throw IllegalStateException(noGitFound, e)
}
}
internal fun gitPull(repo: Path) {
try {
execute(repo, GIT, "pull", "--rebase")
}
catch (e: Exception) {
callSafely(printStackTrace = false) {
execute(repo, GIT, "rebase", "--abort")
}
log("Unable to pull changes for $repo: ${e.message}")
}
}
/**
* @param dirToList optional dir in [repo] from which to list files
* @return map of file paths (relative to [dirToList]) to [GitObject]
*/
internal fun listGitObjects(repo: Path, dirToList: Path?, fileFilter: (Path) -> Boolean = { true }): Map<String, GitObject> {
return listGitTree(repo, dirToList, fileFilter)
.collect(Collectors.toMap({ it.first }, { it.second }))
}
private fun listGitTree(repo: Path, dirToList: Path?, fileFilter: (Path) -> Boolean): Stream<Pair<String, GitObject>> {
val relativeDirToList = dirToList?.toFile()?.relativeTo(repo.toFile())?.path ?: ""
log("Inspecting $repo/$relativeDirToList")
if (!isUnderTeamCity()) gitPull(repo)
return execute(repo, GIT, "ls-tree", "HEAD", "-r", relativeDirToList)
.trim().lines().stream()
.filter(String::isNotBlank).map { line ->
// format: <mode> SP <type> SP <object> TAB <file>
line.splitWithTab()
.also { if (it.size != 2) error(line) }
.let { it[0].splitWithSpace() + it[1] }
.also { if (it.size != 4) error(line) }
}
.filter { fileFilter(repo.resolve(it[3].removeSuffix("\"").removePrefix("\""))) }
// <file>, <object>, repo
.map { GitObject(it[3], it[2], repo) }
.map { it.path.removePrefix("$relativeDirToList/") to it }
}
/**
* @param repos multiple git repos from which to list files
* @param root root repo
* @return map of file paths (relative to [root]) to [GitObject]
*/
internal fun listGitObjects(root: Path, repos: List<Path>, fileFilter: (Path) -> Boolean = { true }): Map<String, GitObject> {
return repos.parallelStream().flatMap { repo ->
listGitTree(repo, null, fileFilter).map {
// root relative <file> path to git object
val rootRelativePath = root.relativize(repo).toString()
if (rootRelativePath.isEmpty()) {
it.first
}
else {
"$rootRelativePath/${it.first}"
} to it.second
}
}.collect(Collectors.toMap({ it.first }, { it.second }))
}
/**
* @param path path relative to [repo]
*/
internal data class GitObject(val path: String, val hash: String, val repo: Path) {
val file: Path = repo.resolve(path)
}
/**
* @param dir path in repo
* @return root of repo
*/
internal fun findGitRepoRoot(dir: Path, silent: Boolean = false): Path {
return when {
Files.isDirectory(dir) && dir.toFile().listFiles()?.find { file ->
file.isDirectory && file.name == ".git"
} != null -> {
if (!silent) {
log("Git repo found in $dir")
}
dir
}
dir.parent != null -> {
if (!silent) {
log("No git repo found in $dir")
}
findGitRepoRoot(dir.parent, silent)
}
else -> error("No git repo found in $dir")
}
}
internal fun cleanup(repo: Path) {
execute(repo, GIT, "reset", "--hard")
execute(repo, GIT, "clean", "-xfd")
}
internal fun stageFiles(files: List<String>, repo: Path) {
// OS has argument length limit
splitAndTry(1000, files, repo) {
execute(repo, GIT, "add", "--no-ignore-removal", "--ignore-errors", *it.toTypedArray())
}
}
private fun splitAndTry(factor: Int, files: List<String>, repo: Path, block: (files: List<String>) -> Unit) {
files.split(factor).forEach {
try {
block(it)
}
catch (e: Exception) {
if (e.message?.contains("did not match any files") == true) return
val finerFactor: Int = factor / 2
if (finerFactor < 1) throw e
log("Git add command failed with ${e.message}")
splitAndTry(finerFactor, files, repo, block)
}
}
}
internal fun commit(repo: Path, message: String, user: String, email: String) {
execute(
repo, GIT,
"-c", "user.name=$user",
"-c", "user.email=$email",
"commit", "-m", message,
"--author=$user <$email>"
)
}
internal fun commitAndPush(repo: Path, branch: String, message: String, user: String, email: String, force: Boolean = false): CommitInfo {
commit(repo, message, user, email)
push(repo, branch, user, email, force)
return commitInfo(repo) ?: error("Unable to read last commit")
}
internal fun checkout(repo: Path, branch: String) = execute(repo, GIT, "checkout", branch)
internal fun push(repo: Path, spec: String, user: String? = null, email: String? = null, force: Boolean = false) =
retry(doRetry = { beforePushRetry(it, repo, spec, user, email) }) {
var args = arrayOf("origin", spec)
if (force) args += "--force"
execute(repo, GIT, "push", *args, withTimer = true)
}
private fun beforePushRetry(e: Throwable, repo: Path, spec: String, user: String?, email: String?): Boolean {
if (!isGitServerUnavailable(e)) {
val specParts = spec.split(':')
val identity = if (user != null && email != null) arrayOf(
"-c", "user.name=$user",
"-c", "user.email=$email"
)
else emptyArray()
execute(repo, GIT, *identity, "pull", "--rebase=true", "origin", if (specParts.count() == 2) {
"${specParts[1]}:${specParts[0]}"
}
else spec, withTimer = true)
}
return true
}
private fun isGitServerUnavailable(e: Throwable) = with(e.message ?: "") {
contains("remote end hung up unexpectedly")
|| contains("Service is in readonly mode")
|| contains("failed to lock")
|| contains("Connection timed out")
}
@Volatile
private var origins = emptyMap<Path, String>()
private val originsGuard = Any()
internal fun getOriginUrl(repo: Path): String {
if (!origins.containsKey(repo)) {
synchronized(originsGuard) {
if (!origins.containsKey(repo)) {
origins = origins + (repo to execute(repo, GIT, "ls-remote", "--get-url", "origin")
.removeSuffix(System.lineSeparator())
.trim())
}
}
}
return origins.getValue(repo)
}
@Volatile
private var latestChangeCommits = emptyMap<String, CommitInfo>()
private val latestChangeCommitsGuard = Any()
/**
* @param path path relative to [repo]
*/
internal fun latestChangeCommit(path: String, repo: Path): CommitInfo? {
val file = repo.resolve(path).toAbsolutePath().toString()
if (!latestChangeCommits.containsKey(file)) {
synchronized(file) {
if (!latestChangeCommits.containsKey(file)) {
val commitInfo = monoRepoMergeAwareCommitInfo(repo, path)
if (commitInfo != null) {
synchronized(latestChangeCommitsGuard) {
latestChangeCommits = latestChangeCommits + (file to commitInfo)
}
}
else return null
}
}
}
return latestChangeCommits.getValue(file)
}
private fun monoRepoMergeAwareCommitInfo(repo: Path, path: String) =
pathInfo(repo, "--", path)?.let { commitInfo ->
if (commitInfo.parents.size == 6 && commitInfo.subject.contains("Merge all repositories")) {
val strippedPath = path.stripMergedRepoPrefix()
commitInfo.parents.asSequence().mapNotNull {
pathInfo(repo, it, "--", strippedPath)
}.firstOrNull()
}
else commitInfo
}
private fun String.stripMergedRepoPrefix(): String = when {
startsWith("community/android/tools-base/") -> removePrefix("community/android/tools-base/")
startsWith("community/android/") -> removePrefix("community/android/")
startsWith("community/") -> removePrefix("community/")
startsWith("contrib/") -> removePrefix("contrib/")
startsWith("CIDR/") -> removePrefix("CIDR/")
else -> this
}
/**
* @return latest commit (or merge) time
*/
internal fun latestChangeTime(path: String, repo: Path): Long {
// latest commit for file
val commit = latestChangeCommit(path, repo)
if (commit == null) return -1
val mergeCommit = findMergeCommit(repo, commit.hash)
return max(commit.timestamp, mergeCommit?.timestamp ?: -1)
}
/**
* see [https://stackoverflow.com/questions/8475448/find-merge-commit-which-include-a-specific-commit]
*/
private fun findMergeCommit(repo: Path, commit: String, searchUntil: String = "HEAD"): CommitInfo? {
// list commits that are both descendants of commit hash and ancestors of HEAD
val ancestryPathList = execute(repo, GIT, "rev-list", "$commit..$searchUntil", "--ancestry-path")
.lineSequence().filter { it.isNotBlank() }
// follow only the first parent commit upon seeing a merge commit
val firstParentList = execute(repo, GIT, "rev-list", "$commit..$searchUntil", "--first-parent")
.lineSequence().filter { it.isNotBlank() }.toSet()
// last common commit may be the latest merge
return ancestryPathList
.lastOrNull(firstParentList::contains)
?.let { commitInfo(repo, it) }
?.takeIf {
// should be merge
it.parents.size > 1 &&
// but not some branch merge right after [commit]
it.parents.first() != commit
}?.let {
when {
// if it's a merge of master into master then all parents belong to master but the first one doesn't lead to [commit]
isMergeOfMasterIntoMaster(repo, it) -> findMergeCommit(repo, commit, it.parents[1])
it.parents.size > 2 -> {
log("WARNING: Merge commit ${it.hash} for $commit in $repo is found but it has more than two parents (one of them could be master), skipping")
null
}
// merge is found
else -> it
}
}
}
/**
* Inspecting commit subject which isn't reliable criteria, may need to be adjusted
*
* @param merge merge commit
*/
private fun isMergeOfMasterIntoMaster(repo: Path, merge: CommitInfo) =
merge.parents.size == 2 && with(merge.subject) {
val head = head(repo)
(contains("Merge branch $head") ||
contains("Merge branch '$head'") ||
contains("origin/$head")) &&
(!contains(" into ") ||
endsWith("into $head") ||
endsWith("into '$head'"))
}
@Volatile
private var heads = emptyMap<Path, String>()
private val headsGuard = Any()
internal fun head(repo: Path): String {
if (!heads.containsKey(repo)) {
synchronized(headsGuard) {
if (!heads.containsKey(repo)) {
heads = heads + (repo to execute(repo, GIT, "rev-parse", "--abbrev-ref", "HEAD").removeSuffix(System.lineSeparator()))
}
}
}
return heads.getValue(repo)
}
internal fun commitInfo(repo: Path, vararg args: String) = gitLog(repo, *args).singleOrNull()
private fun pathInfo(repo: Path, vararg args: String) = gitLog(repo, "--follow", *args).singleOrNull()
private fun gitLog(repo: Path, vararg args: String): List<CommitInfo> {
return execute(
repo, GIT, "log",
"--max-count", "1",
"--format=%H/%cd/%P/%cn/%ce/%s",
"--date=raw", *args
).lineSequence().mapNotNull {
val output = it.splitNotBlank("/")
// <hash>/<timestamp> <timezone>/<parent hashes>/committer email/<subject>
if (output.size >= 6) {
CommitInfo(
repo = repo,
hash = output[0],
timestamp = output[1].splitWithSpace()[0].toLong(),
parents = output[2].splitWithSpace(),
committer = Committer(name = output[3], email = output[4]),
subject = output.subList(5, output.size)
.joinToString(separator = "/")
.removeSuffix(System.lineSeparator())
)
}
else null
}.toList()
}
internal data class CommitInfo(
val hash: String,
val timestamp: Long,
val subject: String,
val committer: Committer,
val parents: List<String>,
val repo: Path
)
internal data class Committer(val name: String, val email: String)
internal fun gitStatus(repo: Path, includeUntracked: Boolean = false) = Changes().apply {
execute(repo, GIT, "status", "--short", "--untracked-files=${if (includeUntracked) "all" else "no"}", "--ignored=no")
.lineSequence()
.filter(String::isNotBlank)
.forEach {
val (status, path) = it.splitToSequence("->", " ")
.filter(String::isNotBlank)
.map(String::trim)
.toList()
val type = when(status) {
"A", "??" -> Changes.Type.ADDED
"M" -> Changes.Type.MODIFIED
"D" -> Changes.Type.DELETED
else -> error("Unknown change type: $status. Git status line: $it")
}
register(type, listOf(path))
}
}
internal fun gitStage(repo: Path) = execute(repo, GIT, "diff", "--cached", "--name-status")
internal fun changesFromCommit(repo: Path, hash: String): Map<Changes.Type, List<String>> {
return execute(repo, GIT, "show", "--pretty=format:none", "--name-status", "--no-renames", hash)
.lineSequence().map { it.trim() }
.filter { it.isNotEmpty() && it != "none" }
.map { it.splitWithTab() }
.onEach { if (it.size != 2) error(it.joinToString(" ")) }
.map {
val (type, path) = it
when (type) {
"A" -> Changes.Type.ADDED
"D" -> Changes.Type.DELETED
"M" -> Changes.Type.MODIFIED
"T" -> Changes.Type.MODIFIED
else -> return@map null
} to path
}
.filterNotNull().groupBy({ it.first }, { it.second })
}
internal fun gitClone(uri: String, dir: Path): Path {
val filesBeforeClone = dir.toFile().listFiles()?.toList() ?: emptyList()
execute(dir, GIT, "clone", uri)
return ((dir.toFile().listFiles()?.toList() ?: emptyList()) - filesBeforeClone).first {
uri.contains(it.name)
}.toPath()
}
| apache-2.0 | 368178c7979ba1e335be8a17c43c93b0 | 33.05569 | 152 | 0.639815 | 3.727803 | false | false | false | false |
ThePreviousOne/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/base/BaseReader.kt | 1 | 6746 | package eu.kanade.tachiyomi.ui.reader.viewer.base
import com.davemorrissey.labs.subscaleview.decoder.*
import eu.kanade.tachiyomi.data.preference.getOrDefault
import eu.kanade.tachiyomi.data.source.model.Page
import eu.kanade.tachiyomi.ui.base.fragment.BaseFragment
import eu.kanade.tachiyomi.ui.reader.ReaderActivity
import eu.kanade.tachiyomi.ui.reader.ReaderChapter
import java.util.*
/**
* Base reader containing the common data that can be used by its implementations. It does not
* contain any UI related action.
*/
abstract class BaseReader : BaseFragment() {
companion object {
/**
* Rapid decoder.
*/
const val RAPID_DECODER = 0
/**
* Skia decoder.
*/
const val SKIA_DECODER = 1
/**
* Image decoder.
*/
const val IMAGE_DECODER = 2
}
/**
* List of chapters added in the reader.
*/
private val chapters = ArrayList<ReaderChapter>()
/**
* List of pages added in the reader. It can contain pages from more than one chapter.
*/
var pages: MutableList<Page> = ArrayList()
private set
/**
* Current visible position of [pages].
*/
var currentPage: Int = 0
protected set
/**
* Region decoder class to use.
*/
lateinit var regionDecoderClass: Class<out ImageRegionDecoder>
private set
/**
* Bitmap decoder class to use.
*/
lateinit var bitmapDecoderClass: Class<out ImageDecoder>
private set
/**
* Whether tap navigation is enabled or not.
*/
val tappingEnabled by lazy { readerActivity.preferences.readWithTapping().getOrDefault() }
/**
* Whether the reader has requested to append a chapter. Used with seamless mode to avoid
* restarting requests when changing pages.
*/
private var hasRequestedNextChapter: Boolean = false
/**
* Returns the active page.
*/
fun getActivePage(): Page? {
return pages.getOrNull(currentPage)
}
/**
* Called when a page changes. Implementations must call this method.
*
* @param position the new current page.
*/
fun onPageChanged(position: Int) {
val oldPage = pages[currentPage]
val newPage = pages[position]
val oldChapter = oldPage.chapter
val newChapter = newPage.chapter
// Update page indicator and seekbar
readerActivity.onPageChanged(newPage)
// Active chapter has changed.
if (oldChapter.id != newChapter.id) {
readerActivity.onEnterChapter(newPage.chapter, newPage.pageNumber)
}
// Request next chapter only when the conditions are met.
if (pages.size - position < 5 && chapters.last().id == newChapter.id
&& readerActivity.presenter.hasNextChapter() && !hasRequestedNextChapter) {
hasRequestedNextChapter = true
readerActivity.presenter.appendNextChapter()
}
currentPage = position
}
/**
* Sets the active page.
*
* @param page the page to display.
*/
fun setActivePage(page: Page) {
setActivePage(getPageIndex(page))
}
/**
* Searchs for the index of a page in the current list without requiring them to be the same
* object.
*
* @param search the page to search.
* @return the index of the page in [pages] or 0 if it's not found.
*/
fun getPageIndex(search: Page): Int {
for ((index, page) in pages.withIndex()) {
if (page.pageNumber == search.pageNumber && page.chapter.id == search.chapter.id) {
return index
}
}
return 0
}
/**
* Called from the presenter when the page list of a chapter is ready. This method is called
* on every [onResume], so we add some logic to avoid duplicating chapters.
*
* @param chapter the chapter to set.
* @param currentPage the initial page to display.
*/
fun onPageListReady(chapter: ReaderChapter, currentPage: Page) {
if (!chapters.contains(chapter)) {
// if we reset the loaded page we also need to reset the loaded chapters
chapters.clear()
chapters.add(chapter)
pages = ArrayList(chapter.pages)
onChapterSet(chapter, currentPage)
} else {
setActivePage(currentPage)
}
}
/**
* Called from the presenter when the page list of a chapter to append is ready. This method is
* called on every [onResume], so we add some logic to avoid duplicating chapters.
*
* @param chapter the chapter to append.
*/
fun onPageListAppendReady(chapter: ReaderChapter) {
if (!chapters.contains(chapter)) {
hasRequestedNextChapter = false
chapters.add(chapter)
pages.addAll(chapter.pages!!)
onChapterAppended(chapter)
}
}
/**
* Sets the active page.
*
* @param pageNumber the index of the page from [pages].
*/
abstract fun setActivePage(pageNumber: Int)
/**
* Called when a new chapter is set in [BaseReader].
*
* @param chapter the chapter set.
* @param currentPage the initial page to display.
*/
abstract fun onChapterSet(chapter: ReaderChapter, currentPage: Page)
/**
* Called when a chapter is appended in [BaseReader].
*
* @param chapter the chapter appended.
*/
abstract fun onChapterAppended(chapter: ReaderChapter)
/**
* Moves pages forward. Implementations decide how to move (by a page, by some distance...).
*/
abstract fun moveToNext()
/**
* Moves pages backward. Implementations decide how to move (by a page, by some distance...).
*/
abstract fun moveToPrevious()
/**
* Sets the active decoder class.
*
* @param value the decoder class to use.
*/
fun setDecoderClass(value: Int) {
when (value) {
RAPID_DECODER -> {
bitmapDecoderClass = RapidImageDecoder::class.java
regionDecoderClass = RapidImageRegionDecoder::class.java
}
SKIA_DECODER -> {
bitmapDecoderClass = SkiaImageDecoder::class.java
regionDecoderClass = SkiaImageRegionDecoder::class.java
}
IMAGE_DECODER -> {
bitmapDecoderClass = IImageDecoder::class.java
regionDecoderClass = IImageRegionDecoder::class.java
}
}
}
/**
* Property to get the reader activity.
*/
val readerActivity: ReaderActivity
get() = activity as ReaderActivity
}
| apache-2.0 | cc96d0f022368bcacb961055884c16b5 | 28.458515 | 99 | 0.612363 | 4.649207 | false | false | false | false |
orauyeu/SimYukkuri | subprojects/simyukkuri/src/main/kotlin/simyukkuri/gameobject/yukkuri/event/action/actions/NoAction.kt | 1 | 626 | package simyukkuri.gameobject.yukkuri.event.action.actions
import simyukkuri.gameobject.yukkuri.event.IndividualEvent
import simyukkuri.gameobject.yukkuri.event.action.Action
import simyukkuri.gameobject.yukkuri.event.action.Posture
/** アクションがないことを表すアクション */
object NoAction : Action {
override val hasEnded: Boolean = true
override val currentAction: Action = this
override fun execute() = Unit
override fun interrupt() = Unit
override fun isTheSameAs(other: IndividualEvent): Boolean = other === this
override val posture: Posture = Posture.FRONT
} | apache-2.0 | 47701f6a5864cbf2e145ff6c1ddc45ae | 37.466667 | 78 | 0.761017 | 4.275362 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/platform/forge/reflection/reference/ReflectedMethodReference.kt | 1 | 7064 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.forge.reflection.reference
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.platform.mcp.McpModuleType
import com.demonwav.mcdev.util.constantStringValue
import com.demonwav.mcdev.util.findModule
import com.demonwav.mcdev.util.qualifiedMemberReference
import com.demonwav.mcdev.util.toTypedArray
import com.intellij.codeInsight.completion.JavaLookupElementBuilder
import com.intellij.lang.jvm.JvmModifier
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.command.CommandProcessor
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiClassObjectAccessExpression
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementResolveResult
import com.intellij.psi.PsiExpressionList
import com.intellij.psi.PsiLiteral
import com.intellij.psi.PsiReference
import com.intellij.psi.PsiReferenceBase
import com.intellij.psi.PsiReferenceProvider
import com.intellij.psi.PsiSubstitutor
import com.intellij.psi.ResolveResult
import com.intellij.psi.codeStyle.CodeStyleManager
import com.intellij.psi.codeStyle.JavaCodeStyleManager
import com.intellij.psi.util.MethodSignatureUtil
import com.intellij.psi.util.TypeConversionUtil
import com.intellij.util.ProcessingContext
object ReflectedMethodReference : PsiReferenceProvider() {
override fun getReferencesByElement(element: PsiElement, context: ProcessingContext): Array<PsiReference> {
// The pattern for this provider should only match method params, but better be safe
if (element.parent !is PsiExpressionList) {
return arrayOf()
}
return arrayOf(Reference(element as PsiLiteral))
}
class Reference(element: PsiLiteral) : PsiReferenceBase.Poly<PsiLiteral>(element) {
val methodName
get() = element.constantStringValue ?: ""
val expressionList
get() = element.parent as PsiExpressionList
override fun getVariants(): Array<Any> {
val typeClass = findReferencedClass() ?: return arrayOf()
return typeClass.allMethods
.asSequence()
.filter { !it.hasModifier(JvmModifier.PUBLIC) }
.map { method ->
JavaLookupElementBuilder.forMethod(method, PsiSubstitutor.EMPTY).withInsertHandler { context, _ ->
val literal = context.file.findElementAt(context.startOffset)?.parent as? PsiLiteral
?: return@withInsertHandler
val params = literal.parent as? PsiExpressionList ?: return@withInsertHandler
val srgManager = literal.findModule()?.let { MinecraftFacet.getInstance(it) }
?.getModuleOfType(McpModuleType)?.srgManager
val srgMap = srgManager?.srgMapNow
val signature = method.getSignature(PsiSubstitutor.EMPTY)
val returnType = method.returnType?.let { TypeConversionUtil.erasure(it).canonicalText }
?: return@withInsertHandler
val paramTypes = MethodSignatureUtil.calcErasedParameterTypes(signature)
.map { it.canonicalText }
val memberRef = method.qualifiedMemberReference
val srgMethod = srgMap?.getSrgMethod(memberRef) ?: memberRef
context.setLaterRunnable {
// Commit changes made by code completion
context.commitDocument()
// Run command to replace PsiElement
CommandProcessor.getInstance().runUndoTransparentAction {
runWriteAction {
val elementFactory = JavaPsiFacade.getElementFactory(context.project)
val srgLiteral = elementFactory.createExpressionFromText(
"\"${srgMethod.name}\"",
params
)
if (params.expressionCount > 1) {
params.expressions[1].replace(srgLiteral)
} else {
params.add(srgLiteral)
}
if (params.expressionCount > 2) {
params.deleteChildRange(params.expressions[2], params.expressions.last())
}
val returnTypeRef = elementFactory.createExpressionFromText(
"$returnType.class",
params
)
params.add(returnTypeRef)
for (paramType in paramTypes) {
val paramTypeRef = elementFactory.createExpressionFromText(
"$paramType.class",
params
)
params.add(paramTypeRef)
}
JavaCodeStyleManager.getInstance(context.project).shortenClassReferences(params)
CodeStyleManager.getInstance(context.project).reformat(params, true)
context.editor.caretModel.moveToOffset(params.textRange.endOffset)
}
}
}
}
}
.toTypedArray()
}
override fun multiResolve(incompleteCode: Boolean): Array<ResolveResult> {
val typeClass = findReferencedClass() ?: return arrayOf()
val name = methodName
val srgManager = element.findModule()?.let { MinecraftFacet.getInstance(it) }
?.getModuleOfType(McpModuleType)?.srgManager
val srgMap = srgManager?.srgMapNow
val mcpName = srgMap?.mapMcpToSrgName(name) ?: name
return typeClass.allMethods.asSequence()
.filter { it.name == mcpName }
.map(::PsiElementResolveResult)
.toTypedArray()
}
private fun findReferencedClass(): PsiClass? {
val callParams = element.parent as? PsiExpressionList
val classRef = callParams?.expressions?.first() as? PsiClassObjectAccessExpression
val type = classRef?.operand?.type as? PsiClassType
return type?.resolve()
}
}
}
| mit | e5c4449c6c6710fec3b1a4c2552fc611 | 45.473684 | 118 | 0.570074 | 6.39276 | false | false | false | false |
paplorinc/intellij-community | java/execution/impl/src/com/intellij/execution/application/JavaApplicationRunConfigurationImporter.kt | 4 | 2604 | /*
* 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.execution.application
import com.intellij.execution.ShortenCommandLine
import com.intellij.execution.configurations.ConfigurationFactory
import com.intellij.execution.configurations.ConfigurationTypeUtil
import com.intellij.execution.configurations.RunConfiguration
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider
import com.intellij.openapi.externalSystem.service.project.settings.RunConfigurationImporter
import com.intellij.openapi.project.Project
import com.intellij.util.ObjectUtils.consumeIfCast
class JavaApplicationRunConfigurationImporter : RunConfigurationImporter {
override fun process(project: Project, runConfiguration: RunConfiguration, cfg: Map<String, *>, modelsProvider: IdeModifiableModelsProvider) {
if (runConfiguration !is ApplicationConfiguration) {
throw IllegalArgumentException("Unexpected type of run configuration: ${runConfiguration::class.java}")
}
consumeIfCast(cfg["moduleName"], String::class.java) {
val module = modelsProvider.modifiableModuleModel.findModuleByName(it)
if (module != null) {
runConfiguration.setModule(module)
}
}
consumeIfCast(cfg["mainClass"], String::class.java) { runConfiguration.mainClassName = it }
consumeIfCast(cfg["jvmArgs"], String::class.java) { runConfiguration.vmParameters = it }
consumeIfCast(cfg["programParameters"], String::class.java) { runConfiguration.programParameters = it }
consumeIfCast(cfg["envs"], Map::class.java) { runConfiguration.envs = it as MutableMap<String, String> }
consumeIfCast(cfg["workingDirectory"], String::class.java) { runConfiguration.workingDirectory = it }
consumeIfCast(cfg["shortenCommandLine"], String::class.java) {
try {
runConfiguration.shortenCommandLine = ShortenCommandLine.valueOf(it)
} catch (e: IllegalArgumentException) {
LOG.warn("Illegal value of 'shortenCommandLine': $it", e)
}
}
}
override fun canImport(typeName: String): Boolean = typeName == "application"
override fun getConfigurationFactory(): ConfigurationFactory =
ConfigurationTypeUtil.findConfigurationType<ApplicationConfigurationType>(
ApplicationConfigurationType::class.java)
.configurationFactories[0]
companion object {
val LOG = Logger.getInstance(JavaApplicationRunConfigurationImporter::class.java)
}
} | apache-2.0 | a79fe5f29ce0303f9b0130002ecd05c0 | 47.240741 | 144 | 0.771889 | 4.913208 | false | true | false | false |
akhbulatov/wordkeeper | app/src/main/java/com/akhbulatov/wordkeeper/data/global/local/database/word/WordDbModel.kt | 1 | 531 | package com.akhbulatov.wordkeeper.data.global.local.database.word
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "words")
data class WordDbModel(
@ColumnInfo(name = "name") val name: String,
@ColumnInfo(name = "translation") val translation: String,
@ColumnInfo(name = "datetime") val datetime: Long,
@ColumnInfo(name = "category") val category: String
) {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "_id")
var id: Long = 0
}
| apache-2.0 | 2c44fe193223a15ab4785b0bc75e3327 | 28.5 | 65 | 0.717514 | 3.820144 | false | false | false | false |
google/intellij-community | python/python-psi-impl/src/com/jetbrains/python/inspections/PyTypeHintsInspection.kt | 5 | 44942 | // 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.inspections
import com.intellij.codeInsight.controlflow.ControlFlowUtil
import com.intellij.codeInspection.*
import com.intellij.codeInspection.util.InspectionMessage
import com.intellij.codeInspection.util.IntentionFamilyName
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiFileFactory
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.QualifiedName
import com.jetbrains.python.PyNames
import com.jetbrains.python.PyPsiBundle
import com.jetbrains.python.PyTokenTypes
import com.jetbrains.python.codeInsight.controlflow.ControlFlowCache
import com.jetbrains.python.codeInsight.controlflow.ReadWriteInstruction
import com.jetbrains.python.codeInsight.controlflow.ScopeOwner
import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil
import com.jetbrains.python.codeInsight.functionTypeComments.PyFunctionTypeAnnotationDialect
import com.jetbrains.python.codeInsight.imports.AddImportHelper
import com.jetbrains.python.codeInsight.imports.AddImportHelper.ImportPriority
import com.jetbrains.python.codeInsight.typeHints.PyTypeHintFile
import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider
import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider.isBitwiseOrUnionAvailable
import com.jetbrains.python.documentation.PythonDocumentationProvider
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.impl.PyBuiltinCache
import com.jetbrains.python.psi.impl.PyEvaluator
import com.jetbrains.python.psi.impl.PyPsiUtils
import com.jetbrains.python.psi.resolve.PyResolveContext
import com.jetbrains.python.psi.resolve.PyResolveUtil
import com.jetbrains.python.psi.types.*
import com.jetbrains.python.sdk.PythonSdkUtil
class PyTypeHintsInspection : PyInspection() {
override fun buildVisitor(holder: ProblemsHolder,
isOnTheFly: Boolean,
session: LocalInspectionToolSession): PsiElementVisitor = Visitor(holder, PyInspectionVisitor.getContext(session))
private class Visitor(holder: ProblemsHolder, context: TypeEvalContext) : PyInspectionVisitor(holder, context) {
private val genericQName = QualifiedName.fromDottedString(PyTypingTypeProvider.GENERIC)
override fun visitPyCallExpression(node: PyCallExpression) {
super.visitPyCallExpression(node)
val callee = node.callee as? PyReferenceExpression
val calleeQName = callee?.let { PyResolveUtil.resolveImportedElementQNameLocally(it) } ?: emptyList()
if (QualifiedName.fromDottedString(PyTypingTypeProvider.TYPE_VAR) in calleeQName) {
val target = getTargetFromAssignment(node)
checkTypeVarPlacement(node, target)
checkTypeVarArguments(node, target)
checkTypeVarRedefinition(target)
}
if (QualifiedName.fromDottedString(PyTypingTypeProvider.TYPING_PARAM_SPEC) in calleeQName) {
val target = getTargetFromAssignment(node)
checkParamSpecArguments(node, target)
}
checkInstanceAndClassChecks(node)
checkParenthesesOnGenerics(node)
}
private fun getTargetFromAssignment(node: PyCallExpression): PyExpression? {
val assignmentStatement = node.parent as? PyAssignmentStatement
if (assignmentStatement == null) return null
return assignmentStatement.targetsToValuesMapping.firstOrNull { it.second == node }?.first
}
override fun visitPyClass(node: PyClass) {
super.visitPyClass(node)
val superClassExpressions = node.superClassExpressions.asList()
checkPlainGenericInheritance(superClassExpressions)
checkGenericDuplication(superClassExpressions)
checkGenericCompleteness(node)
}
override fun visitPySubscriptionExpression(node: PySubscriptionExpression) {
super.visitPySubscriptionExpression(node)
checkParameters(node)
checkParameterizedBuiltins(node)
}
private fun checkParameterizedBuiltins(node: PySubscriptionExpression) {
if (LanguageLevel.forElement(node).isAtLeast(LanguageLevel.PYTHON39)) return
val qualifier = node.qualifier
if (qualifier is PyReferenceExpression) {
val hasImportFromFuture = (node.containingFile as? PyFile)?.hasImportFromFuture(FutureFeature.ANNOTATIONS) ?: false
if (PyBuiltinCache.isInBuiltins(qualifier) && qualifier.name in PyTypingTypeProvider.TYPING_BUILTINS_GENERIC_ALIASES &&
!hasImportFromFuture) {
registerProblem(node, PyPsiBundle.message("INSP.type.hints.builtin.cannot.be.parameterized.directly", qualifier.name),
ReplaceWithTypingGenericAliasQuickFix())
}
}
}
override fun visitPyReferenceExpression(node: PyReferenceExpression) {
super.visitPyReferenceExpression(node)
if (!PyTypingTypeProvider.isInsideTypeHint(node, myTypeEvalContext)) {
return
}
if (node.referencedName == PyNames.CANONICAL_SELF) {
val typeName = myTypeEvalContext.getType(node)?.name
if (typeName != null && typeName != PyNames.CANONICAL_SELF) {
registerProblem(node, PyPsiBundle.message("INSP.type.hints.invalid.type.self"), ProblemHighlightType.GENERIC_ERROR, null,
ReplaceWithTypeNameQuickFix(typeName))
}
}
val isTopLevelTypeHint = node.parent is PyAnnotation ||
node.parent is PyExpressionStatement && node.parent.parent is PyTypeHintFile
if (isTopLevelTypeHint) {
if (resolvesToAnyOfQualifiedNames(node, PyTypingTypeProvider.LITERAL, PyTypingTypeProvider.LITERAL_EXT)) {
registerProblem(node, PyPsiBundle.message("INSP.type.hints.literal.must.have.at.least.one.parameter"))
}
if (resolvesToAnyOfQualifiedNames(node, PyTypingTypeProvider.ANNOTATED, PyTypingTypeProvider.ANNOTATED_EXT)) {
registerProblem(node, PyPsiBundle.message("INSP.type.hints.annotated.must.be.called.with.at.least.two.arguments"))
}
}
else if (resolvesToAnyOfQualifiedNames(node, PyTypingTypeProvider.TYPE_ALIAS, PyTypingTypeProvider.TYPE_ALIAS_EXT)) {
registerProblem(node, PyPsiBundle.message("INSP.type.hints.type.alias.must.be.used.as.standalone.type.hint"))
}
}
override fun visitPyFile(node: PyFile) {
super.visitPyFile(node)
if (node is PyTypeHintFile && PyTypingTypeProvider.isInsideTypeHint(node, myTypeEvalContext)) {
node.children.singleOrNull().also { if (it is PyExpressionStatement) checkTupleMatching(it.expression) }
}
}
override fun visitPyElement(node: PyElement) {
super.visitPyElement(node)
if (node is PyTypeCommentOwner &&
node is PyAnnotationOwner &&
node.typeComment?.text.let { it != null && !PyTypingTypeProvider.TYPE_IGNORE_PATTERN.matcher(it).matches() }) {
val message = PyPsiBundle.message("INSP.type.hints.type.specified.both.in.type.comment.and.annotation")
if (node is PyFunction) {
if (node.annotationValue != null || node.parameterList.parameters.any { it is PyNamedParameter && it.annotationValue != null }) {
registerProblem(node.typeComment, message, RemoveElementQuickFix(PyPsiBundle.message("QFIX.remove.type.comment")))
registerProblem(node.nameIdentifier, message, RemoveFunctionAnnotations())
}
}
else if (node.annotationValue != null) {
registerProblem(node.typeComment, message, RemoveElementQuickFix(PyPsiBundle.message("QFIX.remove.type.comment")))
registerProblem(node.annotation, message, RemoveElementQuickFix(PyPsiBundle.message("QFIX.remove.annotation")))
}
}
}
override fun visitPyFunction(node: PyFunction) {
super.visitPyFunction(node)
checkTypeCommentAndParameters(node)
}
override fun visitPyTargetExpression(node: PyTargetExpression) {
super.visitPyTargetExpression(node)
checkAnnotatedNonSelfAttribute(node)
checkTypeAliasTarget(node)
}
private fun checkTypeAliasTarget(target: PyTargetExpression) {
val parent = target.parent
if (parent is PyTypeDeclarationStatement) {
val annotation = target.annotation?.value
if (annotation is PyReferenceExpression && resolvesToAnyOfQualifiedNames(annotation, PyTypingTypeProvider.TYPE_ALIAS,
PyTypingTypeProvider.TYPE_ALIAS_EXT)) {
registerProblem(target, PyPsiBundle.message("INSP.type.hints.type.alias.must.be.immediately.initialized"))
}
}
else if (parent is PyAssignmentStatement &&
PyTypingTypeProvider.isExplicitTypeAlias(parent, myTypeEvalContext) && !PyUtil.isTopLevel(parent)) {
registerProblem(target, PyPsiBundle.message("INSP.type.hints.type.alias.must.be.top.level.declaration"))
}
}
private fun checkTypeVarPlacement(call: PyCallExpression, target: PyExpression?) {
if (target == null) {
registerProblem(call, PyPsiBundle.message("INSP.type.hints.typevar.expression.must.be.always.directly.assigned.to.variable"))
}
}
private fun checkTypeVarRedefinition(target: PyExpression?) {
val scopeOwner = ScopeUtil.getScopeOwner(target) ?: return
val name = target?.name ?: return
val instructions = ControlFlowCache.getControlFlow(scopeOwner).instructions
val startInstruction = ControlFlowUtil.findInstructionNumberByElement(instructions, target)
ControlFlowUtil.iteratePrev(startInstruction, instructions) { instruction ->
if (instruction is ReadWriteInstruction &&
instruction.num() != startInstruction &&
name == instruction.name &&
instruction.access.isWriteAccess) {
registerProblem(target, PyPsiBundle.message("INSP.type.hints.type.variables.must.not.be.redefined"))
ControlFlowUtil.Operation.BREAK
}
else {
ControlFlowUtil.Operation.NEXT
}
}
}
private fun checkParamSpecArguments(call: PyCallExpression, target: PyExpression?) {
processMatchedArgument(call) { name, argument ->
if (name == "name") {
checkNameIsTheSameAsTarget(argument, target,
PyPsiBundle.message("INSP.type.hints.paramspec.expects.string.literal.as.first.argument"),
PyPsiBundle.message("INSP.type.hints.argument.to.paramspec.must.be.string.equal.to.variable.name"))
}
}
}
private fun checkTypeVarArguments(call: PyCallExpression, target: PyExpression?) {
var covariant = false
var contravariant = false
var bound: PyExpression? = null
val constraints = mutableListOf<PyExpression?>()
processMatchedArgument(call) { name, argument ->
when (name) {
"name" ->
checkNameIsTheSameAsTarget(argument, target,
PyPsiBundle.message("INSP.type.hints.typevar.expects.string.literal.as.first.argument"),
PyPsiBundle.message("INSP.type.hints.argument.to.typevar.must.be.string.equal.to.variable.name"))
"covariant" -> covariant = PyEvaluator.evaluateAsBoolean(argument, false)
"contravariant" -> contravariant = PyEvaluator.evaluateAsBoolean(argument, false)
"bound" -> bound = argument
"constraints" -> constraints.add(argument)
}
}
if (covariant && contravariant) {
registerProblem(call, PyPsiBundle.message("INSP.type.hints.bivariant.type.variables.are.not.supported"),
ProblemHighlightType.GENERIC_ERROR)
}
if (constraints.isNotEmpty() && bound != null) {
registerProblem(call, PyPsiBundle.message("INSP.type.hints.typevar.constraints.cannot.be.combined.with.bound"),
ProblemHighlightType.GENERIC_ERROR)
}
if (constraints.size == 1) {
registerProblem(call, PyPsiBundle.message("INSP.type.hints.single.typevar.constraint.not.allowed"),
ProblemHighlightType.GENERIC_ERROR)
}
constraints.asSequence().plus(bound).forEach {
if (it != null) {
val type = PyTypingTypeProvider.getType(it, myTypeEvalContext)?.get()
if (PyTypeChecker.hasGenerics(type, myTypeEvalContext)) {
registerProblem(it, PyPsiBundle.message("INSP.type.hints.typevar.constraints.cannot.be.parametrized.by.type.variables"))
}
}
}
}
private fun checkNameIsTheSameAsTarget(argument: PyExpression?, target: PyExpression?,
@InspectionMessage notStringLiteralMessage: String,
@InspectionMessage notEqualMessage: String) {
if (argument !is PyStringLiteralExpression) {
registerProblem(argument, notStringLiteralMessage)
}
else {
val targetName = target?.name
if (targetName != null && targetName != argument.stringValue) {
registerProblem(argument,
notEqualMessage,
ReplaceWithTargetNameQuickFix(targetName))
}
}
}
private fun processMatchedArgument(call: PyCallExpression,
processor: (name: String?, argument: PyExpression?) -> Unit) {
val resolveContext = PyResolveContext.defaultContext(myTypeEvalContext)
call
.multiMapArguments(resolveContext)
.firstOrNull { it.unmappedArguments.isEmpty() && it.unmappedParameters.isEmpty() }
?.let { mapping ->
mapping.mappedParameters.entries.forEach {
val name = it.value.name
val argument = PyUtil.peelArgument(it.key)
processor(name, argument)
}
}
}
private fun checkInstanceAndClassChecks(call: PyCallExpression) {
if (call.isCalleeText(PyNames.ISINSTANCE, PyNames.ISSUBCLASS)) {
val base = call.arguments.getOrNull(1) ?: return
checkInstanceAndClassChecksOn(base)
}
}
private fun checkInstanceAndClassChecksOn(base: PyExpression) {
if (base is PyBinaryExpression && base.operator == PyTokenTypes.OR) {
if (isBitwiseOrUnionAvailable(base)) {
val left = base.leftExpression
val right = base.rightExpression
if (left != null) checkInstanceAndClassChecksOn(left)
if (right != null) checkInstanceAndClassChecksOn(right)
}
return
}
checkInstanceAndClassChecksOnTypeVar(base)
checkInstanceAndClassChecksOnReference(base)
checkInstanceAndClassChecksOnSubscription(base)
}
private fun checkInstanceAndClassChecksOnTypeVar(base: PyExpression) {
val type = myTypeEvalContext.getType(base)
if (type is PyGenericType && !type.isDefinition ||
type is PyCollectionType && type.elementTypes.any { it is PyGenericType } && !type.isDefinition) {
registerProblem(base,
PyPsiBundle.message("INSP.type.hints.type.variables.cannot.be.used.with.instance.class.checks"),
ProblemHighlightType.GENERIC_ERROR)
}
}
private fun checkInstanceAndClassChecksOnReference(base: PyExpression) {
if (base is PyReferenceExpression) {
val resolvedBase = multiFollowAssignmentsChain(base)
resolvedBase
.asSequence()
.filterIsInstance<PyQualifiedNameOwner>()
.mapNotNull { it.qualifiedName }
.forEach {
when (it) {
PyTypingTypeProvider.ANY,
PyTypingTypeProvider.UNION,
PyTypingTypeProvider.GENERIC,
PyTypingTypeProvider.OPTIONAL,
PyTypingTypeProvider.CLASS_VAR,
PyTypingTypeProvider.NO_RETURN,
PyTypingTypeProvider.FINAL,
PyTypingTypeProvider.FINAL_EXT,
PyTypingTypeProvider.LITERAL,
PyTypingTypeProvider.LITERAL_EXT,
PyTypingTypeProvider.ANNOTATED,
PyTypingTypeProvider.ANNOTATED_EXT,
PyTypingTypeProvider.TYPE_ALIAS,
PyTypingTypeProvider.TYPE_ALIAS_EXT -> {
val shortName = it.substringAfterLast('.')
registerProblem(base, PyPsiBundle.message("INSP.type.hints.type.cannot.be.used.with.instance.class.checks", shortName),
ProblemHighlightType.GENERIC_ERROR)
}
}
}
resolvedBase
.asSequence()
.filterIsInstance<PySubscriptionExpression>()
.filter { myTypeEvalContext.maySwitchToAST(it) }
.forEach { checkInstanceAndClassChecksOnSubscriptionOperand(base, it.operand) }
}
}
private fun checkInstanceAndClassChecksOnSubscription(base: PyExpression) {
if (base is PySubscriptionExpression) {
checkInstanceAndClassChecksOnSubscriptionOperand(base, base.operand)
}
}
private fun checkInstanceAndClassChecksOnSubscriptionOperand(base: PyExpression, operand: PyExpression) {
if (operand is PyReferenceExpression) {
multiFollowAssignmentsChain(operand)
.forEach {
if (it is PyQualifiedNameOwner) {
when (val qName = it.qualifiedName) {
PyTypingTypeProvider.GENERIC,
PyTypingTypeProvider.CLASS_VAR,
PyTypingTypeProvider.FINAL,
PyTypingTypeProvider.FINAL_EXT,
PyTypingTypeProvider.LITERAL,
PyTypingTypeProvider.LITERAL_EXT,
PyTypingTypeProvider.ANNOTATED,
PyTypingTypeProvider.ANNOTATED_EXT -> {
registerParametrizedGenericsProblem(qName, base)
return@forEach
}
PyTypingTypeProvider.UNION,
PyTypingTypeProvider.OPTIONAL -> {
if (!isBitwiseOrUnionAvailable(base)) {
registerParametrizedGenericsProblem(qName, base)
}
else if (base is PySubscriptionExpression) {
val indexExpr = base.indexExpression
if (indexExpr is PyTupleExpression) {
indexExpr.elements.forEach { tupleElement -> checkInstanceAndClassChecksOn(tupleElement) }
}
else if (indexExpr != null) {
checkInstanceAndClassChecksOn(indexExpr)
}
}
}
PyTypingTypeProvider.CALLABLE,
PyTypingTypeProvider.TYPE,
PyTypingTypeProvider.PROTOCOL,
PyTypingTypeProvider.PROTOCOL_EXT -> {
registerProblem(base,
PyPsiBundle.message("INSP.type.hints.parameterized.generics.cannot.be.used.with.instance.class.checks"),
ProblemHighlightType.GENERIC_ERROR,
null,
if (base is PySubscriptionExpression) RemoveGenericParametersQuickFix() else null)
return@forEach
}
}
}
if (it is PyTypedElement) {
val type = myTypeEvalContext.getType(it)
if (type is PyWithAncestors && PyTypingTypeProvider.isGeneric(type, myTypeEvalContext)) {
registerProblem(base,
PyPsiBundle.message("INSP.type.hints.parameterized.generics.cannot.be.used.with.instance.class.checks"),
ProblemHighlightType.GENERIC_ERROR,
null,
if (base is PySubscriptionExpression) RemoveGenericParametersQuickFix() else null)
}
}
}
}
}
private fun registerParametrizedGenericsProblem(qName: String, base: PsiElement) {
val shortName = qName.substringAfterLast('.')
registerProblem(base, PyPsiBundle.message("INSP.type.hints.type.cannot.be.used.with.instance.class.checks", shortName),
ProblemHighlightType.GENERIC_ERROR)
}
private fun checkParenthesesOnGenerics(call: PyCallExpression) {
val callee = call.callee
if (callee is PyReferenceExpression) {
if (PyResolveUtil.resolveImportedElementQNameLocally(callee).any { PyTypingTypeProvider.GENERIC_CLASSES.contains(it.toString()) }) {
registerProblem(call,
PyPsiBundle.message("INSP.type.hints.generics.should.be.specified.through.square.brackets"),
ProblemHighlightType.GENERIC_ERROR,
null,
ReplaceWithSubscriptionQuickFix())
}
else if (PyTypingTypeProvider.isInsideTypeHint(call, myTypeEvalContext)) {
multiFollowAssignmentsChain(callee)
.asSequence()
.map { if (it is PyFunction) it.containingClass else it }
.any { it is PyWithAncestors && PyTypingTypeProvider.isGeneric(it, myTypeEvalContext) }
.also {
if (it) registerProblem(call, PyPsiBundle.message("INSP.type.hints.generics.should.be.specified.through.square.brackets"),
ReplaceWithSubscriptionQuickFix())
}
}
}
}
private fun checkPlainGenericInheritance(superClassExpressions: List<PyExpression>) {
superClassExpressions
.asSequence()
.filterIsInstance<PyReferenceExpression>()
.filter { genericQName in PyResolveUtil.resolveImportedElementQNameLocally(it) }
.forEach {
registerProblem(it, PyPsiBundle.message("INSP.type.hints.cannot.inherit.from.plain.generic"),
ProblemHighlightType.GENERIC_ERROR)
}
}
private fun checkGenericDuplication(superClassExpressions: List<PyExpression>) {
superClassExpressions
.asSequence()
.filter { superClass ->
val resolved = if (superClass is PyReferenceExpression) multiFollowAssignmentsChain(superClass) else listOf(superClass)
resolved
.asSequence()
.filterIsInstance<PySubscriptionExpression>()
.filter { myTypeEvalContext.maySwitchToAST(it) }
.mapNotNull { it.operand as? PyReferenceExpression }
.any { genericQName in PyResolveUtil.resolveImportedElementQNameLocally(it) }
}
.drop(1)
.forEach {
registerProblem(it, PyPsiBundle.message("INSP.type.hints.cannot.inherit.from.generic.multiple.times"),
ProblemHighlightType.GENERIC_ERROR)
}
}
private fun checkGenericCompleteness(cls: PyClass) {
var seenGeneric = false
val genericTypeVars = linkedSetOf<PsiElement>()
val nonGenericTypeVars = linkedSetOf<PsiElement>()
cls.superClassExpressions.forEach { superClass ->
val generics = collectGenerics(superClass)
generics.first?.let {
genericTypeVars.addAll(it)
seenGeneric = true
}
nonGenericTypeVars.addAll(generics.second)
}
if (seenGeneric && (nonGenericTypeVars - genericTypeVars).isNotEmpty()) {
val nonGenericTypeVarsNames = nonGenericTypeVars
.asSequence()
.filterIsInstance<PyTargetExpression>()
.mapNotNull { it.name }
.joinToString(", ")
val genericTypeVarsNames = genericTypeVars
.asSequence()
.filterIsInstance<PyTargetExpression>()
.mapNotNull { it.name }
.joinToString(", ")
registerProblem(cls.superClassExpressionList,
PyPsiBundle.message("INSP.type.hints.some.type.variables.are.not.listed.in.generic",
nonGenericTypeVarsNames, genericTypeVarsNames),
ProblemHighlightType.GENERIC_ERROR)
}
}
private fun collectGenerics(superClassExpression: PyExpression): Pair<Set<PsiElement>?, Set<PsiElement>> {
val resolvedSuperClass =
if (superClassExpression is PyReferenceExpression) multiFollowAssignmentsChain(superClassExpression)
else listOf(superClassExpression)
var seenGeneric = false
val genericTypeVars = linkedSetOf<PsiElement>()
val nonGenericTypeVars = linkedSetOf<PsiElement>()
resolvedSuperClass
.asSequence()
.filterIsInstance<PySubscriptionExpression>()
.filter { myTypeEvalContext.maySwitchToAST(it) }
.forEach { superSubscription ->
val operand = superSubscription.operand
val generic =
operand is PyReferenceExpression &&
genericQName in PyResolveUtil.resolveImportedElementQNameLocally(operand)
val index = superSubscription.indexExpression
val parameters = (index as? PyTupleExpression)?.elements ?: arrayOf(index)
val superClassTypeVars = parameters
.asSequence()
.filterIsInstance<PyReferenceExpression>()
.flatMap { multiFollowAssignmentsChain(it, this::followNotTypeVar).asSequence() }
.filterIsInstance<PyTargetExpression>()
.filter { myTypeEvalContext.getType(it) is PyGenericType }
.toSet()
if (generic) genericTypeVars.addAll(superClassTypeVars) else nonGenericTypeVars.addAll(superClassTypeVars)
seenGeneric = seenGeneric || generic
}
return Pair(if (seenGeneric) genericTypeVars else null, nonGenericTypeVars)
}
private fun checkParameters(node: PySubscriptionExpression) {
val operand = node.operand as? PyReferenceExpression ?: return
val index = node.indexExpression ?: return
val callableQName = QualifiedName.fromDottedString(PyTypingTypeProvider.CALLABLE)
val literalQName = QualifiedName.fromDottedString(PyTypingTypeProvider.LITERAL)
val literalExtQName = QualifiedName.fromDottedString(PyTypingTypeProvider.LITERAL_EXT)
val annotatedQName = QualifiedName.fromDottedString(PyTypingTypeProvider.ANNOTATED)
val annotatedExtQName = QualifiedName.fromDottedString(PyTypingTypeProvider.ANNOTATED_EXT)
val typeAliasQName = QualifiedName.fromDottedString(PyTypingTypeProvider.TYPE_ALIAS)
val typeAliasExtQName = QualifiedName.fromDottedString(PyTypingTypeProvider.TYPE_ALIAS_EXT)
val qNames = PyResolveUtil.resolveImportedElementQNameLocally(operand)
var typingOnly = true
var callableExists = false
qNames.forEach {
when (it) {
genericQName -> checkGenericParameters(index)
literalQName, literalExtQName -> checkLiteralParameter(index)
annotatedQName, annotatedExtQName -> checkAnnotatedParameter(index)
typeAliasQName, typeAliasExtQName -> reportParameterizedTypeAlias(index)
callableQName -> {
callableExists = true
checkCallableParameters(index)
}
}
typingOnly = typingOnly && it.firstComponent == PyTypingTypeProvider.TYPING
}
if (qNames.isNotEmpty() && typingOnly) {
checkTypingMemberParameters(index, callableExists)
}
}
private fun reportParameterizedTypeAlias(index: PyExpression) {
// There is another warning in the type hint context
if (!PyTypingTypeProvider.isInsideTypeHint(index, myTypeEvalContext)) {
registerProblem(index, PyPsiBundle.message("INSP.type.hints.type.alias.cannot.be.parameterized"),
ProblemHighlightType.GENERIC_ERROR)
}
}
private fun checkLiteralParameter(index: PyExpression) {
val subParameter = if (index is PySubscriptionExpression) index.operand else null
if (subParameter is PyReferenceExpression &&
PyResolveUtil
.resolveImportedElementQNameLocally(subParameter)
.any { qName -> qName.toString().let { it == PyTypingTypeProvider.LITERAL || it == PyTypingTypeProvider.LITERAL_EXT } }) {
// if `index` is like `typing.Literal[...]` and has invalid form,
// outer `typing.Literal[...]` won't be highlighted
return
}
if (PyLiteralType.fromLiteralParameter(index, myTypeEvalContext) == null) {
registerProblem(index, PyPsiBundle.message("INSP.type.hints.illegal.literal.parameter"))
}
}
private fun checkAnnotatedParameter(index: PyExpression) {
if (index !is PyTupleExpression) {
registerProblem(index, PyPsiBundle.message("INSP.type.hints.annotated.must.be.called.with.at.least.two.arguments"))
}
}
private fun checkGenericParameters(index: PyExpression) {
val parameters = (index as? PyTupleExpression)?.elements ?: arrayOf(index)
val genericParameters = mutableSetOf<PsiElement>()
parameters.forEach {
if (it !is PyReferenceExpression) {
registerProblem(it, PyPsiBundle.message("INSP.type.hints.parameters.to.generic.must.all.be.type.variables"),
ProblemHighlightType.GENERIC_ERROR)
}
else {
val type = myTypeEvalContext.getType(it)
if (type != null) {
if (type is PyGenericType || isParamSpecOrConcatenate(it, myTypeEvalContext)) {
if (!genericParameters.addAll(multiFollowAssignmentsChain(it))) {
registerProblem(it, PyPsiBundle.message("INSP.type.hints.parameters.to.generic.must.all.be.unique"),
ProblemHighlightType.GENERIC_ERROR)
}
}
else {
registerProblem(it, PyPsiBundle.message("INSP.type.hints.parameters.to.generic.must.all.be.type.variables"),
ProblemHighlightType.GENERIC_ERROR)
}
}
}
}
}
private fun checkCallableParameters(index: PyExpression) {
if (index !is PyTupleExpression) {
registerProblem(index, PyPsiBundle.message("INSP.type.hints.illegal.callable.format"), ProblemHighlightType.GENERIC_ERROR)
return
}
val parameters = index.elements
if (parameters.size > 2) {
val possiblyLastParameter = parameters[parameters.size - 2]
registerProblem(index,
PyPsiBundle.message("INSP.type.hints.illegal.callable.format"),
ProblemHighlightType.GENERIC_ERROR,
null,
TextRange.create(0, possiblyLastParameter.startOffsetInParent + possiblyLastParameter.textLength),
SurroundElementsWithSquareBracketsQuickFix())
}
else if (parameters.size < 2) {
registerProblem(index, PyPsiBundle.message("INSP.type.hints.illegal.callable.format"), ProblemHighlightType.GENERIC_ERROR)
}
else {
val first = parameters.first()
if (!isSdkAvailable(first) || isParamSpecOrConcatenate(first, myTypeEvalContext)) return
if (first !is PyListLiteralExpression && !(first is PyNoneLiteralExpression && first.isEllipsis)) {
registerProblem(first,
PyPsiBundle.message("INSP.type.hints.illegal.first.parameter"),
ProblemHighlightType.GENERIC_ERROR,
null,
if (first is PyParenthesizedExpression) ReplaceWithListQuickFix() else SurroundElementWithSquareBracketsQuickFix())
}
}
}
private fun isSdkAvailable(element: PsiElement): Boolean =
PythonSdkUtil.findPythonSdk(ModuleUtilCore.findModuleForPsiElement(element)) != null
private fun isParamSpecOrConcatenate(expression: PyExpression, context: TypeEvalContext) : Boolean =
PyTypingTypeProvider.isConcatenate(expression, context) || PyTypingTypeProvider.isParamSpec(expression, context)
private fun checkTypingMemberParameters(index: PyExpression, isCallable: Boolean) {
val parameters = if (index is PyTupleExpression) index.elements else arrayOf(index)
parameters
.asSequence()
.drop(if (isCallable) 1 else 0)
.forEach {
if (it is PyListLiteralExpression) {
registerProblem(it,
PyPsiBundle.message("INSP.type.hints.parameters.to.generic.types.must.be.types"),
ProblemHighlightType.GENERIC_ERROR,
null,
RemoveSquareBracketsQuickFix())
}
else if (it is PyReferenceExpression && multiFollowAssignmentsChain(it).any { resolved -> resolved is PyListLiteralExpression }) {
registerProblem(it, PyPsiBundle.message("INSP.type.hints.parameters.to.generic.types.must.be.types"),
ProblemHighlightType.GENERIC_ERROR)
}
}
}
private fun checkTupleMatching(expression: PyExpression) {
if (expression !is PyTupleExpression) return
val assignment = PyPsiUtils.getRealContext(expression).parent as? PyAssignmentStatement ?: return
val lhs = assignment.leftHandSideExpression ?: return
if (PyTypingTypeProvider.mapTargetsToAnnotations(lhs, expression).isEmpty() &&
(expression.elements.isNotEmpty() || assignment.rawTargets.isNotEmpty())) {
registerProblem(expression, PyPsiBundle.message("INSP.type.hints.type.comment.cannot.be.matched.with.unpacked.variables"))
}
}
private fun checkTypeCommentAndParameters(node: PyFunction) {
val functionTypeAnnotation = PyTypingTypeProvider.getFunctionTypeAnnotation(node) ?: return
val parameterTypes = functionTypeAnnotation.parameterTypeList.parameterTypes
if (parameterTypes.singleOrNull().let { it is PyNoneLiteralExpression && it.isEllipsis }) return
val actualParametersSize = node.parameterList.parameters.size
val commentParametersSize = parameterTypes.size
val cls = node.containingClass
val modifier = node.modifier
val hasSelf = cls != null && modifier != PyFunction.Modifier.STATICMETHOD
if (commentParametersSize < actualParametersSize - if (hasSelf) 1 else 0) {
registerProblem(node.typeComment, PyPsiBundle.message("INSP.type.hints.type.signature.has.too.few.arguments"))
}
else if (commentParametersSize > actualParametersSize) {
registerProblem(node.typeComment, PyPsiBundle.message("INSP.type.hints.type.signature.has.too.many.arguments"))
}
else if (hasSelf && actualParametersSize == commentParametersSize) {
val actualSelfType =
(myTypeEvalContext.getType(cls!!) as? PyInstantiableType<*>)
?.let { if (modifier == PyFunction.Modifier.CLASSMETHOD) it.toClass() else it.toInstance() }
?: return
val commentSelfType =
parameterTypes.firstOrNull()
?.let { PyTypingTypeProvider.getType(it, myTypeEvalContext) }
?.get()
?: return
if (!PyTypeChecker.match(commentSelfType, actualSelfType, myTypeEvalContext)) {
val actualSelfTypeDescription = PythonDocumentationProvider.getTypeDescription(actualSelfType, myTypeEvalContext)
val commentSelfTypeDescription = PythonDocumentationProvider.getTypeDescription(commentSelfType, myTypeEvalContext)
registerProblem(node.typeComment, PyPsiBundle.message("INSP.type.hints.type.self.not.supertype.its.class",
commentSelfTypeDescription, actualSelfTypeDescription))
}
}
}
private fun checkAnnotatedNonSelfAttribute(node: PyTargetExpression) {
val qualifier = node.qualifier ?: return
if (node.annotation == null && node.typeComment == null) return
val scopeOwner = ScopeUtil.getScopeOwner(node)
if (scopeOwner !is PyFunction) {
registerProblem(node, PyPsiBundle.message("INSP.type.hints.non.self.attribute.could.not.be.type.hinted"))
return
}
val self = scopeOwner.parameterList.parameters.firstOrNull()?.takeIf { it.isSelf }
if (self == null ||
PyUtil.multiResolveTopPriority(qualifier, resolveContext).let { it.isNotEmpty() && it.all { e -> e != self } }) {
registerProblem(node, PyPsiBundle.message("INSP.type.hints.non.self.attribute.could.not.be.type.hinted"))
}
}
private fun followNotTypingOpaque(target: PyTargetExpression): Boolean {
return !PyTypingTypeProvider.OPAQUE_NAMES.contains(target.qualifiedName)
}
private fun followNotTypeVar(target: PyTargetExpression): Boolean {
return !myTypeEvalContext.maySwitchToAST(target) || target.findAssignedValue() !is PyCallExpression
}
private fun multiFollowAssignmentsChain(referenceExpression: PyReferenceExpression,
follow: (PyTargetExpression) -> Boolean = this::followNotTypingOpaque): List<PsiElement> {
return referenceExpression.multiFollowAssignmentsChain(resolveContext, follow).mapNotNull { it.element }
}
private fun resolvesToAnyOfQualifiedNames(referenceExpr: PyReferenceExpression, vararg names: String): Boolean {
return multiFollowAssignmentsChain(referenceExpr)
.filterIsInstance<PyQualifiedNameOwner>()
.mapNotNull { it.qualifiedName }
.any { names.contains(it) }
}
}
companion object {
private class ReplaceWithTypeNameQuickFix(private val typeName: String) : LocalQuickFix {
override fun getFamilyName() = PyPsiBundle.message("QFIX.replace.with.type.name")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as? PyReferenceExpression ?: return
element.reference.handleElementRename(typeName)
}
}
private class RemoveElementQuickFix(@IntentionFamilyName private val description: String) : LocalQuickFix {
override fun getFamilyName() = description
override fun applyFix(project: Project, descriptor: ProblemDescriptor) = descriptor.psiElement.delete()
}
private class RemoveFunctionAnnotations : LocalQuickFix {
override fun getFamilyName() = PyPsiBundle.message("QFIX.remove.function.annotations")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val function = (descriptor.psiElement.parent as? PyFunction) ?: return
function.annotation?.delete()
function.parameterList.parameters
.asSequence()
.filterIsInstance<PyNamedParameter>()
.mapNotNull { it.annotation }
.forEach { it.delete() }
}
}
private class ReplaceWithTargetNameQuickFix(private val targetName: String) : LocalQuickFix {
override fun getFamilyName() = PyPsiBundle.message("QFIX.replace.with.target.name")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val old = descriptor.psiElement as? PyStringLiteralExpression ?: return
val new = PyElementGenerator.getInstance(project).createStringLiteral(old, targetName) ?: return
old.replace(new)
}
}
private class RemoveGenericParametersQuickFix : LocalQuickFix {
override fun getFamilyName() = PyPsiBundle.message("QFIX.remove.generic.parameters")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val old = descriptor.psiElement as? PySubscriptionExpression ?: return
old.replace(old.operand)
}
}
private class ReplaceWithSubscriptionQuickFix : LocalQuickFix {
override fun getFamilyName() = PyPsiBundle.message("QFIX.replace.with.square.brackets")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as? PyCallExpression ?: return
val callee = element.callee?.text ?: return
val argumentList = element.argumentList ?: return
val index = argumentList.text.let { it.substring(1, it.length - 1) }
val language = element.containingFile.language
val text = if (language == PyFunctionTypeAnnotationDialect.INSTANCE) "() -> $callee[$index]" else "$callee[$index]"
PsiFileFactory
.getInstance(project)
// it's important to create file with same language as element's file to have correct behaviour in injections
.createFileFromText(language, text)
?.let { it.firstChild.lastChild as? PySubscriptionExpression }
?.let { element.replace(it) }
}
}
private class SurroundElementsWithSquareBracketsQuickFix : LocalQuickFix {
override fun getFamilyName() = PyPsiBundle.message("QFIX.surround.with.square.brackets")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as? PyTupleExpression ?: return
val list = PyElementGenerator.getInstance(project).createListLiteral()
val originalElements = element.elements
originalElements.dropLast(1).forEach { list.add(it) }
originalElements.dropLast(2).forEach { it.delete() }
element.elements.first().replace(list)
}
}
private class SurroundElementWithSquareBracketsQuickFix : LocalQuickFix {
override fun getFamilyName() = PyPsiBundle.message("QFIX.surround.with.square.brackets")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement
val list = PyElementGenerator.getInstance(project).createListLiteral()
list.add(element)
element.replace(list)
}
}
private class ReplaceWithListQuickFix : LocalQuickFix {
override fun getFamilyName() = PyPsiBundle.message("QFIX.replace.with.square.brackets")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement
val expression = (element as? PyParenthesizedExpression)?.containedExpression ?: return
val elements = expression.let { if (it is PyTupleExpression) it.elements else arrayOf(it) }
val list = PyElementGenerator.getInstance(project).createListLiteral()
elements.forEach { list.add(it) }
element.replace(list)
}
}
private class RemoveSquareBracketsQuickFix : LocalQuickFix {
override fun getFamilyName() = PyPsiBundle.message("QFIX.remove.square.brackets")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as? PyListLiteralExpression ?: return
val subscription = PsiTreeUtil.getParentOfType(element, PySubscriptionExpression::class.java, true, ScopeOwner::class.java)
val index = subscription?.indexExpression ?: return
val newIndexElements = if (index is PyTupleExpression) {
index.elements.flatMap { if (it == element) element.elements.asList() else listOf(it) }
}
else {
element.elements.asList()
}
if (newIndexElements.size == 1) {
index.replace(newIndexElements.first())
}
else {
val newIndexText = newIndexElements.joinToString(prefix = "(", postfix = ")") { it.text }
val expression = PyElementGenerator.getInstance(project).createExpressionFromText(LanguageLevel.forElement(element), newIndexText)
val newIndex = (expression as? PyParenthesizedExpression)?.containedExpression as? PyTupleExpression ?: return
index.replace(newIndex)
}
}
}
private class ReplaceWithTypingGenericAliasQuickFix : LocalQuickFix {
override fun getFamilyName(): String = PyPsiBundle.message("QFIX.replace.with.typing.alias")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val subscription = descriptor.psiElement as? PySubscriptionExpression ?: return
val refExpr = subscription.operand as? PyReferenceExpression ?: return
val alias = PyTypingTypeProvider.TYPING_BUILTINS_GENERIC_ALIASES[refExpr.name] ?: return
val languageLevel = LanguageLevel.forElement(subscription)
val priority = if (languageLevel.isAtLeast(LanguageLevel.PYTHON35)) ImportPriority.THIRD_PARTY else ImportPriority.BUILTIN
AddImportHelper.addOrUpdateFromImportStatement(subscription.containingFile, "typing", alias, null, priority, subscription)
val newRefExpr = PyElementGenerator.getInstance(project).createExpressionFromText(languageLevel, alias)
refExpr.replace(newRefExpr)
}
}
}
}
| apache-2.0 | 460a0c996691eda6faa5fd158a4a599d | 43.673956 | 142 | 0.675293 | 5.247781 | false | false | false | false |
JetBrains/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/ui/preview/html/DefaultCodeFenceGeneratingProvider.kt | 1 | 6852 | // 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.preview.html
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import org.intellij.markdown.MarkdownTokenTypes
import org.intellij.markdown.ast.ASTNode
import org.intellij.markdown.ast.getTextInNode
import org.intellij.markdown.html.GeneratingProvider
import org.intellij.markdown.html.HtmlGenerator
import org.intellij.markdown.html.entities.EntityConverter
import org.intellij.plugins.markdown.extensions.CodeFenceGeneratingProvider
import org.intellij.plugins.markdown.extensions.common.highlighter.MarkdownCodeFencePreviewHighlighter
import org.intellij.plugins.markdown.extensions.jcef.commandRunner.CommandRunnerExtension
internal class DefaultCodeFenceGeneratingProvider(
private val cacheProviders: Array<CodeFenceGeneratingProvider>,
private val project: Project? = null,
private val file: VirtualFile? = null
): GeneratingProvider {
private fun pluginGeneratedHtml(language: String?, codeFenceContent: String, codeFenceRawContent: String, node: ASTNode): String {
if (language == null) {
return insertCodeOffsets(codeFenceContent, node)
}
val html = cacheProviders
.filter { it.isApplicable(language) }.stream()
.findFirst()
.map {
if (it is MarkdownCodeFencePreviewHighlighter && file != null) {
it.generateHtmlForFile(language, codeFenceRawContent, node, file)
} else {
it.generateHtml(language, codeFenceRawContent, node)
}
}
.orElse(insertCodeOffsets(codeFenceContent, node))
return processCodeBlock(codeFenceRawContent, language) + html
}
private fun processCodeBlock(codeFenceRawContent: String, language: String): String {
return file?.let(CommandRunnerExtension::getRunnerByFile)?.processCodeBlock(codeFenceRawContent, language) ?: ""
}
private fun processCodeLine(rawCodeLine: String): String {
return file?.let(CommandRunnerExtension::getRunnerByFile)?.processCodeLine(rawCodeLine, true) ?: ""
}
override fun processNode(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode) {
val indentBefore = node.getTextInNode(text).commonPrefixWith(" ".repeat(10)).length
visitor.consumeHtml("<pre class=\"code-fence\" ${HtmlGenerator.getSrcPosAttribute(node)}>")
addCopyButton(visitor, collectFenceText(node, text).trim())
var state = 0
var childrenToConsider = node.children
if (childrenToConsider.last().type == MarkdownTokenTypes.CODE_FENCE_END) {
childrenToConsider = childrenToConsider.subList(0, childrenToConsider.size - 1)
}
var lastChildWasContent = false
val attributes = ArrayList<String>()
var language: String? = null
val codeFenceRawContent = StringBuilder()
val codeFenceContent = StringBuilder()
for (child in childrenToConsider) {
if (state == 1 && child.type in listOf(MarkdownTokenTypes.CODE_FENCE_CONTENT, MarkdownTokenTypes.EOL)) {
codeFenceRawContent.append(HtmlGenerator.trimIndents(codeFenceRawText(text, child), indentBefore))
codeFenceContent.append(HtmlGenerator.trimIndents(codeFenceText(text, child), indentBefore))
lastChildWasContent = child.type == MarkdownTokenTypes.CODE_FENCE_CONTENT
}
if (state == 0 && child.type == MarkdownTokenTypes.FENCE_LANG) {
language = HtmlGenerator.leafText(text, child).toString().trim()
attributes.add("class=\"language-${language.split(" ").joinToString(separator = "-")}\"")
}
if (state == 0 && child.type == MarkdownTokenTypes.EOL) {
visitor.consumeTagOpen(node, "code", *attributes.toTypedArray())
state = 1
}
}
val rawContentResult = codeFenceRawContent.toString()
if (state == 1) {
visitor.consumeHtml(
pluginGeneratedHtml(language, codeFenceContent.toString(), rawContentResult, node)
)
}
if (state == 0) {
visitor.consumeTagOpen(node, "code", *attributes.toTypedArray())
}
if (lastChildWasContent) {
visitor.consumeHtml("\n")
}
visitor.consumeHtml("</code></pre>")
}
private fun collectFenceText(node: ASTNode, allText: String): String {
return buildString {
collectFenceText(this, node, allText)
}
}
private fun collectFenceText(builder: StringBuilder, node: ASTNode, allText: String) {
if (node.type == MarkdownTokenTypes.CODE_FENCE_CONTENT || node.type == MarkdownTokenTypes.EOL) {
builder.append(codeFenceRawText(allText, node))
}
for (child in node.children) {
collectFenceText(builder, child, allText)
}
}
private fun addCopyButton(visitor: HtmlGenerator.HtmlGeneratingVisitor, content: String) {
val encodedContent = PreviewEncodingUtil.encodeContent(content)
// language=HTML
val html = """
<div class="code-fence-highlighter-copy-button" data-fence-content="$encodedContent">
<img class="code-fence-highlighter-copy-button-icon">
</div>
""".trimIndent()
visitor.consumeHtml(html)
}
private fun codeFenceRawText(text: String, node: ASTNode): CharSequence {
return when (node.type) {
MarkdownTokenTypes.BLOCK_QUOTE -> ""
else -> node.getTextInNode(text)
}
}
private fun codeFenceText(text: String, node: ASTNode): CharSequence =
if (node.type != MarkdownTokenTypes.BLOCK_QUOTE) HtmlGenerator.leafText(text, node, false) else ""
private fun insertCodeOffsets(content: String, node: ASTNode): String {
val lines = ArrayList<String>()
val baseOffset = calcCodeFenceContentBaseOffset(node)
var left = baseOffset
for (line in content.lines()) {
val right = left + line.length
lines.add("<span ${HtmlGenerator.SRC_ATTRIBUTE_NAME}='$left..${left + line.length}'>${processCodeLine(line) + escape(line)}</span>")
left = right + 1
}
return lines.joinToString(
separator = "\n",
prefix = "<span ${HtmlGenerator.SRC_ATTRIBUTE_NAME}='${node.startOffset}..$baseOffset'/>",
postfix = node.children.find { it.type == MarkdownTokenTypes.CODE_FENCE_END }?.let {
"<span ${HtmlGenerator.SRC_ATTRIBUTE_NAME}='${it.startOffset}..${it.endOffset}'/>"
} ?: ""
)
}
companion object {
internal fun calcCodeFenceContentBaseOffset(node: ASTNode): Int {
val baseNode = node.children.find { it.type == MarkdownTokenTypes.FENCE_LANG }
?: node.children.find { it.type == MarkdownTokenTypes.CODE_FENCE_START }
return baseNode?.let { it.endOffset + 1 } ?: node.startOffset
}
internal fun escape(html: String) = EntityConverter.replaceEntities(
html,
processEntities = true,
processEscapes = false
)
}
}
| apache-2.0 | e23858de27fe40fba7b802bbee6b544f | 40.277108 | 158 | 0.710012 | 4.386684 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/KotlinCodeFragmentFactory.kt | 1 | 13385 | // 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.evaluate
import com.intellij.debugger.DebuggerManagerEx
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.debugger.engine.evaluation.CodeFragmentFactory
import com.intellij.debugger.engine.evaluation.TextWithImports
import com.intellij.debugger.engine.events.DebuggerCommandImpl
import com.intellij.debugger.impl.DebuggerContextImpl
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiTypesUtil
import com.intellij.util.IncorrectOperationException
import com.intellij.util.concurrency.Semaphore
import com.sun.jdi.AbsentInformationException
import com.sun.jdi.InvalidStackFrameException
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.base.projectStructure.hasKotlinJvmRuntime
import org.jetbrains.kotlin.idea.core.syncNonBlockingReadAction
import org.jetbrains.kotlin.idea.core.util.CodeFragmentUtils
import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.DebugLabelPropertyDescriptorProvider
import org.jetbrains.kotlin.idea.debugger.core.getContextElement
import org.jetbrains.kotlin.idea.debugger.base.util.hopelessAware
import org.jetbrains.kotlin.idea.j2k.J2kPostProcessor
import org.jetbrains.kotlin.idea.j2k.convertToKotlin
import org.jetbrains.kotlin.idea.j2k.j2kText
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.j2k.AfterConversionPass
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded
import org.jetbrains.kotlin.types.KotlinType
import java.util.concurrent.atomic.AtomicReference
class KotlinCodeFragmentFactory : CodeFragmentFactory() {
override fun createCodeFragment(item: TextWithImports, context: PsiElement?, project: Project): JavaCodeFragment {
val contextElement = getContextElement(context)
val codeFragment = KtBlockCodeFragment(project, "fragment.kt", item.text, initImports(item.imports), contextElement)
supplyDebugInformation(codeFragment, context)
codeFragment.putCopyableUserData(CodeFragmentUtils.RUNTIME_TYPE_EVALUATOR) { expression: KtExpression ->
val debuggerContext = DebuggerManagerEx.getInstanceEx(project).context
val debuggerSession = debuggerContext.debuggerSession
if (debuggerSession == null || debuggerContext.suspendContext == null) {
null
} else {
val semaphore = Semaphore()
semaphore.down()
val nameRef = AtomicReference<KotlinType>()
val worker = object : KotlinRuntimeTypeEvaluator(
null, expression, debuggerContext, ProgressManager.getInstance().progressIndicator!!
) {
override fun typeCalculationFinished(type: KotlinType?) {
nameRef.set(type)
semaphore.up()
}
}
debuggerContext.debugProcess?.managerThread?.invoke(worker)
for (i in 0..50) {
ProgressManager.checkCanceled()
if (semaphore.waitFor(20)) break
}
nameRef.get()
}
}
if (contextElement != null && contextElement !is KtElement) {
codeFragment.putCopyableUserData(KtCodeFragment.FAKE_CONTEXT_FOR_JAVA_FILE) {
val emptyFile = createFakeFileWithJavaContextElement("", contextElement)
val debuggerContext = DebuggerManagerEx.getInstanceEx(project).context
val debuggerSession = debuggerContext.debuggerSession
if ((debuggerSession == null || debuggerContext.suspendContext == null) &&
!isUnitTestMode()
) {
LOG.warn("Couldn't create fake context element for java file, debugger isn't paused on breakpoint")
return@putCopyableUserData emptyFile
}
val frameInfo = getFrameInfo(contextElement, debuggerContext) ?: run {
val position = "${debuggerContext.sourcePosition?.file?.name}:${debuggerContext.sourcePosition?.line}"
LOG.warn("Couldn't get info about 'this' and local variables for $position")
return@putCopyableUserData emptyFile
}
val fakeFunctionText = buildString {
append("fun ")
val thisType = frameInfo.thisObject?.asProperty()?.typeReference?.typeElement?.unwrapNullableType()
if (thisType != null) {
append(thisType.text).append('.')
}
append(FAKE_JAVA_CONTEXT_FUNCTION_NAME).append("() {\n")
for (variable in frameInfo.variables) {
val text = variable.asProperty()?.text ?: continue
append(" ").append(text).append("\n")
}
// There should be at least one declaration inside the function (or 'fakeContext' below won't work).
append(" val _debug_context_val = 1\n")
append("}")
}
val fakeFile = createFakeFileWithJavaContextElement(fakeFunctionText, contextElement)
val fakeFunction = fakeFile.declarations.firstOrNull() as? KtFunction
val fakeContext = fakeFunction?.bodyBlockExpression?.statements?.lastOrNull()
return@putCopyableUserData fakeContext ?: emptyFile
}
}
return codeFragment
}
private fun KtTypeElement.unwrapNullableType(): KtTypeElement {
return if (this is KtNullableType) innerType ?: this else this
}
private fun supplyDebugInformation(codeFragment: KtCodeFragment, context: PsiElement?) {
val project = codeFragment.project
val debugProcess = getDebugProcess(project, context) ?: return
DebugLabelPropertyDescriptorProvider(codeFragment, debugProcess).supplyDebugLabels()
}
private fun getDebugProcess(project: Project, context: PsiElement?): DebugProcessImpl? {
return if (isUnitTestMode()) {
context?.getCopyableUserData(DEBUG_CONTEXT_FOR_TESTS)?.debugProcess
} else {
DebuggerManagerEx.getInstanceEx(project).context.debugProcess
}
}
private fun getFrameInfo(contextElement: PsiElement?, debuggerContext: DebuggerContextImpl): FrameInfo? {
val semaphore = Semaphore()
semaphore.down()
var frameInfo: FrameInfo? = null
val worker = object : DebuggerCommandImpl() {
override fun action() {
try {
val frameProxy = hopelessAware {
if (isUnitTestMode()) {
contextElement?.getCopyableUserData(DEBUG_CONTEXT_FOR_TESTS)?.frameProxy
} else {
debuggerContext.frameProxy
}
}
frameInfo = FrameInfo.from(debuggerContext.project, frameProxy)
} catch (ignored: AbsentInformationException) {
// Debug info unavailable
} catch (ignored: InvalidStackFrameException) {
// Thread is resumed, the frame we have is not valid anymore
} finally {
semaphore.up()
}
}
}
debuggerContext.debugProcess?.managerThread?.invoke(worker)
for (i in 0..50) {
if (semaphore.waitFor(20)) break
}
return frameInfo
}
private fun initImports(imports: String?): String? {
if (!imports.isNullOrEmpty()) {
return imports.split(KtCodeFragment.IMPORT_SEPARATOR)
.mapNotNull { fixImportIfNeeded(it) }
.joinToString(KtCodeFragment.IMPORT_SEPARATOR)
}
return null
}
private fun fixImportIfNeeded(import: String): String? {
// skip arrays
if (import.endsWith("[]")) {
return fixImportIfNeeded(import.removeSuffix("[]").trim())
}
// skip primitive types
if (PsiTypesUtil.boxIfPossible(import) != import) {
return null
}
return import
}
override fun createPresentationCodeFragment(item: TextWithImports, context: PsiElement?, project: Project): JavaCodeFragment {
val kotlinCodeFragment = createCodeFragment(item, context, project)
if (PsiTreeUtil.hasErrorElements(kotlinCodeFragment) && kotlinCodeFragment is KtCodeFragment) {
val javaExpression = try {
PsiElementFactory.getInstance(project).createExpressionFromText(item.text, context)
} catch (e: IncorrectOperationException) {
null
}
val importList = try {
kotlinCodeFragment.importsAsImportList()?.let {
(PsiFileFactory.getInstance(project).createFileFromText(
"dummy.java", JavaFileType.INSTANCE, it.text
) as? PsiJavaFile)?.importList
}
} catch (e: IncorrectOperationException) {
null
}
if (javaExpression != null && !PsiTreeUtil.hasErrorElements(javaExpression)) {
var convertedFragment: KtExpressionCodeFragment? = null
project.executeWriteCommand(KotlinDebuggerEvaluationBundle.message("j2k.expression")) {
try {
val (elementResults, _, conversionContext) = javaExpression.convertToKotlin() ?: return@executeWriteCommand
val newText = elementResults.singleOrNull()?.text
val newImports = importList?.j2kText()
if (newText != null) {
convertedFragment = KtExpressionCodeFragment(
project,
kotlinCodeFragment.name,
newText,
newImports,
kotlinCodeFragment.context
)
AfterConversionPass(project, J2kPostProcessor(formatCode = false))
.run(
convertedFragment!!,
conversionContext,
range = null,
onPhaseChanged = null
)
}
} catch (e: Throwable) {
// ignored because text can be invalid
LOG.error("Couldn't convert expression:\n`${javaExpression.text}`", e)
}
}
return convertedFragment ?: kotlinCodeFragment
}
}
return kotlinCodeFragment
}
override fun isContextAccepted(contextElement: PsiElement?): Boolean = runReadAction {
when {
// PsiCodeBlock -> DummyHolder -> originalElement
contextElement is PsiCodeBlock -> isContextAccepted(contextElement.context?.context)
contextElement == null -> false
contextElement.language == KotlinFileType.INSTANCE.language -> true
contextElement.language == JavaFileType.INSTANCE.language -> {
val project = contextElement.project
val scope = contextElement.resolveScope
syncNonBlockingReadAction(project) { scope.hasKotlinJvmRuntime(project) }
}
else -> false
}
}
override fun getFileType(): KotlinFileType = KotlinFileType.INSTANCE
override fun getEvaluatorBuilder() = KotlinEvaluatorBuilder
companion object {
private val LOG = Logger.getInstance(this::class.java)
@get:TestOnly
val DEBUG_CONTEXT_FOR_TESTS: Key<DebuggerContextImpl> = Key.create("DEBUG_CONTEXT_FOR_TESTS")
const val FAKE_JAVA_CONTEXT_FUNCTION_NAME = "_java_locals_debug_fun_"
}
private fun createFakeFileWithJavaContextElement(funWithLocalVariables: String, javaContext: PsiElement): KtFile {
val javaFile = javaContext.containingFile as? PsiJavaFile
val sb = StringBuilder()
javaFile?.packageName?.takeUnless { it.isBlank() }?.let {
sb.append("package ").append(it.quoteIfNeeded()).append("\n")
}
javaFile?.importList?.let { sb.append(it.text).append("\n") }
sb.append(funWithLocalVariables)
return KtPsiFactory.contextual(javaContext).createFile("fakeFileForJavaContextInDebugger.kt", sb.toString())
}
}
| apache-2.0 | ad291bfc074981ee623262c3e3da41ce | 42.74183 | 131 | 0.618229 | 5.893879 | false | false | false | false |
allotria/intellij-community | build/tasks/src/org/jetbrains/intellij/build/tasks/reorderJars.kt | 1 | 9043 | // 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.intellij.build.tasks
import com.intellij.util.zip.ImmutableZipEntry
import com.intellij.util.zip.ImmutableZipFile
import it.unimi.dsi.fastutil.ints.IntSet
import org.jetbrains.intellij.build.io.*
import java.lang.System.Logger
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.channels.FileChannel
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
import java.util.concurrent.Callable
import java.util.concurrent.Future
import java.util.concurrent.atomic.AtomicBoolean
// see JarMemoryLoader.SIZE_ENTRY
internal const val SIZE_ENTRY = "META-INF/jb/$\$size$$"
internal const val PACKAGE_INDEX_NAME = "__packageIndex__"
@Suppress("ReplaceJavaStaticMethodWithKotlinAnalog")
private val excludedLibJars = java.util.Set.of("testFramework.core.jar", "testFramework.jar", "testFramework-java.jar")
fun main(args: Array<String>) {
System.setProperty("java.util.logging.SimpleFormatter.format", "%5\$s %n")
reorderJars(homeDir = Path.of(args[0]),
targetDir = Path.of(args[1]),
bootClassPathJarNames = listOf("bootstrap.jar", "util.jar", "jdom.jar", "log4j.jar", "jna.jar"),
stageDir = Path.of(args[2]),
antLibDir = null,
platformPrefix = "idea", logger = System.getLogger(""))
}
fun reorderJars(homeDir: Path,
targetDir: Path,
bootClassPathJarNames: Iterable<String>,
stageDir: Path,
platformPrefix: String,
antLibDir: Path?,
logger: Logger) {
val libDir = homeDir.resolve("lib")
val ideaDirsParent = Files.createTempDirectory("idea-reorder-jars-")
val classLoadingLogFile = stageDir.resolve("class-loading-log.txt")
try {
@Suppress("SpellCheckingInspection")
runJava(
mainClass = "com.intellij.idea.Main",
args = listOf("jarOrder", classLoadingLogFile.toString()),
jvmArgs = listOfNotNull("-Xmx1024m",
"-Didea.record.classpath.info=true",
"-Didea.system.path=${ideaDirsParent.resolve("system")}",
"-Didea.config.path=${ideaDirsParent.resolve("config")}",
"-Didea.home.path=$homeDir",
"-Didea.platform.prefix=$platformPrefix"),
classPath = bootClassPathJarNames.map { libDir.resolve(it).toString() },
logger = logger
)
}
finally {
deleteDir(ideaDirsParent)
}
val sourceToNames = readClassLoadingLog(classLoadingLogFile, homeDir)
val coreClassLoaderFiles = computeAppClassPath(sourceToNames, libDir, antLibDir)
logger.log(Logger.Level.INFO, "Reordering *.jar files in $homeDir")
doReorderJars(sourceToNames = sourceToNames, sourceDir = homeDir, targetDir = targetDir, logger = logger)
val resultFile = libDir.resolve("classpath.txt")
Files.writeString(resultFile, coreClassLoaderFiles.joinToString(separator = "\n") { libDir.relativize(it).toString() })
}
private fun computeAppClassPath(sourceToNames: Map<Path, List<String>>, libDir: Path, antLibDir: Path?): LinkedHashSet<Path> {
val result = LinkedHashSet<Path>()
// add first - should be listed first
sourceToNames.keys.asSequence().filter { it.parent == libDir }.toCollection(result)
addJarsFromDir(libDir) { paths ->
// sort to ensure stable performance results
result.addAll(paths.filter { !excludedLibJars.contains(it.fileName.toString()) }.sorted())
}
if (antLibDir != null) {
val distAntLib = libDir.resolve("ant/lib")
addJarsFromDir(antLibDir) { paths ->
// sort to ensure stable performance results
result.addAll(paths.map { distAntLib.resolve(antLibDir.relativize(it)) }.sorted())
}
}
return result
}
private inline fun addJarsFromDir(dir: Path, consumer: (Sequence<Path>) -> Unit) {
Files.newDirectoryStream(dir).use { stream ->
consumer(stream.asSequence().filter { it.toString().endsWith(".jar") })
}
}
internal fun readClassLoadingLog(classLoadingLogFile: Path, rootDir: Path): Map<Path, List<String>> {
val sourceToNames = LinkedHashMap<Path, MutableList<String>>()
Files.lines(classLoadingLogFile).use { lines ->
lines.forEach {
val data = it.split(':', limit = 2)
val source = rootDir.resolve(data[1])
sourceToNames.computeIfAbsent(source) { mutableListOf() }.add(data[0])
}
}
return sourceToNames
}
internal fun doReorderJars(sourceToNames: Map<Path, List<String>>,
sourceDir: Path,
targetDir: Path,
logger: Logger): List<PackageIndexEntry> {
val executor = createIoTaskExecutorPool()
val results = mutableListOf<Future<PackageIndexEntry?>>()
val errorOccurred = AtomicBoolean()
for ((jarFile, orderedNames) in sourceToNames.entries) {
if (!Files.exists(jarFile)) {
logger.log(Logger.Level.ERROR, "Cannot find jar: $jarFile")
continue
}
results.add(executor.submit(Callable {
if (errorOccurred.get()) {
return@Callable null
}
try {
logger.info("Reorder jar: $jarFile")
reorderJar(jarFile, orderedNames, if (targetDir == sourceDir) jarFile else targetDir.resolve(sourceDir.relativize(jarFile)))
}
catch (e: Throwable) {
errorOccurred.set(true)
throw e
}
}))
}
executor.shutdown()
val index = ArrayList<PackageIndexEntry>(sourceToNames.size)
for (future in results) {
index.add(future.get() ?: continue)
}
return index
}
data class PackageIndexEntry(val path: Path, val classPackageIndex: IntSet, val resourcePackageIndex: IntSet)
fun reorderJar(jarFile: Path, orderedNames: List<String>, resultJarFile: Path): PackageIndexEntry {
val orderedNameToIndex = HashMap<String, Int>(orderedNames.size)
for ((index, orderedName) in orderedNames.withIndex()) {
orderedNameToIndex.put(orderedName, index)
}
val tempJarFile = resultJarFile.resolveSibling("${resultJarFile.fileName}_reorder.jar")
val packageIndexBuilder = PackageIndexBuilder()
ImmutableZipFile.load(jarFile).use { zipFile ->
// ignore existing package index on reorder - a new one will computed even if it is the same, do not optimize for simplicity
val entries = zipFile.entries.asSequence().filter { it.name != PACKAGE_INDEX_NAME }.toMutableList()
entries.sortWith(Comparator { o1, o2 ->
val o2p = o2.name
if ("META-INF/plugin.xml" == o2p) {
return@Comparator Int.MAX_VALUE
}
val o1p = o1.name
if ("META-INF/plugin.xml" == o1p) {
-Int.MAX_VALUE
}
else {
val i1 = orderedNameToIndex.get(o1p)
if (i1 == null) {
if (orderedNameToIndex.containsKey(o2p)) 1 else 0
}
else {
val i2 = orderedNameToIndex.get(o2p)
if (i2 == null) -1 else (i1 - i2)
}
}
})
packageIndexBuilder.add(entries)
Files.createDirectories(tempJarFile.parent)
FileChannel.open(tempJarFile, RW_CREATE_NEW).use { outChannel ->
val zipCreator = ZipFileWriter(outChannel, deflater = null)
zipCreator.writeUncompressedEntry(SIZE_ENTRY, 2) {
it.putShort((orderedNames.size and 0xffff).toShort())
}
packageIndexBuilder.writePackageIndex(zipCreator)
writeEntries(entries, zipCreator, zipFile)
writeDirs(packageIndexBuilder.dirsToCreate, zipCreator)
val comment = ByteBuffer.allocate(16).order(ByteOrder.LITTLE_ENDIAN)
comment.putInt(1759251304)
comment.putShort(orderedNames.size.toShort())
comment.flip()
zipCreator.finish(comment)
}
}
try {
Files.move(tempJarFile, resultJarFile, StandardCopyOption.REPLACE_EXISTING)
}
catch (e: Exception) {
throw e
}
finally {
Files.deleteIfExists(tempJarFile)
}
return PackageIndexEntry(path = resultJarFile, packageIndexBuilder.classPackageHashSet, packageIndexBuilder.resourcePackageHashSet)
}
internal fun writeDirs(dirsToCreate: Set<String>, zipCreator: ZipFileWriter) {
if (dirsToCreate.isEmpty()) {
return
}
val list = dirsToCreate.toMutableList()
list.sort()
for (name in list) {
// name in our ImmutableZipEntry doesn't have ending slash
zipCreator.addDirEntry(if (name.endsWith('/')) name else "$name/")
}
}
internal fun writeEntries(entries: List<ImmutableZipEntry>, zipCreator: ZipFileWriter, sourceZipFile: ImmutableZipFile) {
for (entry in entries) {
val name = entry.name
if (entry.isDirectory) {
continue
}
// by intention not the whole original ZipArchiveEntry is copied,
// but only name, method and size are copied - that's enough and should be enough
val data = entry.getByteBuffer(sourceZipFile)
try {
zipCreator.writeUncompressedEntry(name, data)
}
finally {
entry.releaseBuffer(data)
}
}
} | apache-2.0 | 03e6c5a21d2cfdb281b1b089be6fca02 | 34.888889 | 140 | 0.679421 | 4.129224 | false | false | false | false |
PaystackHQ/paystack-android | paystack/src/main/java/co/paystack/android/api/request/ValidateTransactionParams.kt | 1 | 544 | package co.paystack.android.api.request
import co.paystack.android.api.utils.pruneNullValues
data class ValidateTransactionParams(
val transactionId: String,
val token: String? = null,
val deviceId: String? = null
) {
fun toRequestMap() = mapOf(
FIELD_TOKEN to token,
FIELD_DEVICE to deviceId,
FIELD_TRANS to transactionId,
).pruneNullValues()
companion object {
const val FIELD_TOKEN = "token"
const val FIELD_DEVICE = "device"
const val FIELD_TRANS = "trans"
}
}
| apache-2.0 | 3a955c5a95953a751b6dc9b1c8124a9a | 24.904762 | 52 | 0.659926 | 4.090226 | false | false | false | false |
zdary/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/dsl/MavenDependencyModificator.kt | 1 | 13710 | // 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.jetbrains.idea.maven.dsl
import com.intellij.buildsystem.model.DeclaredDependency
import com.intellij.buildsystem.model.unified.UnifiedCoordinates
import com.intellij.buildsystem.model.unified.UnifiedDependency
import com.intellij.buildsystem.model.unified.UnifiedDependencyRepository
import com.intellij.externalSystem.ExternalDependencyModificator
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.xml.XmlFile
import com.intellij.psi.xml.XmlTag
import com.intellij.util.xml.DomUtil
import com.intellij.util.xml.GenericDomValue
import org.jetbrains.annotations.NotNull
import org.jetbrains.idea.maven.dom.MavenDomElement
import org.jetbrains.idea.maven.dom.MavenDomUtil
import org.jetbrains.idea.maven.dom.converters.MavenDependencyCompletionUtil
import org.jetbrains.idea.maven.dom.model.MavenDomDependency
import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel
import org.jetbrains.idea.maven.dom.model.MavenDomRepository
import org.jetbrains.idea.maven.model.MavenConstants.SCOPE_COMPILE
import org.jetbrains.idea.maven.model.MavenId
import org.jetbrains.idea.maven.project.MavenProject
import org.jetbrains.idea.maven.project.MavenProjectBundle
import org.jetbrains.idea.maven.project.MavenProjectsManager
val mavenTopLevelElementsOrder = listOf(
"modelVersion",
"parent",
"groupId",
"artifactId",
"version",
"packaging",
"properties",
"name",
"description",
"url",
"inceptionYear",
"licenses",
"organization",
"developers",
"contributors",
"modules",
"dependencyManagement",
"dependencies",
"build",
"reporting",
"issueManagement",
"ciManagement",
"mailingLists",
"scm",
"prerequisites",
"repositories",
"pluginRepositories",
"distributionManagement",
"profiles"
)
val elementsBeforeDependencies = elementsBefore("dependencies")
val elementsBeforeRepositories = elementsBefore("repositories")
fun elementsBefore(s: String): Set<String> {
return mavenTopLevelElementsOrder.takeWhile { it != s }
.toSet()
}
class MavenDependencyModificator(private val myProject: Project) : ExternalDependencyModificator {
private val myProjectsManager: MavenProjectsManager = MavenProjectsManager.getInstance(myProject)
private val myDocumentManager: PsiDocumentManager = PsiDocumentManager.getInstance(myProject)
private fun addDependenciesTagIfNotExists(psiFile: XmlFile, model: MavenDomProjectModel) {
addTagIfNotExists(psiFile, model.dependencies, elementsBeforeDependencies)
}
private fun addRepositoriesTagIfNotExists(psiFile: XmlFile, model: MavenDomProjectModel) {
addTagIfNotExists(psiFile, model.repositories, elementsBeforeRepositories)
}
private fun addTagIfNotExists(psiFile: XmlFile, element: MavenDomElement, elementsBefore: Set<String>) {
if (element.exists()) {
return
}
val rootTag = psiFile.rootTag
if (rootTag == null) {
element.ensureTagExists()
return
}
val children = rootTag.children
if (children == null || children.isEmpty()) {
element.ensureTagExists()
return
}
val lastOrNull = children
.mapNotNull { it as? XmlTag }
.lastOrNull { elementsBefore.contains(it.name) }
val child = rootTag.createChildTag(element.xmlElementName, rootTag.namespace, null, false)
rootTag.addAfter(child, lastOrNull)
}
private fun getDependenciesModel(module: Module,
groupId: String, artifactId: String): Pair<MavenDomProjectModel, MavenDomDependency?> {
val project: MavenProject = myProjectsManager.findProject(module) ?: throw IllegalArgumentException(MavenProjectBundle.message(
"maven.project.not.found.for", module.name))
return ReadAction.compute<Pair<MavenDomProjectModel, MavenDomDependency?>, Throwable> {
val model = MavenDomUtil.getMavenDomProjectModel(myProject, project.file) ?: throw IllegalStateException(
MavenProjectBundle.message("maven.model.error", module.name))
val managedDependency = MavenDependencyCompletionUtil.findManagedDependency(model, myProject, groupId, artifactId)
return@compute Pair(model, managedDependency)
}
}
override fun supports(module: Module): Boolean {
return myProjectsManager.isMavenizedModule(module)
}
override fun addDependency(module: Module, descriptor: UnifiedDependency) {
requireNotNull(descriptor.coordinates.groupId)
requireNotNull(descriptor.coordinates.version)
requireNotNull(descriptor.coordinates.artifactId)
val mavenId = descriptor.coordinates.toMavenId()
val (model, managedDependency) = getDependenciesModel(module, mavenId.groupId!!, mavenId.artifactId!!)
val psiFile = DomUtil.getFile(model)
WriteCommandAction.writeCommandAction(myProject, psiFile).compute<Unit, Throwable> {
addDependenciesTagIfNotExists(psiFile, model)
val dependency = MavenDomUtil.createDomDependency(model, null)
dependency.groupId.stringValue = mavenId.groupId
dependency.artifactId.stringValue = mavenId.artifactId
val scope = toMavenScope(descriptor.scope, managedDependency?.scope?.stringValue)
scope?.let { dependency.scope.stringValue = it }
if (managedDependency == null || managedDependency.version.stringValue != mavenId.version) {
dependency.version.stringValue = mavenId.version
}
saveFile(psiFile)
}
}
override fun updateDependency(module: Module, oldDescriptor: UnifiedDependency, newDescriptor: UnifiedDependency) {
requireNotNull(newDescriptor.coordinates.groupId)
requireNotNull(newDescriptor.coordinates.version)
requireNotNull(newDescriptor.coordinates.artifactId)
val oldMavenId = oldDescriptor.coordinates.toMavenId()
val newMavenId = newDescriptor.coordinates.toMavenId()
val (model, managedDependency) = ReadAction.compute<Pair<MavenDomProjectModel, MavenDomDependency?>, Throwable> {
getDependenciesModel(module, oldMavenId.groupId!!, oldMavenId.artifactId!!)
}
val psiFile = managedDependency?.let(DomUtil::getFile) ?: DomUtil.getFile(model)
WriteCommandAction.writeCommandAction(myProject, psiFile).compute<Unit, Throwable> {
if (managedDependency != null) {
val parentModel = managedDependency.getParentOfType(MavenDomProjectModel::class.java, true)
if (parentModel != null) {
updateVariableOrValue(parentModel, managedDependency.version, newMavenId.version!!)
}
else {
managedDependency.version.stringValue = newDescriptor.coordinates.version
}
}
else {
for (dep in model.dependencies.dependencies) {
if (dep.artifactId.stringValue == oldMavenId.artifactId && dep.groupId.stringValue == oldMavenId.groupId) {
updateVariableOrValue(model, dep.artifactId, newMavenId.artifactId!!)
updateVariableOrValue(model, dep.groupId, newMavenId.groupId!!)
updateVariableOrValue(model, dep.version, newMavenId.version!!)
}
}
}
saveFile(psiFile)
}
}
override fun removeDependency(module: Module, descriptor: UnifiedDependency) {
requireNotNull(descriptor.coordinates.groupId)
requireNotNull(descriptor.coordinates.version)
val mavenId = descriptor.coordinates.toMavenId()
val (model, _) = getDependenciesModel(module, mavenId.groupId!!, mavenId.artifactId!!)
val psiFile = DomUtil.getFile(model)
WriteCommandAction.writeCommandAction(myProject, psiFile).compute<Unit, Throwable> {
for (dep in model.dependencies.dependencies) {
if (dep.artifactId.stringValue == mavenId.artifactId && dep.groupId.stringValue == mavenId.groupId) {
dep.xmlTag?.delete()
}
}
if (model.dependencies.dependencies.isEmpty()) {
model.dependencies.xmlTag?.delete()
}
saveFile(psiFile)
}
}
override fun addRepository(module: Module, repository: UnifiedDependencyRepository) {
val project: MavenProject = myProjectsManager.findProject(module) ?: throw IllegalArgumentException(MavenProjectBundle.message(
"maven.project.not.found.for", module.name))
val model = ReadAction.compute<MavenDomProjectModel, Throwable> {
MavenDomUtil.getMavenDomProjectModel(myProject, project.file) ?: throw IllegalStateException(
MavenProjectBundle.message("maven.model.error", module.name))
}
for (repo in model.repositories.repositories) {
if (repo.url.stringValue?.trimLastSlash() == repository.url?.trimLastSlash()) {
return
}
}
val psiFile = DomUtil.getFile(model)
WriteCommandAction.writeCommandAction(myProject, psiFile).compute<Unit, Throwable> {
addRepositoriesTagIfNotExists(psiFile, model)
val repoTag = model.repositories.addRepository()
repository.id?.let { repoTag.id.stringValue = it }
repository.name?.let { repoTag.name.stringValue = it }
repository.url.let { repoTag.url.stringValue = it }
saveFile(psiFile)
}
}
override fun deleteRepository(module: Module, repository: UnifiedDependencyRepository) {
val project: MavenProject = myProjectsManager.findProject(module) ?: throw IllegalArgumentException(MavenProjectBundle.message(
"maven.project.not.found.for", module.name))
val (model, repo) = ReadAction.compute<Pair<MavenDomProjectModel, MavenDomRepository?>, Throwable> {
val model = MavenDomUtil.getMavenDomProjectModel(myProject, project.file) ?: throw IllegalStateException(
MavenProjectBundle.message("maven.model.error", module.name))
for (repo in model.repositories.repositories) {
if (repo.url.stringValue?.trimLastSlash() == repository.url?.trimLastSlash()) {
return@compute Pair(model, repo)
}
}
return@compute null
}
if (repo == null) return
val psiFile = DomUtil.getFile(repo)
WriteCommandAction.writeCommandAction(myProject, psiFile).compute<Unit, Throwable> {
repo.xmlTag?.delete()
if(model.repositories.repositories.isEmpty()) {
model.repositories.xmlTag?.delete()
}
saveFile(psiFile)
}
}
private fun saveFile(psiFile: @NotNull XmlFile) {
val document = myDocumentManager.getDocument(psiFile) ?: throw IllegalStateException(MavenProjectBundle.message(
"maven.model.error", psiFile))
myDocumentManager.doPostponedOperationsAndUnblockDocument(document)
FileDocumentManager.getInstance().saveDocument(document)
}
private fun updateVariableOrValue(model: MavenDomProjectModel,
domValue: GenericDomValue<String>,
newValue: String) {
val rawText = domValue.rawText?.trim()
if (rawText != null && rawText.startsWith("${'$'}{") && rawText.endsWith("}")) {
val propertyName = rawText.substring(2, rawText.length - 1)
val subTags = model.properties.xmlTag?.subTags ?: emptyArray()
for (subTag in subTags) {
if (subTag.name == propertyName) {
//TODO: recursive property declaration
subTag.value.text = newValue
return
}
}
}
else {
domValue.stringValue = newValue
}
}
private fun toMavenScope(scope: String?, managedScope: String?): String? {
if (managedScope == null) {
if (scope == null || scope == SCOPE_COMPILE) return null
return scope
}
if (scope == managedScope) return null
return scope
}
override fun declaredDependencies(module: @NotNull Module): List<DeclaredDependency>? {
val project = MavenProjectsManager.getInstance(module.project).findProject(module) ?: return emptyList()
return ReadAction.compute<List<DeclaredDependency>, Throwable> {
val model = MavenDomUtil.getMavenDomProjectModel(myProject, project.file) ?: throw IllegalStateException(
MavenProjectBundle.message("maven.model.error", module.name))
model.dependencies.dependencies.map {
var scope = it.scope.stringValue
if (scope == SCOPE_COMPILE) scope = null
val dataContext = object: DataContext {
override fun getData(dataId: String): Any? {
if(CommonDataKeys.PSI_ELEMENT.`is`(dataId)){
return it.xmlElement
}
return null
}
}
DeclaredDependency(it.groupId.stringValue, it.artifactId.stringValue, it.version.stringValue, scope, dataContext)
}
}
}
override fun declaredRepositories(module: Module): List<UnifiedDependencyRepository> {
val project = MavenProjectsManager.getInstance(module.project).findProject(module) ?: return emptyList()
return ReadAction.compute<List<UnifiedDependencyRepository>, Throwable> {
val model = MavenDomUtil.getMavenDomProjectModel(myProject, project.file) ?: throw IllegalStateException(
MavenProjectBundle.message("maven.model.error", module.name))
model.repositories.repositories.map {
UnifiedDependencyRepository(it.id.stringValue, it.name.stringValue, it.url.stringValue ?: "")
}
}
}
}
private fun String.trimLastSlash(): String {
return trimEnd('/')
}
private fun UnifiedCoordinates.toMavenId(): MavenId {
return MavenId(groupId, artifactId, version)
}
| apache-2.0 | 092319f0e55f566ba0de8bd729c6db12 | 39.682493 | 140 | 0.730708 | 4.931655 | false | false | false | false |
leafclick/intellij-community | platform/statistics/src/com/intellij/internal/statistic/collectors/fus/PluginInfoWhiteListRule.kt | 1 | 833 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic.collectors.fus
import com.intellij.internal.statistic.eventLog.validator.ValidationResultType
import com.intellij.internal.statistic.eventLog.validator.rules.EventContext
import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomWhiteListRule
class PluginInfoWhiteListRule : CustomWhiteListRule() {
override fun acceptRuleId(ruleId: String?) =
ruleId == "project_type" || ruleId == "framework" || ruleId == "gutter_icon" || ruleId == "editor_notification_panel_key"
override fun doValidate(data: String, context: EventContext): ValidationResultType {
return acceptWhenReportedByPluginFromPluginRepository(context)
}
}
| apache-2.0 | 2fceb2763f13fd5ee4d0e72efe4e02fe | 54.533333 | 140 | 0.798319 | 4.293814 | false | false | false | false |
bassaer/AppTesting | lib/src/main/kotlin/com/github/bassaer/lib/model/User.kt | 1 | 320 | package com.github.bassaer.lib.model
/**
* User
* Created by nakayama on 2017/11/01.
*/
data class User(var id: Int,val name: String) {
private var checksum = 0
init {
checksum = this.id * this.name.length
}
fun isPrimary() = this.id % 3 == 0
public fun getChecksum() = this.checksum;
} | apache-2.0 | b7bdd81418d666b81f09c2d4a0befabc | 19.0625 | 47 | 0.621875 | 3.333333 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/unaryOp/call.kt | 3 | 481 | fun box(): String {
val a1: Byte = 1.unaryMinus()
val a2: Short = 1.unaryMinus()
val a3: Int = 1.unaryMinus()
val a4: Long = 1.unaryMinus()
val a5: Double = 1.0.unaryMinus()
val a6: Float = 1f.unaryMinus()
if (a1 != (-1).toByte()) return "fail 1"
if (a2 != (-1).toShort()) return "fail -1"
if (a3 != -1) return "fail 3"
if (a4 != -1L) return "fail 4"
if (a5 != -1.0) return "fail 5"
if (a6 != -1f) return "fail 6"
return "OK"
} | apache-2.0 | 9141f31fba578716fa87b8905149bdd2 | 27.352941 | 46 | 0.534304 | 2.764368 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/MaxOrMinTransformation.kt | 6 | 7309 | // 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.loopToCallChain.result
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.*
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.sequence.MapTransformation
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.blockExpressionsOrSingle
class MaxOrMinTransformation(
loop: KtForExpression,
initialization: VariableInitialization,
private val isMax: Boolean
) : AssignToVariableResultTransformation(loop, initialization) {
override val presentation: String
get() = if (isMax) "maxOrNull()" else "minOrNull()"
override fun generateCode(chainedCallGenerator: ChainedCallGenerator): KtExpression {
val call = chainedCallGenerator.generate(presentation)
return KtPsiFactory(call).createExpressionByPattern(
"$0\n ?: $1", call, initialization.initializer,
reformat = chainedCallGenerator.reformat
)
}
/**
* Matches:
* val variable = <initial>
* for (...) {
* ...
* if (variable > <input variable>) { // or '<' or operands swapped
* variable = <input variable>
* }
* }
*
* or
*
* val variable = <initial>
* for (...) {
* ...
* // or '<', '<=', '>=' or operands swapped
* variable = if (variable > <input variable>) <input variable> else variable
* }
* }
* or
*
* val variable = <initial>
* for (...) {
* ...
* // or Math.min or operands swapped
* variable = Math.max(variable, <expression>)
* }
* }
*/
object Matcher : TransformationMatcher {
override val indexVariableAllowed: Boolean
get() = true
override fun match(state: MatchingState): TransformationMatch.Result? {
return matchIfAssign(state)
?: matchAssignIf(state)
?: matchMathMaxOrMin(state)
}
private fun matchIfAssign(state: MatchingState): TransformationMatch.Result? {
val ifExpression = state.statements.singleOrNull() as? KtIfExpression ?: return null
if (ifExpression.`else` != null) return null
val then = ifExpression.then ?: return null
val statement = then.blockExpressionsOrSingle().singleOrNull() as? KtBinaryExpression ?: return null
if (statement.operationToken != KtTokens.EQ) return null
return match(ifExpression.condition, statement.left, statement.right, null, state.inputVariable, state.outerLoop)
}
private fun matchAssignIf(state: MatchingState): TransformationMatch.Result? {
val assignment = state.statements.singleOrNull() as? KtBinaryExpression ?: return null
if (assignment.operationToken != KtTokens.EQ) return null
val ifExpression = assignment.right as? KtIfExpression ?: return null
return match(
ifExpression.condition,
assignment.left,
ifExpression.then,
ifExpression.`else`,
state.inputVariable,
state.outerLoop
)
}
private fun matchMathMaxOrMin(state: MatchingState): TransformationMatch.Result? {
val assignment = state.statements.singleOrNull() as? KtBinaryExpression ?: return null
if (assignment.operationToken != KtTokens.EQ) return null
val variableInitialization =
assignment.left.findVariableInitializationBeforeLoop(state.outerLoop, checkNoOtherUsagesInLoop = false)
?: return null
return matchMathMaxOrMin(variableInitialization, assignment, state, isMax = true)
?: matchMathMaxOrMin(variableInitialization, assignment, state, isMax = false)
}
private fun matchMathMaxOrMin(
variableInitialization: VariableInitialization,
assignment: KtBinaryExpression,
state: MatchingState,
isMax: Boolean
): TransformationMatch.Result? {
val functionName = if (isMax) "max" else "min"
val arguments = assignment.right.extractStaticFunctionCallArguments("java.lang.Math." + functionName) ?: return null
if (arguments.size != 2) return null
val value = when {
arguments[0].isVariableReference(variableInitialization.variable) -> arguments[1] ?: return null
arguments[1].isVariableReference(variableInitialization.variable) -> arguments[0] ?: return null
else -> return null
}
val mapTransformation = if (value.isVariableReference(state.inputVariable))
null
else
MapTransformation(state.outerLoop, state.inputVariable, state.indexVariable, value, mapNotNull = false)
val transformation = MaxOrMinTransformation(state.outerLoop, variableInitialization, isMax)
return TransformationMatch.Result(transformation, listOfNotNull(mapTransformation))
}
private fun match(
condition: KtExpression?,
assignmentTarget: KtExpression?,
valueAssignedIfTrue: KtExpression?,
valueAssignedIfFalse: KtExpression?,
inputVariable: KtCallableDeclaration,
loop: KtForExpression
): TransformationMatch.Result? {
if (condition !is KtBinaryExpression) return null
val comparison = condition.operationToken
if (comparison !in setOf(KtTokens.GT, KtTokens.LT, KtTokens.GTEQ, KtTokens.LTEQ)) return null
val left = condition.left as? KtNameReferenceExpression ?: return null
val right = condition.right as? KtNameReferenceExpression ?: return null
val otherHand = when {
left.isVariableReference(inputVariable) -> right
right.isVariableReference(inputVariable) -> left
else -> return null
}
val variableInitialization = otherHand.findVariableInitializationBeforeLoop(loop, checkNoOtherUsagesInLoop = false)
?: return null
if (!assignmentTarget.isVariableReference(variableInitialization.variable)) return null
val valueToBeVariable = when {
valueAssignedIfTrue.isVariableReference(inputVariable) -> valueAssignedIfFalse
valueAssignedIfFalse.isVariableReference(inputVariable) -> valueAssignedIfTrue
else -> return null
}
if (valueToBeVariable != null && !valueToBeVariable.isVariableReference(variableInitialization.variable)) return null
val isMax = (comparison == KtTokens.GT || comparison == KtTokens.GTEQ) xor (otherHand == left)
val transformation = MaxOrMinTransformation(loop, variableInitialization, isMax)
return TransformationMatch.Result(transformation)
}
}
} | apache-2.0 | 1111958501c4ed58335b538b771ab84d | 42.772455 | 158 | 0.631961 | 5.63966 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/createExpression/createExpressionSimple.kt | 13 | 296 | package createExpressionSimple
class MyClass: Base() {
val i = 1
}
open class Base {
val baseI = 2
}
fun main(args: Array<String>) {
val myClass: Base = MyClass()
val myBase = Base()
//Breakpoint!
val a = 1
}
// PRINT_FRAME
// DESCRIPTOR_VIEW_OPTIONS: NAME_EXPRESSION
| apache-2.0 | 7ee5c3035c273635be959838e89abc38 | 14.578947 | 43 | 0.635135 | 3.288889 | false | false | false | false |
smmribeiro/intellij-community | plugins/gradle/src/org/jetbrains/plugins/gradle/issue/GradleOutOfMemoryIssueChecker.kt | 10 | 4548 | // 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.jetbrains.plugins.gradle.issue
import com.intellij.build.BuildConsoleUtils.getMessageTitle
import com.intellij.build.FileNavigatable
import com.intellij.build.issue.BuildIssue
import com.intellij.build.issue.BuildIssueQuickFix
import com.intellij.build.issue.quickfix.OpenFileQuickFix
import com.intellij.openapi.project.Project
import com.intellij.pom.Navigatable
import com.intellij.util.PlatformUtils
import com.intellij.util.io.isFile
import org.gradle.initialization.BuildLayoutParameters
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.plugins.gradle.issue.quickfix.GradleSettingsQuickFix
import org.jetbrains.plugins.gradle.service.execution.GradleExecutionErrorHandler.getRootCauseAndLocation
import org.jetbrains.plugins.gradle.settings.GradleSystemSettings
import org.jetbrains.plugins.gradle.util.GradleBundle
import java.nio.file.Paths
import java.util.*
import java.util.function.BiPredicate
@ApiStatus.Experimental
class GradleOutOfMemoryIssueChecker : GradleIssueChecker {
override fun check(issueData: GradleIssueData): BuildIssue? {
// do not report OOM errors not related to Gradle tooling
if (issueData.error !is org.gradle.tooling.GradleConnectionException) return null
val rootCause = getRootCauseAndLocation(issueData.error).first
if (rootCause !is OutOfMemoryError) return null
val quickFixDescription = StringBuilder()
val quickFixes = ArrayList<BuildIssueQuickFix>()
val projectGradleProperties = Paths.get(issueData.projectPath, "gradle.properties")
val subItemPadding = " "
if (projectGradleProperties.isFile()) {
val openFileQuickFix = OpenFileQuickFix(projectGradleProperties, "org.gradle.jvmargs")
quickFixDescription.append("$subItemPadding<a href=\"${openFileQuickFix.id}\">gradle.properties</a> in project root directory\n")
quickFixes.add(openFileQuickFix)
}
val gradleUserHomeDir = issueData.buildEnvironment?.gradle?.gradleUserHome ?: BuildLayoutParameters().gradleUserHomeDir
val commonGradleProperties = Paths.get(gradleUserHomeDir.path, "gradle.properties")
if (commonGradleProperties.isFile()) {
val openFileQuickFix = OpenFileQuickFix(commonGradleProperties, "org.gradle.jvmargs")
quickFixDescription.append(
"$subItemPadding<a href=\"${openFileQuickFix.id}\">gradle.properties</a> in GRADLE_USER_HOME directory\n")
quickFixes.add(openFileQuickFix)
}
val gradleVmOptions = GradleSystemSettings.getInstance().gradleVmOptions
if (!gradleVmOptions.isNullOrBlank() && "AndroidStudio" != PlatformUtils.getPlatformPrefix()) { // Android Studio doesn't have Gradle VM options setting
val gradleSettingsFix = GradleSettingsQuickFix(
issueData.projectPath, true,
BiPredicate { _, _ -> gradleVmOptions != GradleSystemSettings.getInstance().gradleVmOptions },
GradleBundle.message("gradle.settings.text.vm.options")
)
quickFixes.add(gradleSettingsFix)
quickFixDescription.append("$subItemPadding<a href=\"${gradleSettingsFix.id}\">IDE Gradle VM options</a> \n")
}
val issueDescription = StringBuilder()
if (issueData.filePosition != null) {
val fileName = issueData.filePosition.file.name
val fileTypePrefix = if (fileName.endsWith("gradle", true) || fileName.endsWith("gradle.kts", true)) "Build file " else ""
issueDescription.appendLine("""
* Where:
$fileTypePrefix'${issueData.filePosition.file.path}' line: ${issueData.filePosition.startLine + 1}
""".trimIndent())
}
issueDescription.appendLine("""
* What went wrong:
Out of memory. ${rootCause.message}
""".trimIndent())
if (quickFixDescription.isNotEmpty()) {
issueDescription.append("\nPossible solution:\n")
issueDescription.append(" - Check the JVM memory arguments defined for the gradle process in:\n")
issueDescription.append(quickFixDescription)
}
val description = issueDescription.toString()
val title = getMessageTitle(rootCause.message ?: description)
return object : BuildIssue {
override val title: String = title
override val description: String = description
override val quickFixes = quickFixes
override fun getNavigatable(project: Project): Navigatable? {
return issueData.filePosition?.run { FileNavigatable(project, issueData.filePosition) }
}
}
}
}
| apache-2.0 | bb6352f0f5e12ff02266eb7a3a3d6391 | 46.873684 | 156 | 0.757256 | 4.683831 | false | false | false | false |
RuneSuite/client | updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/Font.kt | 1 | 927 | package org.runestar.client.updater.mapper.std.classes
import org.runestar.client.updater.mapper.IdentityMapper
import org.runestar.client.updater.mapper.DependsOn
import org.runestar.client.updater.mapper.predicateOf
import org.runestar.client.updater.mapper.Class2
import org.runestar.client.updater.mapper.Method2
@DependsOn(AbstractFont::class)
class Font : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.superType == type<AbstractFont>() }
@DependsOn(AbstractFont.drawGlyph::class)
class drawGlyph : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.mark == method<AbstractFont.drawGlyph>().mark }
}
@DependsOn(AbstractFont.drawGlyphAlpha::class)
class drawGlyphAlpha : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.mark == method<AbstractFont.drawGlyphAlpha>().mark }
}
} | mit | 178fd0763df4287b0acda81d8259e2d3 | 41.181818 | 111 | 0.76699 | 4.12 | false | false | false | false |
FTL-Lang/FTL-Compiler | src/main/kotlin/com/thomas/needham/ftl/frontend/lexer/Lexer.kt | 1 | 8424 | /*
The MIT License (MIT)
FTL-Compiler Copyright (c) 2016 thoma
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.thomas.needham.ftl.frontend.lexer
import com.thomas.needham.ftl.utils.Logger
import com.thomas.needham.ftl.utils.SourceFile
import com.thomas.needham.ftl.frontend.lexer.Token
import com.thomas.needham.ftl.frontend.lexer.TokenRegistry
import com.thomas.needham.ftl.utils.EvaluateStringParams
/**
* This class represents the lexer which splits up source code
* into a list of tokens
* @author Thomas Needham
* @see Token
* @see EnumTokenTypes
*/
class Lexer {
/**
* The inputted source code
*/
val sourceFile: SourceFile
/**
* Token registry to contain the lexed tokens
*/
var tokenRegistry: TokenRegistry
/**
* Primary constructor for The Lexer
* @param sourceFile The Source file to be lexed
*/
constructor(sourceFile: SourceFile) {
this.sourceFile = sourceFile
this.tokenRegistry = TokenRegistry()
}
/**
* Secondary constructor for the Lexer to be used when compiling multiple files
* @param sourceFile the Source file currently being lexed
* @param tokenRegistry A token registry containing the currently lexed tokens
*/
constructor(sourceFile: SourceFile, tokenRegistry: TokenRegistry) {
this.sourceFile = sourceFile
this.tokenRegistry = tokenRegistry
}
/**
* Function to split source code into a list of tokens
* @return Whether the source code was tokenized successfully
*/
fun tokeniseSourceCode(): Boolean {
var index: Int = 0
var currentToken: StringBuilder = StringBuilder()
while (index < sourceFile.text.size) { // while there is source code to read
if (!isControlCharacter(sourceFile.text[index])) { // is the current char a control character
if (sourceFile.text[index] == '\r' || sourceFile.text[index] == '\t') // ignore tabs and new lines
{
index++
continue
}
currentToken.append(sourceFile.text[index]) // append the current char to the current token
index++
} else if (currentToken.toString() == "//") { // Ignore Single Line Comments
while (sourceFile.text[index] != '\n') {
currentToken = StringBuilder()
index++
}
} else if (currentToken.toString() == "/*") { // Ignore Multiline Comments
while ((index < sourceFile.length.toInt() - 1) &&
!(sourceFile.text[index] == '*' && sourceFile.text[index + 1] == '/')) {
currentToken = StringBuilder()
index++
}
if ((index == sourceFile.length.toInt() - 1)) {
System.err.println("\n Unterminated Multiline Comment: ${currentToken.toString()}")
return false
}
index += 2 // Skip the */
} else {
val stackFrame = evaluateString(index, currentToken, sourceFile.text) // Check for unterminated string literals
if (stackFrame == null) { // String Was Properly Terminated
System.err.println("\n Unterminated String Literal: ${currentToken.toString()}")
return false
}
index = stackFrame.valueX!! // XXX: Hack to emulate pass by reference
currentToken = stackFrame.valueY!!
if (!currentToken.toString().isNullOrEmpty() && !currentToken.toString().isNullOrBlank()) {
// If the current token is not null or empty add it to the registry
registerTokenToRegistry(currentToken.toString())
}
registerTokenToRegistry(sourceFile.text[index].toString()) // add the whitespace to the registry
currentToken = StringBuilder() // clear the current token
index++
}
}
return true
}
/**
* Function to evaluate string literals i.e literals containing spaces and escaped characters
* @param index index of the char currently being read
* @param currentToken the value of the current token
* @param sourceChars the source code currently being lexed
* @return A StackFrame containing the index and token value after string termination,
* or null if the string could not be terminated
* @see EvaluateStringParams
*/
private fun evaluateString(index: Int, currentToken: StringBuilder, sourceChars: Array<Char>): EvaluateStringParams? {
var pIndex: Int = index // Make a copy of the passed values
val pCurrentToken: StringBuilder = currentToken
val pSourceChars: Array<Char> = sourceChars
if (!pCurrentToken.toString().isNullOrEmpty() && !pCurrentToken.toString().isNullOrBlank()) {
// if the current token is not empty
if (pCurrentToken.toString().startsWith("\"")) {
// if the current token does not end in "
while (!pCurrentToken.endsWith("\"")) {
// account for escape characters
if (pIndex > pSourceChars.size - 1)
return null
if (pSourceChars[pIndex] != '\\' || (pSourceChars[pIndex] == '\\' && pSourceChars[pIndex - 1] == '\\')) {
pCurrentToken.append(pSourceChars[pIndex]) // Keep appending chars until we find a " or we reach the end
}
pIndex++
if (pSourceChars[pIndex] == '\\') {
pIndex++
while (pSourceChars[pIndex - 1] != '\"' || pSourceChars[pIndex - 2] == '\\') {
if (pIndex > pSourceChars.size - 1)
return null
if (sourceChars[pIndex] != '\\' || sourceChars[pIndex] == '\"') {
if (pSourceChars[pIndex - 1] == '\\') {
when (sourceChars[pIndex]) {
'0' -> pCurrentToken.append('\u0000') // NULL terminator
'n' -> pCurrentToken.append('\n')
'r' -> pCurrentToken.append('\r')
't' -> pCurrentToken.append('\t')
'b' -> pCurrentToken.append('\b')
's' -> pCurrentToken.append(' ')
'f' -> pCurrentToken.append('\u000C')
'\'' -> pCurrentToken.append('\'')
'\"' -> pCurrentToken.append('\"')
'\\' -> pCurrentToken.append('\\')
else -> pCurrentToken.append(sourceChars[pIndex])
}
} else {
pCurrentToken.append(sourceChars[pIndex])
}
pIndex++
} else {
pIndex++
continue
}
}
}
}
pIndex++
}
}
return EvaluateStringParams(pIndex, pCurrentToken, pSourceChars)
}
/**
* Function to add tokens to the token registry
* @param token the token to add to the registry
*/
private fun registerTokenToRegistry(token: String): Unit {
if (!token.isNullOrEmpty() && !token.isNullOrBlank())
tokenRegistry.registerToken(token)
}
/**
* Returns Whether a character is a control character
* @param ch the char to test
* @return Whether ch is a control character
*/
private fun isControlCharacter(ch: Char): Boolean {
return !(ch != ' ' && ch != '\n' &&
ch != '\t' && ch != '(' &&
ch != ')' && ch != '[' &&
ch != ']' && ch != '{' &&
ch != '}' && ch != '\u0000' &&
ch != ',' && ch != ':' &&
ch != ';' && ch != '.')
}
/**
* Function to print all of the tokens defined in the token registry
* @return Returns a list of tokens for the purpose of unit testing
*/
fun printTokens(): List<String> { // Only Returns a list of tokens for the purpose of unit testing
val list: MutableList<String> = mutableListOf()
for (token: Token in tokenRegistry.registeredTokens) {
list.add(token.toString())
Logger.printMessage(token.toString())
}
return list
}
private fun getLineFromOffset(offset: Int): Int {
return sourceFile.text.copyOfRange(0, offset).count { x -> x == '\n' } + 1
}
private fun getColumnFromOffset(offset: Int): Int {
return sourceFile.text.toString().indexOf('\n', offset)
}
} | mit | 17d55670bfb6a6ec5a03dd2606b3c4bf | 35.630435 | 119 | 0.665123 | 4.026769 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/viewHolders/tasks/ChecklistedViewHolder.kt | 1 | 7581 | package com.habitrpg.android.habitica.ui.viewHolders.tasks
import android.content.Context
import android.graphics.Rect
import android.view.LayoutInflater
import android.view.TouchDelegate
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.CompoundButton
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.models.responses.TaskDirection
import com.habitrpg.android.habitica.models.tasks.ChecklistItem
import com.habitrpg.android.habitica.models.tasks.Task
import com.habitrpg.android.habitica.ui.helpers.MarkdownParser
import com.habitrpg.android.habitica.ui.helpers.bindView
import com.habitrpg.android.habitica.ui.views.HabiticaEmojiTextView
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
abstract class ChecklistedViewHolder(itemView: View, scoreTaskFunc: ((Task, TaskDirection) -> Unit), var scoreChecklistItemFunc: ((Task, ChecklistItem) -> Unit), openTaskFunc: ((Task) -> Unit)) : BaseTaskViewHolder(itemView, scoreTaskFunc, openTaskFunc), CompoundButton.OnCheckedChangeListener {
private val checkboxHolder: ViewGroup by bindView(itemView, R.id.checkBoxHolder)
internal val checkbox: CheckBox by bindView(itemView, R.id.checkBox)
internal val checklistView: LinearLayout by bindView(itemView, R.id.checklistView)
internal val checklistBottomSpace: View by bindView(itemView, R.id.checklistBottomSpace)
internal val checklistIndicatorWrapper: ViewGroup by bindView(itemView, R.id.checklistIndicatorWrapper)
private val checklistCompletedTextView: TextView by bindView(itemView, R.id.checkListCompletedTextView)
private val checklistAllTextView: TextView by bindView(itemView, R.id.checkListAllTextView)
init {
checklistIndicatorWrapper.isClickable = true
checklistIndicatorWrapper.setOnClickListener { onChecklistIndicatorClicked() }
checkbox.setOnCheckedChangeListener(this)
expandCheckboxTouchArea(checkboxHolder, checkbox)
}
override fun bind(newTask: Task, position: Int) {
var completed = newTask.completed
if (newTask.isPendingApproval) {
completed = false
}
this.checkbox.isChecked = completed
if (this.shouldDisplayAsActive(newTask) && !newTask.isPendingApproval) {
this.checkboxHolder.setBackgroundResource(newTask.lightTaskColor)
} else {
this.checkboxHolder.setBackgroundColor(this.taskGray)
}
this.checklistCompletedTextView.text = newTask.completedChecklistCount.toString()
this.checklistAllTextView.text = newTask.checklist?.size.toString()
this.checklistView.removeAllViews()
this.updateChecklistDisplay()
this.checklistIndicatorWrapper.visibility = if (newTask.checklist?.size == 0) View.GONE else View.VISIBLE
this.rightBorderView?.visibility = if (newTask.checklist?.size == 0) View.VISIBLE else View.GONE
if (newTask.completed) {
this.rightBorderView?.setBackgroundResource(newTask.lightTaskColor)
} else {
this.rightBorderView?.setBackgroundColor(this.taskGray)
}
super.bind(newTask, position)
}
abstract fun shouldDisplayAsActive(newTask: Task): Boolean
private fun updateChecklistDisplay() {
//This needs to be a LinearLayout, as ListViews can not be inside other ListViews.
if (this.shouldDisplayExpandedChecklist()) {
val layoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as? LayoutInflater
if (this.task?.checklist?.isValid == true) {
checklistView.removeAllViews()
for (item in this.task?.checklist ?: emptyList<ChecklistItem>()) {
val itemView = layoutInflater?.inflate(R.layout.checklist_item_row, this.checklistView, false) as? LinearLayout
val checkbox = itemView?.findViewById<CheckBox>(R.id.checkBox)
val textView = itemView?.findViewById<HabiticaEmojiTextView>(R.id.checkedTextView)
// Populate the data into the template view using the data object
textView?.text = item.text
if (item.text != null) {
Observable.just(item.text)
.map { MarkdownParser.parseMarkdown(it) }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(Consumer<CharSequence> { textView?.text = it }, RxErrorHandler.handleEmptyError())
}
checkbox?.isChecked = item.completed
checkbox?.setOnCheckedChangeListener { _, _ ->
task?.let { scoreChecklistItemFunc(it, item) }
}
val checkboxHolder = itemView?.findViewById<View>(R.id.checkBoxHolder) as? ViewGroup
expandCheckboxTouchArea(checkboxHolder, checkbox)
this.checklistView.addView(itemView)
}
}
this.checklistView.visibility = View.VISIBLE
this.checklistBottomSpace.visibility = View.VISIBLE
} else {
this.checklistView.removeAllViewsInLayout()
this.checklistView.visibility = View.GONE
this.checklistBottomSpace.visibility = View.GONE
}
}
private fun onChecklistIndicatorClicked() {
expandedChecklistRow = if (this.shouldDisplayExpandedChecklist()) null else adapterPosition
if (this.shouldDisplayExpandedChecklist()) {
val recyclerView = this.checklistView.parent.parent as? RecyclerView
val layoutManager = recyclerView?.layoutManager as? LinearLayoutManager
layoutManager?.scrollToPositionWithOffset(this.adapterPosition, 15)
}
updateChecklistDisplay()
}
private fun shouldDisplayExpandedChecklist(): Boolean {
return expandedChecklistRow != null && adapterPosition == expandedChecklistRow
}
private fun expandCheckboxTouchArea(expandedView: View?, checkboxView: View?) {
expandedView?.post {
val rect = Rect()
expandedView.getHitRect(rect)
expandedView.touchDelegate = TouchDelegate(rect, checkboxView)
}
}
override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) {
if (buttonView == checkbox) {
if (task?.isValid != true) {
return
}
if (isChecked != task?.completed) {
task?.let { scoreTaskFunc(it, if (task?.completed == false) TaskDirection.UP else TaskDirection.DOWN) }
}
}
}
override fun setDisabled(openTaskDisabled: Boolean, taskActionsDisabled: Boolean) {
super.setDisabled(openTaskDisabled, taskActionsDisabled)
this.checkbox.isEnabled = !taskActionsDisabled
}
companion object {
private var expandedChecklistRow: Int? = null
}
}
| gpl-3.0 | 14ce7be3d5cd96f490c579d60cb49b45 | 46.909677 | 295 | 0.675505 | 5.115385 | false | false | false | false |
FuturemanGaming/FutureBot-Discord | src/main/kotlin/com/futuremangaming/futurebot/logging.kt | 1 | 2017 | /*
* Copyright 2014-2017 FuturemanGaming
*
* 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.futuremangaming.futurebot
import net.dv8tion.jda.core.utils.SimpleLog
import net.dv8tion.jda.core.utils.SimpleLog.Level
import net.dv8tion.jda.core.utils.SimpleLog.Level.DEBUG
import net.dv8tion.jda.core.utils.SimpleLog.Level.FATAL
import net.dv8tion.jda.core.utils.SimpleLog.Level.INFO
import net.dv8tion.jda.core.utils.SimpleLog.Level.TRACE
import net.dv8tion.jda.core.utils.SimpleLog.Level.WARNING
import org.slf4j.LoggerFactory
fun getLogger(name: String) = LoggerFactory.getLogger(name)!!
fun getLogger(clazz: Class<*>) = LoggerFactory.getLogger(clazz)!!
class SimpleLogger : SimpleLog.LogListener {
override fun onError(log: SimpleLog, err: Throwable) {
val name = log.name
val logger = getLogger(if (name.contains("JDA")) name else "JDA_$name")
logger.error("Failure ", err)
}
override fun onLog(log: SimpleLog, logLevel: Level, message: Any?) {
val name = log.name
val logger = getLogger(if (name.contains("JDA")) name else "JDA_$name")
if (message is Throwable) return onError(log, message)
logger.apply { when (logLevel) {
INFO -> info(message.toString())
WARNING -> warn(message.toString())
TRACE -> trace(message.toString())
FATAL -> error(message.toString())
DEBUG -> debug(message.toString())
else -> { }
} }
}
}
| apache-2.0 | 88eeaafd01e357e5c4381eb78511c1a0 | 37.788462 | 79 | 0.691125 | 3.770093 | false | false | false | false |
leafclick/intellij-community | platform/configuration-store-impl/testSrc/ModuleStoreRenameTest.kt | 1 | 7721 | // 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.configurationStore
import com.intellij.ProjectTopics
import com.intellij.ide.highlighter.ModuleFileType
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.impl.coroutineDispatchingContext
import com.intellij.openapi.application.impl.inWriteAction
import com.intellij.openapi.command.impl.UndoManagerImpl
import com.intellij.openapi.command.undo.UndoManager
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.ModuleListener
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.modifyModules
import com.intellij.openapi.project.rootManager
import com.intellij.openapi.roots.ModuleRootManagerEx
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.testFramework.*
import com.intellij.testFramework.assertions.Assertions.assertThat
import com.intellij.util.Function
import com.intellij.util.SmartList
import com.intellij.util.io.readText
import com.intellij.util.io.systemIndependentPath
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.junit.After
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExternalResource
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
import kotlin.properties.Delegates
private val Module.storage: FileBasedStorage
get() = (stateStore.storageManager as StateStorageManagerImpl).getCachedFileStorages(listOf(StoragePathMacros.MODULE_FILE)).first()
internal class ModuleStoreRenameTest {
companion object {
@JvmField
@ClassRule
val projectRule = ProjectRule()
}
var module: Module by Delegates.notNull()
var dependentModule: Module by Delegates.notNull()
// we test fireModuleRenamedByVfsEvent
private val oldModuleNames = SmartList<String>()
private val tempDirManager = TemporaryDirectory()
@Rule
@JvmField
val ruleChain = RuleChain(
tempDirManager,
object : ExternalResource() {
override fun before() {
runInEdtAndWait {
val moduleFileParent = tempDirManager.newPath(refreshVfs = true)
module = projectRule.createModule(moduleFileParent.resolve("m.iml"))
dependentModule = projectRule.createModule(moduleFileParent.resolve("dependent-module.iml"))
ModuleRootModificationUtil.addDependency(dependentModule, module)
}
module.messageBus.connect().subscribe(ProjectTopics.MODULES, object : ModuleListener {
override fun modulesRenamed(project: Project, modules: MutableList<Module>, oldNameProvider: Function<Module, String>) {
assertThat(modules).containsOnly(module)
oldModuleNames.add(oldNameProvider.`fun`(module))
}
})
}
// should be invoked after project tearDown
override fun after() {
(ApplicationManager.getApplication().stateStore.storageManager as StateStorageManagerImpl).getVirtualFileTracker()!!.remove {
if (it.storageManager.componentManager == module) {
throw AssertionError("Storage manager is not disposed, module $module, storage $it")
}
false
}
}
},
DisposeModulesRule(projectRule)
)
@After
fun tearDown() {
ApplicationManager.getApplication().invokeAndWait {
(UndoManager.getInstance(projectRule.project) as UndoManagerImpl).dropHistoryInTests()
(UndoManager.getInstance(projectRule.project) as UndoManagerImpl).flushCurrentCommandMerger()
}
}
// project structure
@Test
fun `rename module using model`() = runBlocking<Unit> {
saveProjectState()
val storage = module.storage
val oldFile = storage.file
assertThat(oldFile).isRegularFile
val oldName = module.name
val newName = "foo"
withContext(AppUIExecutor.onUiThread().coroutineDispatchingContext()) {
projectRule.project.modifyModules { renameModule(module, newName) }
}
assertRename(newName, oldFile)
assertThat(oldModuleNames).containsOnly(oldName)
}
// project view
@Test
fun `rename module using rename virtual file`() = runBlocking {
testRenameModule()
}
private suspend fun testRenameModule() {
saveProjectState()
val storage = module.storage
val oldFile = storage.file
assertThat(oldFile).isRegularFile
val oldName = module.name
val newName = "foo.dot"
withContext(AppUIExecutor.onUiThread().inWriteAction().coroutineDispatchingContext()) {
LocalFileSystem.getInstance().refreshAndFindFileByPath(oldFile.systemIndependentPath)!!.rename(null, "$newName${ModuleFileType.DOT_DEFAULT_EXTENSION}")
}
assertRename(newName, oldFile)
assertThat(oldModuleNames).containsOnly(oldName)
}
// we cannot test external rename yet, because it is not supported - ModuleImpl doesn't support delete and create events (in case of external change we don't get move event, but get "delete old" and "create new")
private suspend fun assertRename(newName: String, oldFile: Path) {
val newFile = module.storage.file
assertThat(newFile.fileName.toString()).isEqualTo("$newName${ModuleFileType.DOT_DEFAULT_EXTENSION}")
assertThat(oldFile)
.doesNotExist()
.isNotEqualTo(newFile)
assertThat(newFile).isRegularFile
// ensure that macro value updated
assertThat(module.stateStore.storageManager.expandMacros(StoragePathMacros.MODULE_FILE)).isEqualTo(newFile.systemIndependentPath)
saveProjectState()
assertThat(dependentModule.storage.file.readText()).contains("""<orderEntry type="module" module-name="$newName" />""")
}
@Test
fun `rename module parent virtual dir`() = runBlocking {
saveProjectState()
val storage = module.storage
val oldFile = storage.file
val parentVirtualDir = storage.virtualFile!!.parent
withContext(AppUIExecutor.onUiThread().inWriteAction().coroutineDispatchingContext()) {
parentVirtualDir.rename(null, UUID.randomUUID().toString())
}
val newFile = Paths.get(parentVirtualDir.path, "${module.name}${ModuleFileType.DOT_DEFAULT_EXTENSION}")
try {
assertThat(newFile).isRegularFile
assertRename(module.name, oldFile)
assertThat(oldModuleNames).isEmpty()
testRenameModule()
}
finally {
withContext(AppUIExecutor.onUiThread().inWriteAction().coroutineDispatchingContext()) {
parentVirtualDir.delete(this)
}
}
}
@Test
fun `rename module source root`() = runBlocking<Unit>(AppUIExecutor.onUiThread().coroutineDispatchingContext()) {
saveProjectState()
val storage = module.storage
val parentVirtualDir = storage.virtualFile!!.parent
val src = VfsTestUtil.createDir(parentVirtualDir, "foo")
withContext(AppUIExecutor.onUiThread().inWriteAction().coroutineDispatchingContext()) {
PsiTestUtil.addSourceContentToRoots(module, src, false)
}
saveProjectState()
val rootManager = module.rootManager as ModuleRootManagerEx
val stateModificationCount = rootManager.modificationCountForTests
withContext(AppUIExecutor.onUiThread().inWriteAction().coroutineDispatchingContext()) {
src.rename(null, "bar.dot")
}
assertThat(stateModificationCount).isLessThan(rootManager.modificationCountForTests)
}
private suspend fun saveProjectState() {
projectRule.project.stateStore.save()
}
} | apache-2.0 | a8211f16161459ca663b54da9be797c7 | 36.304348 | 214 | 0.753918 | 5.082949 | false | true | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddPropertyToSupertypeFix.kt | 1 | 8664 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.ListPopupStep
import com.intellij.openapi.ui.popup.PopupStep
import com.intellij.openapi.ui.popup.util.BaseListPopupStep
import com.intellij.util.PlatformIcons
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.Modality.ABSTRACT
import org.jetbrains.kotlin.descriptors.Modality.SEALED
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.implicitModality
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.modalityModifier
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
import org.jetbrains.kotlin.types.typeUtil.supertypes
class AddPropertyToSupertypeFix private constructor(
element: KtProperty,
private val properties: List<PropertyData>
) : KotlinQuickFixAction<KtProperty>(element), LowPriorityAction {
private class PropertyData(val signaturePreview: String, val sourceCode: String, val targetClass: KtClass)
override fun getText(): String {
val single = properties.singleOrNull()
return if (single != null) actionName(single) else KotlinBundle.message("fix.add.property.to.supertype.text.generic")
}
override fun getFamilyName() = KotlinBundle.message("fix.add.property.to.supertype.family")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
CommandProcessor.getInstance().runUndoTransparentAction {
if (properties.size == 1 || editor == null || !editor.component.isShowing) {
addProperty(properties.first(), project)
} else {
JBPopupFactory.getInstance().createListPopup(createPropertyPopup(project)).showInBestPositionFor(editor)
}
}
}
private fun addProperty(propertyData: PropertyData, project: Project) {
project.executeWriteCommand(KotlinBundle.message("fix.add.property.to.supertype.progress")) {
val classBody = propertyData.targetClass.getOrCreateBody()
val propertyElement = KtPsiFactory(project).createProperty(propertyData.sourceCode)
val insertedPropertyElement = classBody.addBefore(propertyElement, classBody.rBrace) as KtProperty
ShortenReferences.DEFAULT.process(insertedPropertyElement)
val modifierToken = insertedPropertyElement.modalityModifier()?.node?.elementType as? KtModifierKeywordToken
?: return@executeWriteCommand
if (insertedPropertyElement.implicitModality() == modifierToken) {
RemoveModifierFix(insertedPropertyElement, modifierToken, true).invoke()
}
}
}
private fun createPropertyPopup(project: Project): ListPopupStep<*> {
return object : BaseListPopupStep<PropertyData>(KotlinBundle.message("fix.add.property.to.supertype.choose.type"), properties) {
override fun isAutoSelectionEnabled() = false
override fun onChosen(selectedValue: PropertyData, finalChoice: Boolean): PopupStep<*>? {
if (finalChoice) {
addProperty(selectedValue, project)
}
return PopupStep.FINAL_CHOICE
}
override fun getIconFor(value: PropertyData) = PlatformIcons.PROPERTY_ICON
override fun getTextFor(value: PropertyData) = actionName(value)
}
}
private fun actionName(propertyData: PropertyData): String {
return KotlinBundle.message("fix.add.property.to.supertype.text", propertyData.signaturePreview, propertyData.targetClass.name.toString())
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val property = diagnostic.psiElement as? KtProperty ?: return null
val descriptors = generatePropertiesToAdd(property)
if (descriptors.isEmpty()) return null
val project = diagnostic.psiFile.project
val propertyData = descriptors.mapNotNull { createPropertyData(it, property.initializer, project) }
if (propertyData.isEmpty()) return null
return AddPropertyToSupertypeFix(property, propertyData)
}
private fun createPropertyData(
propertyDescriptor: PropertyDescriptor,
initializer: KtExpression?,
project: Project
): PropertyData? {
val classDescriptor = propertyDescriptor.containingDeclaration as ClassDescriptor
var signaturePreview = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.render(propertyDescriptor)
if (classDescriptor.kind == ClassKind.INTERFACE) {
signaturePreview = signaturePreview.substring("abstract ".length)
}
var sourceCode = IdeDescriptorRenderers.SOURCE_CODE.render(propertyDescriptor)
if (classDescriptor.kind == ClassKind.CLASS && classDescriptor.modality == Modality.OPEN && initializer != null) {
sourceCode += " = ${initializer.text}"
}
val targetClass = DescriptorToSourceUtilsIde.getAnyDeclaration(project, classDescriptor) as? KtClass ?: return null
return PropertyData(signaturePreview, sourceCode, targetClass)
}
private fun generatePropertiesToAdd(propertyElement: KtProperty): List<PropertyDescriptor> {
val propertyDescriptor =
propertyElement.resolveToDescriptorIfAny(BodyResolveMode.FULL) as? PropertyDescriptor ?: return emptyList()
val classDescriptor = propertyDescriptor.containingDeclaration as? ClassDescriptor ?: return emptyList()
return getSuperClasses(classDescriptor)
.asSequence()
.filterNot { KotlinBuiltIns.isAnyOrNullableAny(it.defaultType) }
.map { generatePropertySignatureForType(propertyDescriptor, it) }
.toList()
}
private fun getSuperClasses(classDescriptor: ClassDescriptor): List<ClassDescriptor> {
val supertypes = classDescriptor.defaultType.supertypes().toMutableList().sortSubtypesFirst()
return supertypes.mapNotNull { it.constructor.declarationDescriptor as? ClassDescriptor }
}
private fun MutableList<KotlinType>.sortSubtypesFirst(): List<KotlinType> {
// TODO: rewrite this
val typeChecker = KotlinTypeChecker.DEFAULT
for (i in 1 until size) {
val currentType = this[i]
for (j in 0 until i) {
if (typeChecker.isSubtypeOf(currentType, this[j])) {
this.removeAt(i)
this.add(j, currentType)
break
}
}
}
return this
}
private fun generatePropertySignatureForType(
propertyDescriptor: PropertyDescriptor,
typeDescriptor: ClassDescriptor
): PropertyDescriptor {
val containerModality = typeDescriptor.modality
val modality = if (containerModality == SEALED || containerModality == ABSTRACT) ABSTRACT else propertyDescriptor.modality
return propertyDescriptor.newCopyBuilder()
.setOwner(typeDescriptor)
.setModality(modality)
.setVisibility(propertyDescriptor.visibility)
.setKind(CallableMemberDescriptor.Kind.DECLARATION)
.setCopyOverrides(false)
.build()!!
}
}
} | apache-2.0 | be3985e12d49c40e52501aaa0c38400f | 47.954802 | 158 | 0.699908 | 5.52551 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantLetInspection.kt | 1 | 11898 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.core.util.isMultiLine
import org.jetbrains.kotlin.idea.intentions.*
import org.jetbrains.kotlin.idea.util.textRangeIn
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getReferenceTargets
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.isNullable
abstract class RedundantLetInspection : AbstractApplicabilityBasedInspection<KtCallExpression>(
KtCallExpression::class.java
) {
override fun inspectionText(element: KtCallExpression) = KotlinBundle.message("redundant.let.call.could.be.removed")
final override fun inspectionHighlightRangeInElement(element: KtCallExpression) = element.calleeExpression?.textRangeIn(element)
final override val defaultFixText get() = KotlinBundle.message("remove.let.call")
final override fun isApplicable(element: KtCallExpression): Boolean {
if (!element.isLetMethodCall()) return false
val lambdaExpression = element.lambdaArguments.firstOrNull()?.getLambdaExpression() ?: return false
val parameterName = lambdaExpression.getParameterName() ?: return false
return isApplicable(
element,
lambdaExpression.bodyExpression?.children?.singleOrNull() ?: return false,
lambdaExpression,
parameterName
)
}
protected abstract fun isApplicable(
element: KtCallExpression,
bodyExpression: PsiElement,
lambdaExpression: KtLambdaExpression,
parameterName: String
): Boolean
final override fun applyTo(element: KtCallExpression, project: Project, editor: Editor?) {
val lambdaExpression = element.lambdaArguments.firstOrNull()?.getLambdaExpression() ?: return
when (val bodyExpression = lambdaExpression.bodyExpression?.children?.singleOrNull() ?: return) {
is KtDotQualifiedExpression -> bodyExpression.applyTo(element)
is KtBinaryExpression -> bodyExpression.applyTo(element)
is KtCallExpression -> bodyExpression.applyTo(element, lambdaExpression.functionLiteral, editor)
is KtSimpleNameExpression -> deleteCall(element)
}
}
}
class SimpleRedundantLetInspection : RedundantLetInspection() {
override fun isApplicable(
element: KtCallExpression,
bodyExpression: PsiElement,
lambdaExpression: KtLambdaExpression,
parameterName: String
): Boolean = when (bodyExpression) {
is KtDotQualifiedExpression -> bodyExpression.isApplicable(parameterName)
is KtSimpleNameExpression -> bodyExpression.text == parameterName
else -> false
}
}
class ComplexRedundantLetInspection : RedundantLetInspection() {
override fun isApplicable(
element: KtCallExpression,
bodyExpression: PsiElement,
lambdaExpression: KtLambdaExpression,
parameterName: String
): Boolean = when (bodyExpression) {
is KtBinaryExpression ->
element.parent !is KtSafeQualifiedExpression && bodyExpression.isApplicable(parameterName)
is KtCallExpression ->
if (element.parent is KtSafeQualifiedExpression) {
false
} else {
val references = lambdaExpression.functionLiteral.valueParameterReferences(bodyExpression)
val destructuringDeclaration = lambdaExpression.functionLiteral.valueParameters.firstOrNull()?.destructuringDeclaration
references.isEmpty() || (references.singleOrNull()?.takeIf { expression ->
expression.parents.takeWhile { it != lambdaExpression.functionLiteral }.find { it is KtFunction } == null
} != null && destructuringDeclaration == null)
}
else ->
false
}
override fun inspectionHighlightType(element: KtCallExpression): ProblemHighlightType = if (isSingleLine(element))
ProblemHighlightType.GENERIC_ERROR_OR_WARNING
else
ProblemHighlightType.INFORMATION
}
private fun KtBinaryExpression.applyTo(element: KtCallExpression) {
val left = left ?: return
val factory = KtPsiFactory(element.project)
when (val parent = element.parent) {
is KtQualifiedExpression -> {
val receiver = parent.receiverExpression
val newLeft = when (left) {
is KtDotQualifiedExpression -> left.replaceFirstReceiver(factory, receiver, parent is KtSafeQualifiedExpression)
else -> receiver
}
val newExpression = factory.createExpressionByPattern("$0 $1 $2", newLeft, operationReference, right!!)
parent.replace(newExpression)
}
else -> {
val newLeft = when (left) {
is KtDotQualifiedExpression -> left.deleteFirstReceiver()
else -> factory.createThisExpression()
}
val newExpression = factory.createExpressionByPattern("$0 $1 $2", newLeft, operationReference, right!!)
element.replace(newExpression)
}
}
}
private fun KtDotQualifiedExpression.applyTo(element: KtCallExpression) {
when (val parent = element.parent) {
is KtQualifiedExpression -> {
val factory = KtPsiFactory(element.project)
val receiver = parent.receiverExpression
parent.replace(replaceFirstReceiver(factory, receiver, parent is KtSafeQualifiedExpression))
}
else -> {
element.replace(deleteFirstReceiver())
}
}
}
private fun deleteCall(element: KtCallExpression) {
val parent = element.parent as? KtQualifiedExpression
if (parent != null) {
val replacement = parent.selectorExpression?.takeIf { it != element } ?: parent.receiverExpression
parent.replace(replacement)
} else {
element.delete()
}
}
private fun KtCallExpression.applyTo(element: KtCallExpression, functionLiteral: KtFunctionLiteral, editor: Editor?) {
val parent = element.parent as? KtQualifiedExpression
val reference = functionLiteral.valueParameterReferences(this).firstOrNull()
val replaced = if (parent != null) {
reference?.replace(parent.receiverExpression)
parent.replaced(this)
} else {
reference?.replace(KtPsiFactory(this).createThisExpression())
element.replaced(this)
}
editor?.caretModel?.moveToOffset(replaced.startOffset)
}
private fun KtBinaryExpression.isApplicable(parameterName: String, isTopLevel: Boolean = true): Boolean {
val left = left ?: return false
if (isTopLevel) {
when (left) {
is KtNameReferenceExpression -> if (left.text != parameterName) return false
is KtDotQualifiedExpression -> if (!left.isApplicable(parameterName)) return false
else -> return false
}
} else {
if (!left.isApplicable(parameterName)) return false
}
val right = right ?: return false
return right.isApplicable(parameterName)
}
private fun KtExpression.isApplicable(parameterName: String): Boolean = when (this) {
is KtNameReferenceExpression -> text != parameterName
is KtDotQualifiedExpression -> !hasLambdaExpression() && !nameUsed(parameterName)
is KtBinaryExpression -> isApplicable(parameterName, isTopLevel = false)
is KtCallExpression -> isApplicable(parameterName)
is KtConstantExpression -> true
else -> false
}
private fun KtCallExpression.isApplicable(parameterName: String): Boolean = valueArguments.all {
val argumentExpression = it.getArgumentExpression() ?: return@all false
argumentExpression.isApplicable(parameterName)
}
private fun KtDotQualifiedExpression.isApplicable(parameterName: String): Boolean {
val context by lazy { analyze(BodyResolveMode.PARTIAL) }
return !hasLambdaExpression() && getLeftMostReceiverExpression().let { receiver ->
receiver is KtNameReferenceExpression &&
receiver.getReferencedName() == parameterName &&
!nameUsed(parameterName, except = receiver)
} && callExpression?.getResolvedCall(context) !is VariableAsFunctionResolvedCall && !hasNullableReceiverExtensionCall(context)
}
private fun KtDotQualifiedExpression.hasNullableReceiverExtensionCall(context: BindingContext): Boolean {
val descriptor = selectorExpression?.getResolvedCall(context)?.resultingDescriptor as? CallableMemberDescriptor ?: return false
if (descriptor.extensionReceiverParameter?.type?.isNullable() == true) return true
return (KtPsiUtil.deparenthesize(receiverExpression) as? KtDotQualifiedExpression)?.hasNullableReceiverExtensionCall(context) == true
}
private fun KtDotQualifiedExpression.hasLambdaExpression() = selectorExpression?.anyDescendantOfType<KtLambdaExpression>() ?: false
private fun KtCallExpression.isLetMethodCall() = calleeExpression?.text == "let" && isMethodCall("kotlin.let")
private fun KtLambdaExpression.getParameterName(): String? {
val parameters = valueParameters
if (parameters.size > 1) return null
return if (parameters.size == 1) parameters[0].text else "it"
}
private fun KtExpression.nameUsed(name: String, except: KtNameReferenceExpression? = null): Boolean =
anyDescendantOfType<KtNameReferenceExpression> { it != except && it.getReferencedName() == name }
private fun KtFunctionLiteral.valueParameterReferences(callExpression: KtCallExpression): List<KtNameReferenceExpression> {
val context = analyze(BodyResolveMode.PARTIAL)
val parameterDescriptor = context[BindingContext.FUNCTION, this]?.valueParameters?.singleOrNull() ?: return emptyList()
val variableDescriptorByName = if (parameterDescriptor is ValueParameterDescriptorImpl.WithDestructuringDeclaration)
parameterDescriptor.destructuringVariables.associateBy { it.name }
else
mapOf(parameterDescriptor.name to parameterDescriptor)
val callee = (callExpression.calleeExpression as? KtNameReferenceExpression)?.let {
val descriptor = variableDescriptorByName[it.getReferencedNameAsName()]
if (descriptor != null && it.getReferenceTargets(context).singleOrNull() == descriptor) listOf(it) else null
} ?: emptyList()
return callee + callExpression.valueArguments.flatMap { arg ->
arg.collectDescendantsOfType<KtNameReferenceExpression>().filter {
val descriptor = variableDescriptorByName[it.getReferencedNameAsName()]
descriptor != null && it.getResolvedCall(context)?.resultingDescriptor == descriptor
}
}
}
private fun isSingleLine(element: KtCallExpression): Boolean {
val qualifiedExpression = element.getQualifiedExpressionForSelector() ?: return true
var receiver = qualifiedExpression.receiverExpression
if (receiver.isMultiLine()) return false
var count = 1
while (true) {
if (count > 2) return false
receiver = (receiver as? KtQualifiedExpression)?.receiverExpression ?: break
count++
}
return true
}
| apache-2.0 | 0928b0bdccc890bf8886391159807cac | 45.29572 | 158 | 0.726004 | 5.668414 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/IntroduceVariableIntention.kt | 3 | 2657 | // 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.codeInsight.intention.HighPriorityAction
import com.intellij.java.JavaBundle
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFileSystemItem
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.refactoring.introduce.introduceVariable.KotlinIntroduceVariableHandler
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtDeclarationWithBody
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtStatementExpression
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.types.typeUtil.isNothing
import org.jetbrains.kotlin.types.typeUtil.isUnit
class IntroduceVariableIntention : SelfTargetingRangeIntention<PsiElement>(
PsiElement::class.java, { JavaBundle.message("intention.introduce.variable.text") }
), HighPriorityAction {
private fun getExpressionToProcess(element: PsiElement): KtExpression? {
if (element is PsiFileSystemItem) return null
val startElement = PsiTreeUtil.skipSiblingsBackward(element, PsiWhiteSpace::class.java) ?: element
return startElement.parentsWithSelf
.filterIsInstance<KtExpression>()
.takeWhile { it !is KtDeclarationWithBody && it !is KtStatementExpression }
.firstOrNull {
val parent = it.parent
parent is KtBlockExpression || parent is KtDeclarationWithBody && !parent.hasBlockBody() && parent.bodyExpression == it
}
}
override fun applicabilityRange(element: PsiElement): TextRange? {
val expression = getExpressionToProcess(element) ?: return null
val type = expression.safeAnalyzeNonSourceRootCode().getType(expression)
if (type == null || type.isUnit() || type.isNothing()) return null
return element.textRange
}
override fun applyTo(element: PsiElement, editor: Editor?) {
val expression = getExpressionToProcess(element) ?: return
KotlinIntroduceVariableHandler.doRefactoring(
element.project, editor, expression, isVar = false, occurrencesToReplace = null, onNonInteractiveFinish = null
)
}
override fun startInWriteAction(): Boolean {
return false
}
} | apache-2.0 | b18134a4013d61a1d8f1267965a0e523 | 47.327273 | 158 | 0.760632 | 5.139265 | false | false | false | false |
K0zka/kerub | src/main/kotlin/com/github/kerubistan/kerub/services/impl/AbstractAssetService.kt | 2 | 3423 | package com.github.kerubistan.kerub.services.impl
import com.github.kerubistan.kerub.data.AssetDao
import com.github.kerubistan.kerub.model.Asset
import com.github.kerubistan.kerub.model.AssetOwner
import com.github.kerubistan.kerub.model.AssetOwnerType
import com.github.kerubistan.kerub.model.paging.SearchResultPage
import com.github.kerubistan.kerub.model.paging.SortResultPage
import com.github.kerubistan.kerub.security.AssetAccessController
import com.github.kerubistan.kerub.services.AssetService
import java.util.UUID
abstract class AbstractAssetService<T : Asset>(
val accessController: AssetAccessController,
override val dao: AssetDao<T>,
entityType: String
) : ListableBaseService<T>(entityType), AssetService<T> {
override fun listByOwner(
start: Long, limit: Int, sort: String, ownerType: AssetOwnerType, ownerId: UUID
): SortResultPage<T> {
val list = dao.listByOwner(
owner = AssetOwner(ownerId, ownerType),
start = start,
limit = limit,
sort = sort
)
return SortResultPage(
start = start,
count = list.size.toLong(),
result = list,
sortBy = sort,
total = list.size.toLong() //TODO
)
}
override fun search(
field: String, value: String, start: Long, limit: Int, ownerType: AssetOwnerType, ownerId: UUID
): SearchResultPage<T> {
val list = dao.fieldSearch(
setOf(AssetOwner(ownerId, ownerType)),
field,
value
)
return SearchResultPage(
start = start,
count = list.size.toLong(),
result = list,
total = list.size.toLong(), //TODO
searchby = field
)
}
override fun getById(id: UUID): T =
assertExist(entityType, accessController.doAndCheck {
super.getById(id)
}, id)
override fun update(id: UUID, entity: T): T =
assertExist(entityType, accessController.checkAndDo(entity) {
super.update(id, entity)
}, id)
final override fun delete(id: UUID) {
val entity: T = assertExist(entityType, accessController.doAndCheck { dao[id] }, id)
beforeRemove(entity)
doRemove(entity)
afterRemove(entity)
}
open fun doRemove(entity: T) {
dao.remove(entity)
}
open fun afterRemove(entity: T) {
// usually nothing to do after remove, but some virtual resources may need post-action
}
open fun beforeRemove(entity: T) {
//it would be nice to have a generic validation here, like incoming references
}
override fun add(entity: T): T =
accessController.checkAndDo(asset = entity) {
super.add(entity)
} ?: entity
override fun listAll(start: Long, limit: Int, sort: String): SortResultPage<T> =
accessController.listWithFilter(dao, start, limit, sort)
override fun getByName(name: String): List<T> = accessController.filter(dao.getByName(name) as List<T>)
override fun search(field: String, value: String, start: Long, limit: Int): SearchResultPage<T> =
accessController.searchWithFilter(dao, field, value, start, limit)
override fun getByNameAndOwner(ownerType: AssetOwnerType, ownerId: UUID, name: String): List<T> =
TODO("https://github.com/kerubistan/kerub/issues/173")
override fun autoName(): String {
//TODO: this is checking globally, it should only be allowed when accounts are not mandatory
var nr = dao.count() + 1
var name = "$entityType-$nr"
while (dao.existsByName(name)) {
nr++
name = "$entityType-$nr"
}
return name
}
override fun autoName(ownerType: AssetOwnerType, ownerId: UUID): String {
TODO()
}
} | apache-2.0 | 2d500961ecdcd7a52ff885b62b1c5490 | 28.264957 | 104 | 0.721297 | 3.423 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/uast/uast-kotlin-idea/tests/test/org/jetbrains/uast/test/kotlin/KotlinUastGenerationTest.kt | 4 | 46755 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.test.kotlin
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.Ref
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiType
import com.intellij.psi.SyntaxTraverser
import com.intellij.psi.util.parentOfType
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.UsefulTestCase
import junit.framework.TestCase
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.utils.addToStdlib.cast
import org.jetbrains.uast.*
import org.jetbrains.uast.expressions.UInjectionHost
import org.jetbrains.uast.generate.UParameterInfo
import org.jetbrains.uast.generate.UastCodeGenerationPlugin
import org.jetbrains.uast.generate.refreshed
import org.jetbrains.uast.generate.replace
import org.jetbrains.uast.kotlin.generate.KotlinUastElementFactory
import org.jetbrains.uast.test.env.findElementByTextFromPsi
import org.jetbrains.uast.test.env.findUElementByTextFromPsi
import org.jetbrains.uast.visitor.UastVisitor
import kotlin.test.fail as kfail
class KotlinUastGenerationTest : KotlinLightCodeInsightFixtureTestCase() {
override fun getProjectDescriptor(): LightProjectDescriptor =
KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
private val psiFactory
get() = KtPsiFactory(project)
private val generatePlugin: UastCodeGenerationPlugin
get() = UastCodeGenerationPlugin.byLanguage(KotlinLanguage.INSTANCE)!!
private val uastElementFactory
get() = generatePlugin.getElementFactory(myFixture.project) as KotlinUastElementFactory
fun `test logical and operation with simple operands`() {
val left = psiFactory.createExpression("true").toUElementOfType<UExpression>()
?: kfail("Cannot create left UExpression")
val right = psiFactory.createExpression("false").toUElementOfType<UExpression>()
?: kfail("Cannot create right UExpression")
val expression = uastElementFactory.createBinaryExpression(left, right, UastBinaryOperator.LOGICAL_AND, dummyContextFile())
?: kfail("Cannot create expression")
TestCase.assertEquals("true && false", expression.sourcePsi?.text)
}
fun `test logical and operation with simple operands with parenthesis`() {
val left = psiFactory.createExpression("(true)").toUElementOfType<UExpression>()
?: kfail("Cannot create left UExpression")
val right = psiFactory.createExpression("(false)").toUElementOfType<UExpression>()
?: kfail("Cannot create right UExpression")
val expression = uastElementFactory.createFlatBinaryExpression(left, right, UastBinaryOperator.LOGICAL_AND, dummyContextFile())
?: kfail("Cannot create expression")
TestCase.assertEquals("true && false", expression.sourcePsi?.text)
TestCase.assertEquals("""
UBinaryExpression (operator = &&)
ULiteralExpression (value = true)
ULiteralExpression (value = false)
""".trimIndent(), expression.putIntoFunctionBody().asRecursiveLogString().trim())
}
fun `test logical and operation with simple operands with parenthesis polyadic`() {
val left = psiFactory.createExpression("(true && false)").toUElementOfType<UExpression>()
?: kfail("Cannot create left UExpression")
val right = psiFactory.createExpression("(false)").toUElementOfType<UExpression>()
?: kfail("Cannot create right UExpression")
val expression = uastElementFactory.createFlatBinaryExpression(left, right, UastBinaryOperator.LOGICAL_AND, dummyContextFile())
?: kfail("Cannot create expression")
TestCase.assertEquals("true && false && false", expression.sourcePsi?.text)
TestCase.assertEquals("""
UBinaryExpression (operator = &&)
UBinaryExpression (operator = &&)
ULiteralExpression (value = null)
ULiteralExpression (value = null)
ULiteralExpression (value = null)
""".trimIndent(), expression.asRecursiveLogString().trim())
}
fun `test simple reference creating from variable`() {
val context = dummyContextFile()
val variable = uastElementFactory.createLocalVariable(
"a", PsiType.INT, uastElementFactory.createNullLiteral(context), false, context
)
val reference = uastElementFactory.createSimpleReference(variable, context) ?: kfail("cannot create reference")
TestCase.assertEquals("a", reference.identifier)
}
fun `test simple reference by name`() {
val reference = uastElementFactory.createSimpleReference("a", dummyContextFile())
TestCase.assertEquals("a", reference.identifier)
}
fun `test parenthesised expression`() {
val expression = psiFactory.createExpression("a + b").toUElementOfType<UExpression>()
?: kfail("cannot create expression")
val parenthesizedExpression = uastElementFactory.createParenthesizedExpression(expression, dummyContextFile())
?: kfail("cannot create parenthesized expression")
TestCase.assertEquals("(a + b)", parenthesizedExpression.sourcePsi?.text)
}
fun `test return expression`() {
val expression = psiFactory.createExpression("a + b").toUElementOfType<UExpression>()
?: kfail("Cannot find plugin")
val returnExpression = uastElementFactory.createReturnExpresion(expression, false, dummyContextFile())
TestCase.assertEquals("a + b", returnExpression.returnExpression?.asRenderString())
TestCase.assertEquals("return a + b", returnExpression.sourcePsi?.text)
}
fun `test variable declaration without type`() {
val expression = psiFactory.createExpression("1 + 2").toUElementOfType<UExpression>()
?: kfail("cannot create variable declaration")
val declaration = uastElementFactory.createLocalVariable("a", null, expression, false, dummyContextFile())
TestCase.assertEquals("var a = 1 + 2", declaration.sourcePsi?.text)
}
fun `test variable declaration with type`() {
val expression = psiFactory.createExpression("b").toUElementOfType<UExpression>()
?: kfail("cannot create variable declaration")
val declaration = uastElementFactory.createLocalVariable("a", PsiType.DOUBLE, expression, false, dummyContextFile())
TestCase.assertEquals("var a: kotlin.Double = b", declaration.sourcePsi?.text)
}
fun `test final variable declaration`() {
val expression = psiFactory.createExpression("b").toUElementOfType<UExpression>()
?: kfail("cannot create variable declaration")
val declaration = uastElementFactory.createLocalVariable("a", PsiType.DOUBLE, expression, true, dummyContextFile())
TestCase.assertEquals("val a: kotlin.Double = b", declaration.sourcePsi?.text)
}
fun `test final variable declaration with unique name`() {
val expression = psiFactory.createExpression("b").toUElementOfType<UExpression>()
?: kfail("cannot create variable declaration")
val declaration = uastElementFactory.createLocalVariable("a", PsiType.DOUBLE, expression, true, dummyContextFile())
TestCase.assertEquals("val a: kotlin.Double = b", declaration.sourcePsi?.text)
TestCase.assertEquals("""
ULocalVariable (name = a)
USimpleNameReferenceExpression (identifier = b)
""".trimIndent(), declaration.asRecursiveLogString().trim())
}
fun `test block expression`() {
val statement1 = psiFactory.createExpression("System.out.println()").toUElementOfType<UExpression>()
?: kfail("cannot create statement")
val statement2 = psiFactory.createExpression("System.out.println(2)").toUElementOfType<UExpression>()
?: kfail("cannot create statement")
val block = uastElementFactory.createBlockExpression(listOf(statement1, statement2), dummyContextFile())
TestCase.assertEquals("""
{
System.out.println()
System.out.println(2)
}
""".trimIndent(), block.sourcePsi?.text
)
}
fun `test lambda expression`() {
val statement = psiFactory.createExpression("System.out.println()").toUElementOfType<UExpression>()
?: kfail("cannot create statement")
val lambda = uastElementFactory.createLambdaExpression(
listOf(
UParameterInfo(PsiType.INT, "a"),
UParameterInfo(null, "b")
),
statement,
dummyContextFile()
) ?: kfail("cannot create lambda")
TestCase.assertEquals("{ a: kotlin.Int, b -> System.out.println() }", lambda.sourcePsi?.text)
TestCase.assertEquals("""
ULambdaExpression
UParameter (name = a)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UParameter (name = b)
UAnnotation (fqName = null)
UBlockExpression
UQualifiedReferenceExpression
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = System)
USimpleNameReferenceExpression (identifier = out)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println, resolvesTo = null)
""".trimIndent(), lambda.putIntoFunctionBody().asRecursiveLogString().trim())
}
private fun UExpression.putIntoFunctionBody(): UExpression {
val file = myFixture.configureByText("dummyFile.kt", "fun foo() { TODO() }") as KtFile
val ktFunction = file.declarations.single { it.name == "foo" } as KtFunction
val uMethod = ktFunction.toUElementOfType<UMethod>()!!
return runWriteCommand {
uMethod.uastBody.cast<UBlockExpression>().expressions.single().replace(this)!!
}
}
private fun <T : UExpression> T.putIntoVarInitializer(): T {
val file = myFixture.configureByText("dummyFile.kt", "val foo = TODO()") as KtFile
val ktFunction = file.declarations.single { it.name == "foo" } as KtProperty
val uMethod = ktFunction.toUElementOfType<UVariable>()!!
return runWriteCommand {
@Suppress("UNCHECKED_CAST")
generatePlugin.replace(uMethod.uastInitializer!!, this, UExpression::class.java) as T
}
}
private fun <T : UExpression> runWriteCommand(uExpression: () -> T): T {
val result = Ref<T>()
WriteCommandAction.runWriteCommandAction(project) {
result.set(uExpression())
}
return result.get()
}
fun `test lambda expression with explicit types`() {
val statement = psiFactory.createExpression("System.out.println()").toUElementOfType<UExpression>()
?: kfail("cannot create statement")
val lambda = uastElementFactory.createLambdaExpression(
listOf(
UParameterInfo(PsiType.INT, "a"),
UParameterInfo(PsiType.DOUBLE, "b")
),
statement,
dummyContextFile()
) ?: kfail("cannot create lambda")
TestCase.assertEquals("{ a: kotlin.Int, b: kotlin.Double -> System.out.println() }", lambda.sourcePsi?.text)
TestCase.assertEquals("""
ULambdaExpression
UParameter (name = a)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UParameter (name = b)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UBlockExpression
UQualifiedReferenceExpression
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = System)
USimpleNameReferenceExpression (identifier = out)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println, resolvesTo = null)
""".trimIndent(), lambda.putIntoFunctionBody().asRecursiveLogString().trim())
}
fun `test lambda expression with simplified block body with context`() {
val r = psiFactory.createExpression("return \"10\"").toUElementOfType<UExpression>()
?: kfail("cannot create return")
val block = uastElementFactory.createBlockExpression(listOf(r), dummyContextFile())
val lambda = uastElementFactory.createLambdaExpression(listOf(UParameterInfo(null, "a")), block, dummyContextFile())
?: kfail("cannot create lambda")
TestCase.assertEquals("""{ a -> "10" }""".trimMargin(), lambda.sourcePsi?.text)
TestCase.assertEquals("""
ULambdaExpression
UParameter (name = a)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UBlockExpression
UReturnExpression
ULiteralExpression (value = "10")
""".trimIndent(), lambda.putIntoVarInitializer().asRecursiveLogString().trim())
}
fun `test function argument replacement`() {
val file = myFixture.configureByText(
"test.kt", """
fun f(a: Any){}
fun main(){
f(a)
}
""".trimIndent()
)
val expression = file.findUElementByTextFromPsi<UCallExpression>("f(a)")
val newArgument = psiFactory.createExpression("b").toUElementOfType<USimpleNameReferenceExpression>()
?: kfail("cannot create reference")
WriteCommandAction.runWriteCommandAction(project) {
TestCase.assertNotNull(expression.valueArguments[0].replace(newArgument))
}
val updated = expression.refreshed() ?: kfail("cannot update expression")
TestCase.assertEquals("f", updated.methodName)
TestCase.assertTrue(updated.valueArguments[0] is USimpleNameReferenceExpression)
TestCase.assertEquals("b", (updated.valueArguments[0] as USimpleNameReferenceExpression).identifier)
TestCase.assertEquals("""
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (f))
USimpleNameReferenceExpression (identifier = f, resolvesTo = null)
USimpleNameReferenceExpression (identifier = b)
""".trimIndent(), updated.asRecursiveLogString().trim())
}
fun `test suggested name`() {
val expression = psiFactory.createExpression("f(a) + 1").toUElementOfType<UExpression>()
?: kfail("cannot create expression")
val variable = uastElementFactory.createLocalVariable(null, PsiType.INT, expression, true, dummyContextFile())
TestCase.assertEquals("val i: kotlin.Int = f(a) + 1", variable.sourcePsi?.text)
TestCase.assertEquals("""
ULocalVariable (name = i)
UBinaryExpression (operator = +)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (f))
USimpleNameReferenceExpression (identifier = <anonymous class>, resolvesTo = null)
USimpleNameReferenceExpression (identifier = a)
ULiteralExpression (value = null)
""".trimIndent(), variable.asRecursiveLogString().trim())
}
fun `test method call generation with receiver`() {
val receiver = psiFactory.createExpression(""""10"""").toUElementOfType<UExpression>()
?: kfail("cannot create receiver")
val arg1 = psiFactory.createExpression("1").toUElementOfType<UExpression>()
?: kfail("cannot create arg1")
val arg2 = psiFactory.createExpression("2").toUElementOfType<UExpression>()
?: kfail("cannot create arg2")
val methodCall = uastElementFactory.createCallExpression(
receiver,
"substring",
listOf(arg1, arg2),
null,
UastCallKind.METHOD_CALL
) ?: kfail("cannot create call")
TestCase.assertEquals(""""10".substring(1,2)""", methodCall.uastParent?.sourcePsi?.text)
TestCase.assertEquals("""
UQualifiedReferenceExpression
ULiteralExpression (value = "10")
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 2))
UIdentifier (Identifier (substring))
USimpleNameReferenceExpression (identifier = <anonymous class>, resolvesTo = null)
ULiteralExpression (value = null)
ULiteralExpression (value = null)
""".trimIndent(), methodCall.uastParent?.asRecursiveLogString()?.trim()
)
}
fun `test method call generation without receiver`() {
val arg1 = psiFactory.createExpression("1").toUElementOfType<UExpression>()
?: kfail("cannot create arg1")
val arg2 = psiFactory.createExpression("2").toUElementOfType<UExpression>()
?: kfail("cannot create arg2")
val methodCall = uastElementFactory.createCallExpression(
null,
"substring",
listOf(arg1, arg2),
null,
UastCallKind.METHOD_CALL
) ?: kfail("cannot create call")
TestCase.assertEquals("""substring(1,2)""", methodCall.sourcePsi?.text)
}
fun `test method call generation with generics restoring`() {
val arrays = psiFactory.createExpression("java.util.Arrays").toUElementOfType<UExpression>()
?: kfail("cannot create receiver")
val methodCall = uastElementFactory.createCallExpression(
arrays,
"asList",
listOf(),
createTypeFromText("java.util.List<java.lang.String>", null),
UastCallKind.METHOD_CALL,
dummyContextFile()
) ?: kfail("cannot create call")
TestCase.assertEquals("java.util.Arrays.asList<kotlin.String>()", methodCall.uastParent?.sourcePsi?.text)
}
fun `test method call generation with generics restoring 2 parameters`() {
val collections = psiFactory.createExpression("java.util.Collections").toUElementOfType<UExpression>()
?: kfail("cannot create receiver")
TestCase.assertEquals("java.util.Collections", collections.asRenderString())
val methodCall = uastElementFactory.createCallExpression(
collections,
"emptyMap",
listOf(),
createTypeFromText(
"java.util.Map<java.lang.String, java.lang.Integer>",
null
),
UastCallKind.METHOD_CALL,
dummyContextFile()
) ?: kfail("cannot create call")
TestCase.assertEquals("emptyMap<kotlin.String,kotlin.Int>()", methodCall.sourcePsi?.text)
TestCase.assertEquals("java.util.Collections.emptyMap<kotlin.String,kotlin.Int>()", methodCall.sourcePsi?.parent?.text)
TestCase.assertEquals(
"""
UQualifiedReferenceExpression
UQualifiedReferenceExpression
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = java)
USimpleNameReferenceExpression (identifier = util)
USimpleNameReferenceExpression (identifier = Collections)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (emptyMap))
USimpleNameReferenceExpression (identifier = emptyMap, resolvesTo = null)
""".trimIndent(), methodCall.uastParent?.asRecursiveLogString()?.trim()
)
}
private fun dummyContextFile(): KtFile = myFixture.configureByText("file.kt", "fun foo() {}") as KtFile
fun `test method call generation with generics restoring 1 parameter with 1 existing`() {
val a = psiFactory.createExpression("A").toUElementOfType<UExpression>()
?: kfail("cannot create a receiver")
val param = psiFactory.createExpression("\"a\"").toUElementOfType<UExpression>()
?: kfail("cannot create a parameter")
val methodCall = uastElementFactory.createCallExpression(
a,
"kek",
listOf(param),
createTypeFromText(
"java.util.Map<java.lang.String, java.lang.Integer>",
null
),
UastCallKind.METHOD_CALL,
dummyContextFile()
) ?: kfail("cannot create call")
TestCase.assertEquals("A.kek<kotlin.String,kotlin.Int>(\"a\")", methodCall.sourcePsi?.parent?.text)
TestCase.assertEquals(
"""
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = A)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (kek))
USimpleNameReferenceExpression (identifier = <anonymous class>, resolvesTo = null)
ULiteralExpression (value = "a")
""".trimIndent(), methodCall.uastParent?.asRecursiveLogString()?.trim()
)
}
fun `test callable reference generation with receiver`() {
val receiver = uastElementFactory.createQualifiedReference("java.util.Arrays", myFixture.file)
?: kfail("failed to create receiver")
val methodReference = uastElementFactory.createCallableReferenceExpression(receiver, "asList", myFixture.file)
?: kfail("failed to create method reference")
TestCase.assertEquals(methodReference.sourcePsi?.text, "java.util.Arrays::asList")
}
fun `test callable reference generation without receiver`() {
val methodReference = uastElementFactory.createCallableReferenceExpression(null, "asList", myFixture.file)
?: kfail("failed to create method reference")
TestCase.assertEquals(methodReference.sourcePsi?.text, "::asList")
}
//not implemented (currently we dont perform resolve in code generating)
fun `ignore method call generation with generics restoring 1 parameter with 1 unused `() {
val aClassFile = myFixture.configureByText(
"A.kt",
"""
object A {
fun <T1, T2, T3> kek(a: T1): Map<T1, T3> {
return TODO();
}
}
""".trimIndent()
)
val a = psiFactory.createExpression("A").toUElementOfType<UExpression>()
?: kfail("cannot create a receiver")
val param = psiFactory.createExpression("\"a\"").toUElementOfType<UExpression>()
?: kfail("cannot create a parameter")
val methodCall = uastElementFactory.createCallExpression(
a,
"kek",
listOf(param),
createTypeFromText(
"java.util.Map<java.lang.String, java.lang.Integer>",
null
),
UastCallKind.METHOD_CALL,
aClassFile
) ?: kfail("cannot create call")
TestCase.assertEquals("A.<String, Object, Integer>kek(\"a\")", methodCall.sourcePsi?.text)
}
fun `test method call generation with generics with context`() {
val file = myFixture.configureByText("file.kt", """
class A {
fun <T> method(): List<T> { TODO() }
}
fun main(){
val a = A()
println(a)
}
""".trimIndent()
) as KtFile
val reference = file.findUElementByTextFromPsi<UElement>("println(a)", strict = true)
.findElementByTextFromPsi<UReferenceExpression>("a")
val callExpression = uastElementFactory.createCallExpression(
reference,
"method",
emptyList(),
createTypeFromText(
"java.util.List<java.lang.Integer>",
null
),
UastCallKind.METHOD_CALL,
context = reference.sourcePsi
) ?: kfail("cannot create method call")
TestCase.assertEquals("a.method<kotlin.Int>()", callExpression.uastParent?.sourcePsi?.text)
TestCase.assertEquals("""
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = a)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (method))
USimpleNameReferenceExpression (identifier = method, resolvesTo = null)
""".trimIndent(), callExpression.uastParent?.asRecursiveLogString()?.trim()
)
}
fun `test method call generation without generics with context`() {
val file = myFixture.configureByText("file.kt", """
class A {
fun <T> method(t: T): List<T> { TODO() }
}
fun main(){
val a = A()
println(a)
}
""".trimIndent()
) as KtFile
val reference = file.findUElementByTextFromPsi<UElement>("println(a)")
.findElementByTextFromPsi<UReferenceExpression>("a")
val callExpression = uastElementFactory.createCallExpression(
reference,
"method",
listOf(uastElementFactory.createIntLiteral(1, null)),
createTypeFromText(
"java.util.List<java.lang.Integer>",
null
),
UastCallKind.METHOD_CALL,
context = reference.sourcePsi
) ?: kfail("cannot create method call")
TestCase.assertEquals("a.method(1)", callExpression.uastParent?.sourcePsi?.text)
TestCase.assertEquals("""
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = a)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (method))
USimpleNameReferenceExpression (identifier = method, resolvesTo = null)
ULiteralExpression (value = 1)
""".trimIndent(), callExpression.uastParent?.asRecursiveLogString()?.trim()
)
}
fun `test replace lambda implicit return value`() {
val file = myFixture.configureByText(
"file.kt", """
fun main(){
val a: (Int) -> String = {
println(it)
println(2)
"abc"
}
}
""".trimIndent()
) as KtFile
val uLambdaExpression = file.findUElementByTextFromPsi<UInjectionHost>("\"abc\"")
.getParentOfType<ULambdaExpression>() ?: kfail("cant get lambda")
val expressions = uLambdaExpression.body.cast<UBlockExpression>().expressions
UsefulTestCase.assertSize(3, expressions)
val uReturnExpression = expressions.last() as UReturnExpression
val newStringLiteral = uastElementFactory.createStringLiteralExpression("def", file)
val defReturn = runWriteCommand { uReturnExpression.replace(newStringLiteral) ?: kfail("cant replace") }
val uLambdaExpression2 = defReturn.getParentOfType<ULambdaExpression>() ?: kfail("cant get lambda")
TestCase.assertEquals("{\n println(it)\n println(2)\n \"def\"\n }", uLambdaExpression2.sourcePsi?.text)
TestCase.assertEquals(
"""
ULambdaExpression
UParameter (name = it)
UBlockExpression
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println, resolvesTo = null)
USimpleNameReferenceExpression (identifier = it)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println, resolvesTo = null)
ULiteralExpression (value = 2)
UReturnExpression
ULiteralExpression (value = "def")
""".trimIndent(), uLambdaExpression2.asRecursiveLogString().trim()
)
}
private class UserDataChecker {
private val storedData = Any()
private val KEY = Key.create<Any>("testKey")
private lateinit var uniqueStringLiteralText: String
fun store(uElement: UInjectionHost) {
val psiElement = uElement.sourcePsi as KtStringTemplateExpression
uniqueStringLiteralText = psiElement.text
psiElement.putCopyableUserData(KEY, storedData)
}
fun checkUserDataAlive(uElement: UElement) {
val psiElements = uElement.let { SyntaxTraverser.psiTraverser(it.sourcePsi) }
.filter(KtStringTemplateExpression::class.java)
.filter { it.text == uniqueStringLiteralText }.toList()
UsefulTestCase.assertNotEmpty(psiElements)
UsefulTestCase.assertTrue("uElement still should keep the userdata", psiElements.any { storedData === it!!.getCopyableUserData(KEY) })
}
}
fun `test add intermediate returns to lambda`() {
val file = myFixture.configureByText(
"file.kt", """
fun main(){
val a: (Int) -> String = lname@{
println(it)
println(2)
"abc"
}
}
""".trimIndent()
) as KtFile
val aliveChecker = UserDataChecker()
val uLambdaExpression = file.findUElementByTextFromPsi<UInjectionHost>("\"abc\"")
.also(aliveChecker::store)
.getParentOfType<ULambdaExpression>() ?: kfail("cant get lambda")
val oldBlockExpression = uLambdaExpression.body.cast<UBlockExpression>()
UsefulTestCase.assertSize(3, oldBlockExpression.expressions)
val conditionalExit = with(uastElementFactory) {
createIfExpression(
createBinaryExpression(
createSimpleReference("it", uLambdaExpression.sourcePsi),
createIntLiteral(3, uLambdaExpression.sourcePsi),
UastBinaryOperator.GREATER,
uLambdaExpression.sourcePsi
)!!,
createReturnExpresion(
createStringLiteralExpression("exit", uLambdaExpression.sourcePsi), true,
uLambdaExpression.sourcePsi
),
null,
uLambdaExpression.sourcePsi
)!!
}
val newBlockExpression = uastElementFactory.createBlockExpression(
listOf(conditionalExit) + oldBlockExpression.expressions,
uLambdaExpression.sourcePsi
)
aliveChecker.checkUserDataAlive(newBlockExpression)
val uLambdaExpression2 = runWriteCommand {
oldBlockExpression.replace(newBlockExpression) ?: kfail("cant replace")
}.getParentOfType<ULambdaExpression>() ?: kfail("cant get lambda")
aliveChecker.checkUserDataAlive(uLambdaExpression2)
TestCase.assertEquals(
"""
lname@{
if (it > 3) return@lname "exit"
println(it)
println(2)
"abc"
}
""".trimIndent(), uLambdaExpression2.sourcePsi?.parent?.text
)
TestCase.assertEquals(
"""
ULambdaExpression
UParameter (name = it)
UBlockExpression
UIfExpression
UBinaryExpression (operator = >)
USimpleNameReferenceExpression (identifier = it)
ULiteralExpression (value = 3)
UReturnExpression
ULiteralExpression (value = "exit")
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println, resolvesTo = null)
USimpleNameReferenceExpression (identifier = it)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println, resolvesTo = null)
ULiteralExpression (value = 2)
UReturnExpression
ULiteralExpression (value = "abc")
""".trimIndent(), uLambdaExpression2.asRecursiveLogString().trim()
)
}
fun `test converting lambda to if`() {
val file = myFixture.configureByText(
"file.kt", """
fun foo(call: (Int) -> String): String = call.invoke(2)
fun main() {
foo {
println(it)
println(2)
"abc"
}
}
}
""".trimIndent()
) as KtFile
val aliveChecker = UserDataChecker()
val uLambdaExpression = file.findUElementByTextFromPsi<UInjectionHost>("\"abc\"")
.also { aliveChecker.store(it) }
.getParentOfType<ULambdaExpression>() ?: kfail("cant get lambda")
val oldBlockExpression = uLambdaExpression.body.cast<UBlockExpression>()
aliveChecker.checkUserDataAlive(oldBlockExpression)
val newLambda = with(uastElementFactory) {
createLambdaExpression(
listOf(UParameterInfo(null, "it")),
createIfExpression(
createBinaryExpression(
createSimpleReference("it", uLambdaExpression.sourcePsi),
createIntLiteral(3, uLambdaExpression.sourcePsi),
UastBinaryOperator.GREATER,
uLambdaExpression.sourcePsi
)!!,
oldBlockExpression,
createReturnExpresion(
createStringLiteralExpression("exit", uLambdaExpression.sourcePsi), true,
uLambdaExpression.sourcePsi
),
uLambdaExpression.sourcePsi
)!!.also {
aliveChecker.checkUserDataAlive(it)
},
uLambdaExpression.sourcePsi
)!!
}
aliveChecker.checkUserDataAlive(newLambda)
val uLambdaExpression2 = runWriteCommand {
uLambdaExpression.replace(newLambda) ?: kfail("cant replace")
}
TestCase.assertEquals(
"""
{ it ->
if (it > 3) {
println(it)
println(2)
"abc"
} else return@foo "exit"
}
""".trimIndent(), uLambdaExpression2.sourcePsi?.parent?.text
)
TestCase.assertEquals(
"""
ULambdaExpression
UParameter (name = it)
UAnnotation (fqName = null)
UBlockExpression
UReturnExpression
UIfExpression
UBinaryExpression (operator = >)
USimpleNameReferenceExpression (identifier = it)
ULiteralExpression (value = 3)
UBlockExpression
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println, resolvesTo = null)
USimpleNameReferenceExpression (identifier = it)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println, resolvesTo = null)
ULiteralExpression (value = 2)
ULiteralExpression (value = "abc")
UReturnExpression
ULiteralExpression (value = "exit")
""".trimIndent(), uLambdaExpression2.asRecursiveLogString().trim()
)
aliveChecker.checkUserDataAlive(uLambdaExpression2)
}
fun `test removing unnecessary type parameters while replace`() {
val aClassFile = myFixture.configureByText(
"A.kt",
"""
class A {
fun <T> method():List<T> = TODO()
}
""".trimIndent()
)
val reference = psiFactory.createExpression("a")
.toUElementOfType<UReferenceExpression>() ?: kfail("cannot create reference expression")
val callExpression = uastElementFactory.createCallExpression(
reference,
"method",
emptyList(),
createTypeFromText(
"java.util.List<java.lang.Integer>",
null
),
UastCallKind.METHOD_CALL,
context = aClassFile
) ?: kfail("cannot create method call")
val listAssigment = myFixture.addFileToProject("temp.kt", """
fun foo(kek: List<Int>) {
val list: List<Int> = kek
}
""".trimIndent()).findUElementByTextFromPsi<UVariable>("val list: List<Int> = kek")
WriteCommandAction.runWriteCommandAction(project) {
val methodCall = listAssigment.uastInitializer?.replace(callExpression) ?: kfail("cannot replace!")
// originally result expected be `a.method()` but we expect to clean up type arguments in other plase
TestCase.assertEquals("a.method<Int>()", methodCall.sourcePsi?.parent?.text)
}
}
fun `test create if`() {
val condition = psiFactory.createExpression("true").toUElementOfType<UExpression>()
?: kfail("cannot create condition")
val thenBranch = psiFactory.createBlock("{a(b);}").toUElementOfType<UExpression>()
?: kfail("cannot create then branch")
val elseBranch = psiFactory.createExpression("c++").toUElementOfType<UExpression>()
?: kfail("cannot create else branch")
val ifExpression = uastElementFactory.createIfExpression(condition, thenBranch, elseBranch, dummyContextFile())
?: kfail("cannot create if expression")
TestCase.assertEquals("if (true) {\n { a(b); }\n } else c++", ifExpression.sourcePsi?.text)
}
fun `test qualified reference`() {
val reference = uastElementFactory.createQualifiedReference("java.util.List", myFixture.file)
TestCase.assertEquals("java.util.List", reference?.sourcePsi?.text)
}
fun `test build lambda from returning a variable`() {
val context = dummyContextFile()
val localVariable = uastElementFactory.createLocalVariable("a", null, uastElementFactory.createNullLiteral(context), true, context)
val declarationExpression =
uastElementFactory.createDeclarationExpression(listOf(localVariable), context)
val returnExpression = uastElementFactory.createReturnExpresion(
uastElementFactory.createSimpleReference(localVariable, context), false, context
)
val block = uastElementFactory.createBlockExpression(listOf(declarationExpression, returnExpression), context)
TestCase.assertEquals("""
UBlockExpression
UDeclarationsExpression
ULocalVariable (name = a)
ULiteralExpression (value = null)
UReturnExpression
USimpleNameReferenceExpression (identifier = a)
""".trimIndent(), block.asRecursiveLogString().trim())
val lambda = uastElementFactory.createLambdaExpression(listOf(), block, context) ?: kfail("cannot create lambda expression")
TestCase.assertEquals("{ val a = null\na }", lambda.sourcePsi?.text)
TestCase.assertEquals("""
ULambdaExpression
UBlockExpression
UDeclarationsExpression
ULocalVariable (name = a)
ULiteralExpression (value = null)
UReturnExpression
USimpleNameReferenceExpression (identifier = a)
""".trimIndent(), lambda.putIntoVarInitializer().asRecursiveLogString().trim())
}
fun `test expand oneline lambda`() {
val context = dummyContextFile()
val parameters = listOf(UParameterInfo(PsiType.INT, "a"))
val oneLineLambda = with(uastElementFactory) {
createLambdaExpression(
parameters,
createBinaryExpression(
createSimpleReference("a", context),
createSimpleReference("a", context),
UastBinaryOperator.PLUS, context
)!!, context
)!!
}.putIntoVarInitializer()
val lambdaReturn = (oneLineLambda.body as UBlockExpression).expressions.single()
val lambda = with(uastElementFactory) {
createLambdaExpression(
parameters,
createBlockExpression(
listOf(
createCallExpression(
null,
"println",
listOf(createSimpleReference("a", context)),
PsiType.VOID,
UastCallKind.METHOD_CALL,
context
)!!,
lambdaReturn
),
context
), context
)!!
}
TestCase.assertEquals("{ a: kotlin.Int -> println(a)\na + a }", lambda.sourcePsi?.text)
TestCase.assertEquals("""
ULambdaExpression
UParameter (name = a)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UBlockExpression
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println, resolvesTo = null)
USimpleNameReferenceExpression (identifier = a)
UReturnExpression
UBinaryExpression (operator = +)
USimpleNameReferenceExpression (identifier = a)
USimpleNameReferenceExpression (identifier = a)
""".trimIndent(), lambda.putIntoVarInitializer().asRecursiveLogString().trim())
}
fun `test moving lambda from parenthesis`() {
myFixture.configureByText("myFile.kt", """
fun a(p: (Int) -> Unit) {}
""".trimIndent())
val lambdaExpression = uastElementFactory.createLambdaExpression(
emptyList(),
uastElementFactory.createNullLiteral(null),
null
) ?: kfail("Cannot create lambda")
val callExpression = uastElementFactory.createCallExpression(
null,
"a",
listOf(lambdaExpression),
null,
UastCallKind.METHOD_CALL,
myFixture.file
) ?: kfail("Cannot create method call")
TestCase.assertEquals("""a{ null }""", callExpression.sourcePsi?.text)
}
fun `test saving space after receiver`() {
myFixture.configureByText("myFile.kt", """
fun f() {
a
.b()
.c<caret>()
.d()
}
""".trimIndent())
val receiver =
myFixture.file.findElementAt(myFixture.caretOffset)?.parentOfType<KtDotQualifiedExpression>().toUElementOfType<UExpression>()
?: kfail("Cannot find UExpression")
val callExpression = uastElementFactory.createCallExpression(
receiver,
"e",
listOf(),
null,
UastCallKind.METHOD_CALL,
null
) ?: kfail("Cannot create call expression")
TestCase.assertEquals(
"""
a
.b()
.c()
.e()
""".trimIndent(),
callExpression.sourcePsi?.parentOfType<KtDotQualifiedExpression>()?.text
)
}
private fun createTypeFromText(s: String, newClass: PsiElement?): PsiType {
return JavaPsiFacade.getElementFactory(myFixture.project).createTypeFromText(s, newClass)
}
}
// it is a copy of org.jetbrains.uast.UastUtils.asRecursiveLogString with `appendLine` instead of `appendln` to avoid windows related issues
private fun UElement.asRecursiveLogString(render: (UElement) -> String = { it.asLogString() }): String {
val stringBuilder = StringBuilder()
val indent = " "
accept(object : UastVisitor {
private var level = 0
override fun visitElement(node: UElement): Boolean {
stringBuilder.append(indent.repeat(level))
stringBuilder.appendLine(render(node))
level++
return false
}
override fun afterVisitElement(node: UElement) {
super.afterVisitElement(node)
level--
}
})
return stringBuilder.toString()
}
| apache-2.0 | 591741f9b5c0a8e975921064a14f435f | 42.655462 | 158 | 0.601583 | 5.808075 | false | true | false | false |
dkrivoruchko/ScreenStream | app/src/main/kotlin/info/dvkr/screenstream/ui/view/ColorCircleView.kt | 1 | 1655 | package info.dvkr.screenstream.ui.view
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import androidx.annotation.ColorInt
class ColorCircleView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
private val fillPaint = Paint()
private val strokePaint = Paint()
private val borderWidth = resources.getDimension(com.afollestad.materialdialogs.color.R.dimen.color_circle_view_border)
init {
setWillNotDraw(false)
fillPaint.style = Paint.Style.FILL
fillPaint.isAntiAlias = true
fillPaint.color = Color.DKGRAY
strokePaint.style = Paint.Style.STROKE
strokePaint.isAntiAlias = true
strokePaint.color = Color.BLACK
strokePaint.strokeWidth = borderWidth
}
@ColorInt var color: Int = Color.BLACK
set(value) {
field = value
fillPaint.color = value
invalidate()
}
@ColorInt var border: Int = Color.DKGRAY
set(value) {
field = value
strokePaint.color = value
invalidate()
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) =
super.onMeasure(widthMeasureSpec, widthMeasureSpec)
override fun onDraw(canvas: Canvas) {
canvas.drawCircle(width / 2f, height / 2f, (width / 2f) - borderWidth, fillPaint)
canvas.drawCircle(width / 2f, height / 2f, (width / 2f) - borderWidth, strokePaint)
}
} | mit | f563cd950f917b3a69020259d1cd61c3 | 31.470588 | 123 | 0.676737 | 4.546703 | false | false | false | false |
brianwernick/ExoMedia | library/src/main/kotlin/com/devbrackets/android/exomedia/ui/widget/controls/DefaultVideoControls.kt | 1 | 19208 | package com.devbrackets.android.exomedia.ui.widget.controls
import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Handler
import android.os.Looper
import android.util.AttributeSet
import android.util.SparseBooleanArray
import android.view.View
import android.widget.ImageButton
import android.widget.ProgressBar
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.annotation.ColorRes
import androidx.annotation.IntRange
import androidx.annotation.LayoutRes
import com.devbrackets.android.exomedia.R
import com.devbrackets.android.exomedia.core.state.PlaybackState
import com.devbrackets.android.exomedia.ui.listener.VideoControlsButtonListener
import com.devbrackets.android.exomedia.ui.listener.VideoControlsSeekListener
import com.devbrackets.android.exomedia.ui.listener.VideoControlsVisibilityListener
import com.devbrackets.android.exomedia.ui.widget.VideoView
import com.devbrackets.android.exomedia.util.Repeater
import com.devbrackets.android.exomedia.util.millisToFormattedDuration
import com.devbrackets.android.exomedia.util.tintListCompat
import java.util.*
import kotlin.math.abs
/**
* This is a simple abstraction for the [VideoView] to have a single "View" to add
* or remove for the Default Video Controls.
*/
abstract class DefaultVideoControls : RelativeLayout, VideoControls {
companion object {
@JvmStatic
val DEFAULT_CONTROL_HIDE_DELAY = 2_000L
@JvmStatic
protected val CONTROL_VISIBILITY_ANIMATION_LENGTH: Long = 300
}
protected lateinit var currentTimeTextView: TextView
protected lateinit var endTimeTextView: TextView
protected lateinit var titleTextView: TextView
protected lateinit var subTitleTextView: TextView
protected lateinit var playPauseButton: ImageButton
protected lateinit var previousButton: ImageButton
protected lateinit var nextButton: ImageButton
protected lateinit var loadingProgressBar: ProgressBar
protected lateinit var playDrawable: Drawable
protected lateinit var pauseDrawable: Drawable
protected var visibilityHandler = Handler(Looper.getMainLooper())
protected var progressPollRepeater = Repeater {
updateProgress()
}
protected var videoView: VideoView? = null
var seekListener: VideoControlsSeekListener? = null
var buttonsListener: VideoControlsButtonListener? = null
var visibilityListener: VideoControlsVisibilityListener? = null
protected var internalListener = InternalListener()
protected var enabledViews = SparseBooleanArray()
/**
* The delay in milliseconds to wait to start the hide animation
*/
protected var hideDelay = DEFAULT_CONTROL_HIDE_DELAY
protected var isLoading = false
protected var isVisible = true
/**
* `true` If the empty text blocks can be hidden [default: true]
*/
protected var hideEmptyTextContainer = true
set(value) {
field = value
updateTextContainerVisibility()
}
private var lastUpdatedPosition: Long = 0
private var knownDuration: Long? = null
/**
* Used to retrieve the layout resource identifier to inflate
*
* @return The layout resource identifier to inflate
*/
@get:LayoutRes
protected abstract val layoutResource: Int
open val extraViews: List<View>
get() = LinkedList()
/**
* Determines if the `textContainer` doesn't have any text associated with it
*
* @return True if there is no text contained in the views in the `textContainer`
*/
protected val isTextContainerEmpty: Boolean
get() {
if (!titleTextView.text.isNullOrEmpty()) {
return false
}
return subTitleTextView.text.isNullOrEmpty()
}
/**
* Sets the current video position, updating the seek bar
* and the current time field
*
* @param position The position in milliseconds
*/
abstract fun setPosition(@IntRange(from = 0) position: Long)
/**
* Performs the progress update on the current time field,
* and the seek bar
*
* @param position The position in milliseconds
* @param duration The duration of the video in milliseconds
* @param bufferPercent The integer percent that is buffered [0, 100] inclusive
*/
abstract fun updateProgress(
@IntRange(from = 0) position: Long,
@IntRange(from = 0) duration: Long,
@IntRange(from = 0, to = 100) bufferPercent: Int
)
/**
* Performs the control visibility animation for showing or hiding
* this view
*
* @param toVisible True if the view should be visible at the end of the animation
*/
protected abstract fun animateVisibility(toVisible: Boolean)
/**
* Update the current visibility of the text block independent of
* the controls visibility
*/
protected abstract fun updateTextContainerVisibility()
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)
init {
setup(context)
}
/***
* Updates the current timestamp
*
* @param position The position in milliseconds
*/
protected fun updateCurrentTime(position: Long) {
// optimization :
// update the timestamp text per second regarding the 'reset' or 'seek' operations.
if (abs(position - lastUpdatedPosition) >= 1_000 || lastUpdatedPosition == 0L) {
lastUpdatedPosition = position
currentTimeTextView.text = position.millisToFormattedDuration()
}
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
if (videoView?.isPlaying == true) {
updatePlaybackState(true)
}
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
progressPollRepeater.stop()
}
override fun onAttachedToView(videoView: VideoView) {
videoView.addView(this)
this.videoView = videoView
}
override fun onDetachedFromView(videoView: VideoView) {
videoView.removeView(this)
this.videoView = null
}
/**
* Specifies the callback to inform of button click events
*
* @param callback The callback
*/
fun setButtonListener(callback: VideoControlsButtonListener?) {
this.buttonsListener = callback
}
override fun onPlaybackStateChange(state: PlaybackState) {
when (state) {
PlaybackState.IDLE -> {}
PlaybackState.PREPARING -> showLoading(true)
PlaybackState.BUFFERING -> showLoading(false)
PlaybackState.SEEKING -> showLoading(false)
PlaybackState.READY -> {
finishLoading()
}
PlaybackState.PLAYING -> updatePlaybackState(true)
PlaybackState.PAUSED -> updatePlaybackState(false)
PlaybackState.COMPLETED -> updatePlaybackState(false)
PlaybackState.STOPPED -> updatePlaybackState(false)
PlaybackState.RELEASED -> updatePlaybackState(false)
PlaybackState.ERROR -> updatePlaybackState(false)
}
}
/**
* Informs the controls that the playback state has changed. This will
* update to display the correct views, and manage progress polling.
*
* @param isPlaying True if the media is currently playing
*/
fun updatePlaybackState(isPlaying: Boolean) {
playPauseButton.setImageDrawable(if (isPlaying) pauseDrawable else playDrawable)
progressPollRepeater.start()
if (isPlaying) {
hideDelayed()
} else {
show()
}
}
/**
* Update the controls to indicate that the video
* is loading.
*
* @param initialLoad `true` if the loading is the initial state, not for seeking or buffering
*/
open fun showLoading(initialLoad: Boolean) {
if (isLoading) {
return
}
isLoading = true
}
/**
* Update the controls to indicate that the video is no longer loading
* which will re-display the play/pause, progress, etc. controls
*/
open fun finishLoading() {
if (!isLoading) {
return
}
isLoading = false
}
/**
* Sets the video duration in Milliseconds to display
* at the end of the progress bar
*
* @param duration The duration of the video in milliseconds
*/
open fun setDuration(@IntRange(from = 0) duration: Long) {
knownDuration = duration
}
/**
* Sets the title to display for the current item in playback
*
* @param title The title to display
*/
fun setTitle(title: CharSequence?) {
titleTextView.text = title
updateTextContainerVisibility()
}
/**
* Sets the subtitle to display for the current item in playback. This will be displayed
* as the second line of text
*
* @param subTitle The sub title to display
*/
fun setSubTitle(subTitle: CharSequence?) {
subTitleTextView.text = subTitle
updateTextContainerVisibility()
}
/**
* Sets the button state for the Previous button. This will just
* change the images specified with [.setPreviousDrawable],
* or use the defaults if they haven't been set, and block any click events.
*
*
* This method will NOT re-add buttons that have previously been removed with
* [.setNextButtonRemoved].
*
* @param enabled If the Previous button is enabled [default: false]
*/
fun setPreviousButtonEnabled(enabled: Boolean) {
previousButton.isEnabled = enabled
enabledViews.put(R.id.exomedia_controls_previous_btn, enabled)
}
/**
* Sets the button state for the Next button. This will just
* change the images specified with [.setNextDrawable],
* or use the defaults if they haven't been set, and block any click events.
*
* This method will NOT re-add buttons that have previously been removed with
* [.setPreviousButtonRemoved].
*
* @param enabled If the Next button is enabled [default: false]
*/
fun setNextButtonEnabled(enabled: Boolean) {
nextButton.isEnabled = enabled
enabledViews.put(R.id.exomedia_controls_next_btn, enabled)
}
/**
* Sets the button state for the Rewind button. This will just
* change the images specified with [.setRewindDrawable],
* or use the defaults if they haven't been set
*
*
* This method will NOT re-add buttons that have previously been removed with
* [.setRewindButtonRemoved].
*
* @param enabled If the Rewind button is enabled [default: false]
*/
open fun setRewindButtonEnabled(enabled: Boolean) {
//Purposefully left blank
}
/**
* Sets the button state for the Fast Forward button. This will just
* change the images specified with [.setFastForwardDrawable],
* or use the defaults if they haven't been set
*
*
* This method will NOT re-add buttons that have previously been removed with
* [.setFastForwardButtonRemoved].
*
* @param enabled If the Rewind button is enabled [default: false]
*/
open fun setFastForwardButtonEnabled(enabled: Boolean) {
//Purposefully left blank
}
/**
* Adds or removes the Previous button. This will change the visibility
* of the button, if you want to change the enabled/disabled images see [.setPreviousButtonEnabled]
*
* @param removed If the Previous button should be removed [default: true]
*/
fun setPreviousButtonRemoved(removed: Boolean) {
previousButton.visibility = if (removed) View.GONE else View.VISIBLE
}
/**
* Adds or removes the Next button. This will change the visibility
* of the button, if you want to change the enabled/disabled images see [.setNextButtonEnabled]
*
* @param removed If the Next button should be removed [default: true]
*/
fun setNextButtonRemoved(removed: Boolean) {
nextButton.visibility = if (removed) View.GONE else View.VISIBLE
}
/**
* Adds or removes the Rewind button. This will change the visibility
* of the button, if you want to change the enabled/disabled images see [.setRewindButtonEnabled]
*
* @param removed If the Rewind button should be removed [default: true]
*/
open fun setRewindButtonRemoved(removed: Boolean) {
// Purposefully left blank
}
/**
* Adds or removes the FastForward button. This will change the visibility
* of the button, if you want to change the enabled/disabled images see [.setFastForwardButtonEnabled]
*
* @param removed If the FastForward button should be removed [default: true]
*/
open fun setFastForwardButtonRemoved(removed: Boolean) {
// Purposefully left blank
}
open fun addExtraView(view: View) {
// Purposefully left blank
}
open fun removeExtraView(view: View) {
// Purposefully left blank
}
/**
* Immediately starts the animation to show the controls
*/
open fun show() {
// Makes sure we don't have a hide animation scheduled
visibilityHandler.removeCallbacksAndMessages(null)
clearAnimation()
animateVisibility(true)
}
protected fun hide(delayed: Boolean) {
if (delayed) {
hideDelayed()
} else {
hide()
}
}
/**
* Immediately starts the animation to hide the controls
*/
fun hide() {
if (isLoading) {
return
}
//Makes sure we don't have a separate hide animation scheduled
visibilityHandler.removeCallbacksAndMessages(null)
clearAnimation()
animateVisibility(false)
}
/**
* After the specified delay the view will be hidden. If the user is interacting
* with the controls then we wait until after they are done to start the delay.
*/
fun hideDelayed() {
hideDelayed(hideDelay)
}
/**
* After the specified delay the view will be hidden. If the user is interacting
* with the controls then we wait until after they are done to start the delay.
*
* @param delay The delay in milliseconds to wait to start the hide animation
*/
open fun hideDelayed(delay: Long) {
hideDelay = delay
if (delay < 0 || isLoading) {
return
}
visibilityHandler.postDelayed({ hide() }, delay)
}
/**
* Registers any internal listeners to perform the playback controls,
* such as play/pause, next, and previous
*/
protected open fun registerListeners() {
playPauseButton.setOnClickListener { onPlayPauseClick() }
previousButton.setOnClickListener { onPreviousClick() }
nextButton.setOnClickListener { onNextClick() }
}
/**
* Updates the drawables used for the buttons to AppCompatTintDrawables
*/
protected open fun updateButtonDrawables() {
updateButtonDrawables(R.color.exomedia_default_controls_button_selector)
}
protected open fun updateButtonDrawables(@ColorRes tintList: Int) {
playDrawable = context.tintListCompat(R.drawable.exomedia_ic_play_arrow_white, tintList)
pauseDrawable = context.tintListCompat(R.drawable.exomedia_ic_pause_white, tintList)
playPauseButton.setImageDrawable(playDrawable)
val previousDrawable = context.tintListCompat(R.drawable.exomedia_ic_skip_previous_white, tintList)
previousButton.setImageDrawable(previousDrawable)
val nextDrawable = context.tintListCompat(R.drawable.exomedia_ic_skip_next_white, tintList)
nextButton.setImageDrawable(nextDrawable)
}
/**
* Performs the functionality when the PlayPause button is clicked. This
* includes invoking the callback method if it is enabled, posting the bus
* event, and toggling the video playback.
*/
protected fun onPlayPauseClick() {
if (buttonsListener?.onPlayPauseClicked() != true) {
internalListener.onPlayPauseClicked()
}
}
/**
* Performs the functionality to inform any listeners that the previous
* button has been clicked
*/
protected fun onPreviousClick() {
if (buttonsListener?.onPreviousClicked() != true) {
internalListener.onPreviousClicked()
}
}
/**
* Performs the functionality to inform any listeners that the next
* button has been clicked
*/
protected fun onNextClick() {
if (buttonsListener?.onNextClicked() != true) {
internalListener.onNextClicked()
}
}
/**
* Performs any initialization steps such as retrieving views, registering listeners,
* and updating any drawables.
*
* @param context The context to use for retrieving the correct layout
*/
protected open fun setup(context: Context) {
View.inflate(context, layoutResource, this)
retrieveViews()
registerListeners()
updateButtonDrawables()
}
/**
* Retrieves the view references from the xml layout
*/
protected open fun retrieveViews() {
currentTimeTextView = findViewById(R.id.exomedia_controls_current_time)
endTimeTextView = findViewById(R.id.exomedia_controls_end_time)
titleTextView = findViewById(R.id.exomedia_controls_title)
subTitleTextView = findViewById(R.id.exomedia_controls_sub_title)
playPauseButton = findViewById(R.id.exomedia_controls_play_pause_btn)
previousButton = findViewById(R.id.exomedia_controls_previous_btn)
nextButton = findViewById(R.id.exomedia_controls_next_btn)
loadingProgressBar = findViewById(R.id.exomedia_controls_video_loading)
}
/**
* Performs the functionality to inform the callback
* that the DefaultControls visibility has changed
*/
protected fun onVisibilityChanged() {
if (isVisible) {
visibilityListener?.onControlsShown()
} else {
visibilityListener?.onControlsHidden()
}
}
/**
* Called by the [progressPollRepeater] to update the progress
* bar using the [videoView] to retrieve the correct information
*/
protected fun updateProgress() {
videoView?.let {
if (knownDuration == null || it.duration != knownDuration) {
setDuration(it.duration)
}
updateProgress(it.currentPosition, it.duration, it.bufferPercentage)
}
}
/**
* An internal class used to handle the default functionality for the
* VideoControls
*/
protected open inner class InternalListener : VideoControlsSeekListener, VideoControlsButtonListener {
private var pausedForSeek = false
override fun onPlayPauseClicked(): Boolean {
return videoView?.let {
if (it.isPlaying) {
it.pause()
} else {
it.start()
}
true
} ?: false
}
override fun onPreviousClicked(): Boolean {
//Purposefully left blank
return false
}
override fun onNextClicked(): Boolean {
//Purposefully left blank
return false
}
override fun onRewindClicked(): Boolean {
//Purposefully left blank
return false
}
override fun onFastForwardClicked(): Boolean {
//Purposefully left blank
return false
}
override fun onSeekStarted(): Boolean {
if (videoView == null) {
return false
}
if (videoView?.isPlaying == true) {
pausedForSeek = true
videoView?.pause(true)
}
show()
return true
}
override fun onSeekEnded(seekTime: Long): Boolean {
if (videoView == null) {
return false
}
videoView?.seekTo(seekTime)
if (pausedForSeek) {
pausedForSeek = false
videoView?.start()
hideDelayed()
}
return true
}
}
} | apache-2.0 | f7924bbcad7431aa6cb581453e307103 | 28.643519 | 140 | 0.707257 | 4.60734 | false | false | false | false |
brave-warrior/TravisClient_Android | app-v3/src/main/java/com/khmelenko/lab/varis/repodetails/BranchesFragment.kt | 2 | 3852 | package com.khmelenko.lab.varis.repodetails
import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.khmelenko.lab.varis.R
import com.khmelenko.lab.varis.network.response.Branches
import kotlinx.android.synthetic.main.fragment_list_refreshable.list_refreshable_recycler_view
import kotlinx.android.synthetic.main.fragment_list_refreshable.list_refreshable_swipe_view
import kotlinx.android.synthetic.main.fragment_list_refreshable.progressbar
import kotlinx.android.synthetic.main.view_empty.empty_text
/**
* Fragment with repository branches
*
* @author Dmytro Khmelenko
*/
class BranchesFragment : Fragment() {
private lateinit var branchesListAdapter: BranchesListAdapter
private var branches: Branches? = null
private var listener: BranchesListener? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_list_refreshable, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
list_refreshable_recycler_view.setHasFixedSize(true)
val layoutManager = LinearLayoutManager(context)
list_refreshable_recycler_view.layoutManager = layoutManager
branchesListAdapter = BranchesListAdapter(branches, { position ->
val branch = branches!!.branches[position]
listener?.onBranchSelected(branch.id)
})
list_refreshable_recycler_view.adapter = branchesListAdapter
list_refreshable_swipe_view.setColorSchemeResources(R.color.swipe_refresh_progress)
list_refreshable_swipe_view.setOnRefreshListener { listener?.onReloadBranches() }
progressbar.visibility = View.VISIBLE
}
/**
* Checks whether data existing or not
*/
private fun checkIfEmpty() {
empty_text.setText(R.string.repo_details_branches_empty)
if (branches == null || branches!!.branches.isEmpty()) {
empty_text.visibility = View.VISIBLE
} else {
empty_text.visibility = View.GONE
}
}
override fun onAttach(activity: Context) {
super.onAttach(activity)
try {
listener = activity as BranchesListener?
} catch (e: ClassCastException) {
throw ClassCastException("$activity must implement BranchesListener")
}
}
override fun onDetach() {
super.onDetach()
listener = null
}
/**
* Sets branches data
*
* @param branches Branches
*/
fun setBranches(branches: Branches?) {
list_refreshable_swipe_view.isRefreshing = false
progressbar.visibility = View.GONE
if (branches != null) {
this.branches = branches
branchesListAdapter.setBranches(this.branches)
branchesListAdapter.notifyDataSetChanged()
}
checkIfEmpty()
}
/**
* Interface for communication with this fragment
*/
interface BranchesListener {
/**
* Handles selection of the branch
*
* @param buildId Id of the last build in branch
*/
fun onBranchSelected(buildId: Long)
/**
* Handles request for reloading branches data
*/
fun onReloadBranches()
}
companion object {
/**
* Creates new instance of the fragment
*
* @return Fragment instance
*/
fun newInstance(): BranchesFragment {
return BranchesFragment()
}
}
}
| apache-2.0 | f5cece900168e1c945bf6a7b975340eb | 29.09375 | 94 | 0.665628 | 4.91954 | false | false | false | false |
google/playhvz | Android/ghvzApp/app/src/main/java/com/app/playhvz/screens/quiz/displayquestions/DisplayMultiAnswerQuestionFragment.kt | 1 | 4016 | /*
* Copyright 2020 Google 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.app.playhvz.screens.quiz.displayquestions
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.app.playhvz.R
import com.app.playhvz.common.ui.MarkdownTextView
import com.app.playhvz.firebase.classmodels.QuizQuestion
import com.app.playhvz.screens.declareallegiance.OnCheckAnswersInterface
import com.app.playhvz.screens.declareallegiance.OnUpdateNextButtonInterface
import kotlin.random.Random
class DisplayMultiAnswerQuestionFragment(val question: QuizQuestion) : Fragment(),
OnCheckAnswersInterface {
companion object {
val TAG = DisplayMultiAnswerQuestionFragment::class.qualifiedName
}
private lateinit var descriptionText: MarkdownTextView
private lateinit var recyclerView: RecyclerView
private lateinit var errorLabel: TextView
private lateinit var successLabel: TextView
private lateinit var answerAdapter: CorrectnessAnswerAdapter
private var randomOrderAnswers: MutableList<QuizQuestion.Answer> = mutableListOf()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
randomOrderAnswers.addAll(question.answers)
for (i in randomOrderAnswers.indices) {
randomOrderAnswers[i].order = Random.nextInt(100 * randomOrderAnswers.size)
}
randomOrderAnswers = randomOrderAnswers.sortedBy { answer -> answer.order }.toMutableList()
answerAdapter = CorrectnessAnswerAdapter(requireContext(), randomOrderAnswers)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val view =
inflater.inflate(R.layout.fragment_quiz_question_display_multi_answer, container, false)
descriptionText = view.findViewById(R.id.description_text)
errorLabel = view.findViewById(R.id.error_label)!!
successLabel = view.findViewById(R.id.success_label)!!
recyclerView = view.findViewById(R.id.answer_recycler_view)
recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.adapter = answerAdapter
descriptionText.text = question.text
return view
}
override fun checkAnswers() {
val selectedAnswers = answerAdapter.getSelectedAnswers()
var allCorrect = true
for (i in randomOrderAnswers.indices) {
val answer = randomOrderAnswers[i]
if (answer.isCorrect && !selectedAnswers[i]) {
allCorrect = false
}
if (selectedAnswers[i] && !answer.isCorrect) {
allCorrect = false
}
}
if (allCorrect) {
successLabel.visibility = View.VISIBLE
errorLabel.visibility = View.GONE
allAnswersCorrect()
} else {
successLabel.visibility = View.GONE
errorLabel.visibility = View.VISIBLE
}
}
private fun allAnswersCorrect() {
if (parentFragment is OnUpdateNextButtonInterface) {
val onUpdateNextListener = parentFragment as OnUpdateNextButtonInterface
onUpdateNextListener.enableNextButton(true)
}
}
} | apache-2.0 | 0bd9801e50dc691fc3c267694703cd93 | 37.257143 | 100 | 0.714641 | 4.821128 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/fe10/code-insight/src/org/jetbrains/kotlin/idea/quickfix/KotlinIntentionActionsFactory.kt | 2 | 1995 | // 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.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.QuickFixFactory
import org.jetbrains.kotlin.psi.KtCodeFragment
abstract class KotlinIntentionActionsFactory : QuickFixFactory {
protected open fun isApplicableForCodeFragment(): Boolean = false
protected abstract fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction>
open fun areActionsAvailable(diagnostic: Diagnostic): Boolean = createActions(diagnostic).isNotEmpty()
protected open fun doCreateActionsForAllProblems(
sameTypeDiagnostics: Collection<Diagnostic>
): List<IntentionAction> = emptyList()
fun createActions(diagnostic: Diagnostic): List<IntentionAction> = createActions(listOf(diagnostic), false)
fun createActionsForAllProblems(sameTypeDiagnostics: Collection<Diagnostic>): List<IntentionAction> =
createActions(sameTypeDiagnostics, true)
private fun createActions(sameTypeDiagnostics: Collection<Diagnostic>, createForAll: Boolean): List<IntentionAction> {
if (sameTypeDiagnostics.isEmpty()) return emptyList()
val first = sameTypeDiagnostics.first()
if (first.psiElement.containingFile is KtCodeFragment && !isApplicableForCodeFragment()) {
return emptyList()
}
if (sameTypeDiagnostics.size > 1 && createForAll) {
assert(sameTypeDiagnostics.all { it.psiElement == first.psiElement && it.factory == first.factory }) {
"It's expected to be the list of diagnostics of same type and for same element"
}
return doCreateActionsForAllProblems(sameTypeDiagnostics)
}
return sameTypeDiagnostics.flatMapTo(arrayListOf()) { doCreateActions(it) }
}
}
| apache-2.0 | a0daaf2768b41aeb5482f8a7aeeac539 | 44.340909 | 122 | 0.749373 | 5.45082 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/completion/impl-k1/src/org/jetbrains/kotlin/idea/completion/KotlinInsertTypeArgument.kt | 4 | 7091 | // 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.completion
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.UserDataHolder
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.intentions.InsertExplicitTypeArgumentsIntention
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.error.ErrorType
// Debugging tip: use 'PsiTreeUtilsKt.printTree' to see PSI trees in the runtime. See fun documentation for details.
data class TypeArgsWithOffset(val args: KtTypeArgumentList, val offset: Int)
var UserDataHolder.argList: TypeArgsWithOffset? by UserDataProperty(Key("KotlinInsertTypeArgument.ARG_LIST"))
fun addParamTypesIfNeeded(position: PsiElement): PsiElement {
if (!callExprToUpdateExists(position)) return position
return addParamTypes(position)
}
private fun addParamTypes(position: PsiElement): PsiElement {
data class CallAndDiff(
// callExpression is a child node of dotExprWithoutCaret in general case (in simple case they are equal)
val callExpression: KtCallExpression, // like call()
val dotExprWithoutCaret: KtExpression, // like smth.call()
val dotExprWithCaret: KtQualifiedExpression // initial expression like smth.call().IntellijIdeaRulezzz (now separate synthetic tree)
)
fun getCallWithParamTypesToAdd(positionInCopy: PsiElement): CallAndDiff? {
/*
............KtDotQualifiedExpression [call().IntellijIdeaRulezzz]
...............KtCallExpression [call()]
............................................................
...............KtNameReferenceExpression [IntellijIdeaRulezzz]
..................LeafPsiElement [IntellijIdeaRulezzz] (*) <= positionInCopy
Replacing KtQualifiedExpression with its nested KtCallExpression we're getting "non-broken" tree.
*/
val dotExprWithCaret = positionInCopy.parent.parent as? KtQualifiedExpression ?: return null
val dotExprWithCaretCopy = dotExprWithCaret.copy() as KtQualifiedExpression
val beforeDotExpr = dotExprWithCaret.receiverExpression // smth.call()
val dotExpressionWithoutCaret = dotExprWithCaret.replace(beforeDotExpr) as KtExpression // dotExprWithCaret = beforeDotExpr + '.[?]' + caret
val targetCall = dotExpressionWithoutCaret.findLastCallExpression() ?: return null // call()
return CallAndDiff(targetCall, dotExpressionWithoutCaret, dotExprWithCaretCopy)
}
fun applyTypeArguments(callAndDiff: CallAndDiff, bindingContext: BindingContext): Pair<KtTypeArgumentList, PsiElement>? {
val (callExpression, dotExprWithoutCaret, dotExprWithCaret) = callAndDiff
// KtCallExpression [call()]
InsertExplicitTypeArgumentsIntention.applyTo(callExpression, false) // affects dotExprWithoutCaret as a parent
// KtCallExpression [call<TypeA, TypeB>()]
val dotExprWithoutCaretCopy = dotExprWithoutCaret.copy() as KtExpression
// Now we're restoring original smth.call().IntellijIdeaRulezzz on its place and
// replace call() with call<TypeA, TypeB>().
// smth.call() -> smth.call().IntellijIdeaRulezzz
val originalDotExpr = dotExprWithoutCaret.replace(dotExprWithCaret) as KtQualifiedExpression
val originalNestedDotExpr = originalDotExpr.receiverExpression // smth.call()
originalNestedDotExpr.replace(dotExprWithoutCaretCopy) // smth.call() -> smth.call<TypeA, TYpeB>
// IntellijIdeaRulezzz as before
val newPosition = (originalDotExpr.selectorExpression as? KtNameReferenceExpression)?.getReferencedNameElement() ?: return null
val typeArguments = InsertExplicitTypeArgumentsIntention.createTypeArguments(callExpression, bindingContext) ?: return null
return typeArguments to newPosition
}
val fileCopy = position.containingFile.copy() as KtFile
val positionInCopy = PsiTreeUtil.findSameElementInCopy(position, fileCopy)
val callAndDiff = getCallWithParamTypesToAdd(positionInCopy) ?: return position
val (callExpression, dotExprWithoutCaret, _) = callAndDiff
val bindingContext = fileCopy.getResolutionFacade().analyze(dotExprWithoutCaret, BodyResolveMode.PARTIAL_FOR_COMPLETION)
if (!InsertExplicitTypeArgumentsIntention.isApplicableTo(callExpression, bindingContext))
return position
// We need to fix expression offset so that later 'typeArguments' could be inserted into the editor.
// See usages of `argList` -> JustTypingLookupElementDecorator#handleInsert.
val exprOffset = callExpression.endOffset // applyTypeArguments modifies PSI, offset is to be calculated before
val (typeArguments, newPosition) = applyTypeArguments(callAndDiff, bindingContext) ?: return position
return newPosition.also { it.argList = TypeArgsWithOffset(typeArguments, exprOffset) }
}
private fun callExprToUpdateExists(position: PsiElement): Boolean {
/*
Case: call().IntellijIdeaRulezzz or call()?.IntellijIdeaRulezzz or smth.call()?.IntellijIdeaRulezzz
'position' points to the caret - IntellijIdeaRulezzz and on PSI level it looks as follows:
............KtDotQualifiedExpression [call().IntellijIdeaRulezzz]
..............KtCallExpression [call()]
.............................................................
..............KtNameReferenceExpression [IntellijIdeaRulezzz]
..................LeafPsiElement [IntellijIdeaRulezzz] (*)
*/
val afterDotExprWithCaret = position.parent as? KtNameReferenceExpression ?: return false
val callBeforeDot = afterDotExprWithCaret.getPreviousInQualifiedChain() as? KtCallExpression ?: return false
return callBeforeDot.requiresTypeParams()
}
private fun KtCallExpression.requiresTypeParams(): Boolean {
if (typeArguments.isNotEmpty()) return false
val bindingContext = analyze(BodyResolveMode.PARTIAL)
val resolvedCall = getResolvedCall(bindingContext) ?: return false
if (resolvedCall.typeArguments.isEmpty()) return false
return resolvedCall.typeArguments.values.any { type -> type is ErrorType }
}
private fun KtExpression.getPreviousInQualifiedChain(): KtExpression? {
val receiverExpression = getQualifiedExpressionForSelector()?.receiverExpression
return (receiverExpression as? KtQualifiedExpression)?.selectorExpression ?: receiverExpression
}
private fun KtExpression.findLastCallExpression() =
((this as? KtQualifiedExpression)?.selectorExpression ?: this) as? KtCallExpression
| apache-2.0 | e0a8a2b35b732476d597f36e6eb2d4f1 | 52.315789 | 158 | 0.747849 | 5.105112 | false | false | false | false |
siosio/intellij-community | plugins/ide-features-trainer/src/training/lang/LangSupport.kt | 1 | 2961 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package training.lang
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.ToolWindowAnchor
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import training.learn.exceptons.InvalidSdkException
import training.learn.exceptons.NoSdkException
import java.io.File
import java.io.FileFilter
import java.nio.file.Path
interface LangSupport {
/** It should be a language ID */
val primaryLanguage: String
val defaultProductName: String?
get() = null
val defaultProjectName: String
val filename: String
get() = "Learning"
val langCourseFeedback: String?
get() = null
/** Relative path inside plugin resources */
val projectResourcePath: String
get() = "learnProjects/${primaryLanguage.toLowerCase()}/$defaultProjectName"
/** Language can specify default sandbox-like file to be used for lessons with modifications but also with project support */
val projectSandboxRelativePath: String?
get() = null
companion object {
const val EP_NAME = "training.ift.language.extension"
}
fun installAndOpenLearningProject(projectPath: Path, projectToClose: Project?, postInitCallback: (learnProject: Project) -> Unit)
fun copyLearningProjectFiles(projectDirectory: File, destinationFilter: FileFilter? = null): Boolean
/**
* Implement that method to define SDK lookup depending on a given project.
*
* @return an SDK instance which (existing or newly created) should be applied to the project given. Return `null`
* if no SDK is okay for this project.
*
* @throws NoSdkException in the case no valid SDK is available, yet it's required for the given project
*/
@Throws(NoSdkException::class)
fun getSdkForProject(project: Project): Sdk?
fun applyProjectSdk(sdk: Sdk, project: Project)
fun applyToProjectAfterConfigure(): (Project) -> Unit
/**
* <p> Implement that method to require some checks for the SDK in the learning project.
* The easiest check is to check the presence and SdkType, but other checks like language level
* might be applied as well.
*
* <p> The method should not return anything, but might throw exceptions subclassing InvalidSdkException which
* will be handled by a UI.
*/
@Throws(InvalidSdkException::class)
fun checkSdk(sdk: Sdk?, project: Project)
fun getProjectFilePath(projectName: String): String
fun getToolWindowAnchor(): ToolWindowAnchor = ToolWindowAnchor.LEFT
/** true means block source code modification in demo learning projects (scratches can be modified anyway)*/
fun blockProjectFileModification(project: Project, file: VirtualFile): Boolean = false
@RequiresBackgroundThread
fun cleanupBeforeLessons(project: Project) = Unit
}
| apache-2.0 | cc397cae8cced9db7a2e499890743005 | 37.454545 | 140 | 0.761905 | 4.562404 | false | false | false | false |
tlaukkan/kotlin-web-vr | server/src/main/kotlin/vr/network/model/HandshakeResponse.kt | 2 | 349 | package vr.network.model
data class HandshakeResponse(var software : String = "",
var protocolDialect : String = "",
var protocolVersion : String = "",
var serverCellUris: Array<String> = emptyArray(),
var accepted: Boolean = false) | mit | ba75ce5a06fd4ae5022b6bd5fdd0ba8a | 49 | 78 | 0.495702 | 6.232143 | false | false | false | false |
MartinStyk/AndroidApkAnalyzer | app/src/main/java/sk/styk/martin/apkanalyzer/ui/appdetail/AppDetailActivity.kt | 1 | 1698 | package sk.styk.martin.apkanalyzer.ui.appdetail
import android.os.Bundle
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import dagger.hilt.android.AndroidEntryPoint
import sk.styk.martin.apkanalyzer.R
import sk.styk.martin.apkanalyzer.databinding.ActivityAppDetailBinding
import sk.styk.martin.apkanalyzer.ui.ApkAnalyzerBaseActivity
import sk.styk.martin.apkanalyzer.ui.appdetail.AppDetailFragment.Companion.APP_DETAIL_REQUEST
import sk.styk.martin.apkanalyzer.util.FragmentTag
import sk.styk.martin.apkanalyzer.util.TAG_APP_DETAIL
import timber.log.Timber
@AndroidEntryPoint
open class AppDetailActivity : ApkAnalyzerBaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
DataBindingUtil.setContentView<ActivityAppDetailBinding>(this, R.layout.activity_app_detail)
if (savedInstanceState == null) {
val detailRequest = getDetailRequestBundle()
if (detailRequest?.getParcelable<AppDetailRequest>(APP_DETAIL_REQUEST) == null) {
Toast.makeText(this, R.string.error_loading_package_detail, Toast.LENGTH_LONG).show()
Timber.tag(TAG_APP_DETAIL).e(IllegalStateException("No app detail request"))
finishAffinity()
return
}
val fragment = AppDetailFragment().apply {
arguments = detailRequest
}
supportFragmentManager.beginTransaction()
.add(R.id.container, fragment, FragmentTag.AppDetailParent.tag)
.commit()
}
}
protected open fun getDetailRequestBundle(): Bundle? = intent.extras
}
| gpl-3.0 | b89925f912dd4166e3c851ab808735ea | 37.590909 | 101 | 0.712014 | 4.743017 | false | false | false | false |
joaomneto/TitanCompanion | src/main/java/pt/joaomneto/titancompanion/adventure/impl/fragments/god/GODAdventureCombatFragment.kt | 1 | 1779 | package pt.joaomneto.titancompanion.adventure.impl.fragments.god
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.CheckBox
import pt.joaomneto.titancompanion.R
import pt.joaomneto.titancompanion.adventure.impl.GODAdventure
import pt.joaomneto.titancompanion.adventure.impl.fragments.AdventureCombatFragment
class GODAdventureCombatFragment : AdventureCombatFragment() {
var demon: Boolean = false
var stoneCrystal: Boolean = false
var poisonActivated: Boolean = false
override val damage: () -> Int
get() = { ((activity as GODAdventure).weapon.damage(attackDiceRoll, demon, stoneCrystal)) }
override fun endOfTurnAction(): String {
val adv = activity as GODAdventure
if (adv.weapon == GODWeapon.ASSASSINS_STILETTO && adv.poison> 0 && currentEnemy.staminaLoss> 0) {
poisonActivated = true
adv.poison = adv.poison - 1
}
if (poisonActivated) {
currentEnemy.currentStamina = currentEnemy.currentStamina - 1
return " " + getString(R.string.poisonBlade)
}
return ""
}
override fun addCombatButtonOnClick() {
addCombatButtonOnClick(R.layout.component_64god_add_combatant)
}
override fun confirmCombatAction(mgr: InputMethodManager, addCombatantView: View) {
super.confirmCombatAction(mgr, addCombatantView)
demon = addCombatantView.findViewById<CheckBox>(R.id.demonValue).isChecked
stoneCrystal = addCombatantView.findViewById<CheckBox>(R.id.stoneCrystal).isChecked
}
override fun resetCombat(clearResult: Boolean) {
super.resetCombat(clearResult)
demon = false
stoneCrystal = false
poisonActivated = false
}
}
| lgpl-3.0 | d43b12e6cdacb8db9bd19363b261a61e | 34.58 | 105 | 0.709949 | 4.185882 | false | false | false | false |
mapzen/eraser-map | app/src/main/kotlin/com/mapzen/erasermap/model/MapzenLocationImpl.kt | 1 | 5267 | package com.mapzen.erasermap.model
import android.content.Context
import android.graphics.PointF
import android.location.Location
import android.util.Log
import android.view.WindowManager
import com.mapzen.android.graphics.MapzenMap
import com.mapzen.android.lost.api.LocationRequest
import com.mapzen.android.lost.api.LocationServices
import com.mapzen.erasermap.BuildConfig
import com.mapzen.erasermap.EraserMapApplication
import com.mapzen.erasermap.model.event.LocationChangeEvent
import com.mapzen.pelias.BoundingBox
import com.squareup.otto.Bus
public class MapzenLocationImpl(val locationClientManager: LocationClientManager,
val settings: AppSettings,
val bus: Bus,
val application: EraserMapApplication,
val permissionManager: PermissionManager) : MapzenLocation {
companion object {
private val LOCATION_UPDATE_INTERVAL_IN_MS: Long = 1000L
private val LOCATION_UPDATE_SMALLEST_DISPLACEMENT: Float = 3f
}
private val locationListener = object: com.mapzen.android.lost.api.LocationListener {
override fun onLocationChanged(location: Location) {
onLocationUpdate(location)
}
}
private val request = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(LOCATION_UPDATE_INTERVAL_IN_MS)
.setFastestInterval(LOCATION_UPDATE_INTERVAL_IN_MS)
.setSmallestDisplacement(LOCATION_UPDATE_SMALLEST_DISPLACEMENT)
init {
bus.register(this)
}
override var mapzenMap: MapzenMap? = null
private var previousLocation: Location? = null
private fun configureMockSettings() {
val locationClient = locationClientManager.getClient()
if (settings.isMockLocationEnabled) {
LocationServices.FusedLocationApi?.setMockMode(locationClient, true)
LocationServices.FusedLocationApi?.setMockLocation(locationClient, settings.mockLocation)
}
if (settings.isMockRouteEnabled) {
LocationServices.FusedLocationApi?.setMockTrace(locationClient, settings.mockRoute?.path,
settings.mockRoute?.name)
}
}
override fun getLastLocation(): Location? {
if (!permissionManager.permissionsGranted()) {
return null
}
configureMockSettings()
val client = locationClientManager.getClient()
return LocationServices.FusedLocationApi?.getLastLocation(client)
}
override fun startLocationUpdates() {
if (!permissionManager.permissionsGranted()) {
return
}
configureMockSettings()
val client = locationClientManager.getClient()
LocationServices.FusedLocationApi?.requestLocationUpdates(client, request, locationListener)
}
fun onLocationUpdate(location: Location) {
val previous = previousLocation
val displacement = if (previous != null) previous.distanceTo(location) else Float.MAX_VALUE
if (displacement > LOCATION_UPDATE_SMALLEST_DISPLACEMENT) {
if (BuildConfig.DEBUG) {
Log.d("MapzenLocation", "onLocationChanged: " + location)
}
bus.post(LocationChangeEvent(location))
} else {
if (BuildConfig.DEBUG) {
Log.d("MapzenLocation", "no significant change")
}
}
previousLocation = location
}
override fun stopLocationUpdates() {
val client = locationClientManager.getClient()
LocationServices.FusedLocationApi?.removeLocationUpdates(client, locationListener)
}
override fun getLat(): Double {
val windowManager = application.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val display = windowManager.defaultDisplay
val midLatLon = mapzenMap?.screenPositionToLngLat(PointF(display.width.toFloat() / 2,
display.height.toFloat() / 2))
if (midLatLon?.latitude == null) {
return 0.0
}
return midLatLon?.latitude as Double
}
override fun getLon(): Double {
val windowManager = application.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val display = windowManager.defaultDisplay
val midLatLon = mapzenMap?.screenPositionToLngLat(PointF(display.width.toFloat()/2,
display.height.toFloat()/2))
if (midLatLon?.longitude == null) {
return 0.0
}
return midLatLon?.longitude as Double
}
override fun getBoundingBox(): BoundingBox? {
val windowManager = application.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val display = windowManager.defaultDisplay
val minLatLon = mapzenMap?.screenPositionToLngLat(PointF(0.0f, display.height.toFloat()))
val maxLatLon = mapzenMap?.screenPositionToLngLat(PointF(display.width.toFloat(), 0.0f))
val boundingBox: BoundingBox = BoundingBox(
minLatLon?.latitude as Double,
minLatLon?.longitude as Double,
maxLatLon?.latitude as Double,
maxLatLon?.longitude as Double)
return boundingBox
}
override fun getLocationRequest(): LocationRequest {
return request
}
}
| gpl-3.0 | 8f5ecef21f9cc5f41cc05dc36820e496 | 36.892086 | 101 | 0.687108 | 4.968868 | false | false | false | false |
aosp-mirror/platform_frameworks_support | room/compiler/src/main/kotlin/androidx/room/processor/QueryMethodProcessor.kt | 1 | 7251 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.processor
import androidx.room.Query
import androidx.room.SkipQueryVerification
import androidx.room.Transaction
import androidx.room.ext.KotlinMetadataProcessor
import androidx.room.ext.hasAnnotation
import androidx.room.parser.ParsedQuery
import androidx.room.parser.QueryType
import androidx.room.parser.SqlParser
import androidx.room.solver.query.result.LiveDataQueryResultBinder
import androidx.room.solver.query.result.PojoRowAdapter
import androidx.room.verifier.DatabaseVerificaitonErrors
import androidx.room.verifier.DatabaseVerifier
import androidx.room.vo.QueryMethod
import androidx.room.vo.QueryParameter
import androidx.room.vo.Warning
import com.google.auto.common.AnnotationMirrors
import com.google.auto.common.MoreElements
import com.google.auto.common.MoreTypes
import com.squareup.javapoet.TypeName
import me.eugeniomarletti.kotlin.metadata.KotlinClassMetadata
import me.eugeniomarletti.kotlin.metadata.kotlinMetadata
import javax.annotation.processing.ProcessingEnvironment
import javax.lang.model.element.ExecutableElement
import javax.lang.model.type.DeclaredType
import javax.lang.model.type.TypeKind
class QueryMethodProcessor(
baseContext: Context,
val containing: DeclaredType,
val executableElement: ExecutableElement,
val dbVerifier: DatabaseVerifier? = null
) : KotlinMetadataProcessor {
val context = baseContext.fork(executableElement)
// for kotlin metadata
override val processingEnv: ProcessingEnvironment
get() = context.processingEnv
private val classMetadata =
try {
containing.asElement().kotlinMetadata
} catch (throwable: Throwable) {
context.logger.d(executableElement,
"failed to read get kotlin metadata from %s", executableElement)
} as? KotlinClassMetadata
fun process(): QueryMethod {
val asMember = context.processingEnv.typeUtils.asMemberOf(containing, executableElement)
val executableType = MoreTypes.asExecutable(asMember)
val annotation = MoreElements.getAnnotationMirror(executableElement,
Query::class.java).orNull()
context.checker.check(annotation != null, executableElement,
ProcessorErrors.MISSING_QUERY_ANNOTATION)
val query = if (annotation != null) {
val query = SqlParser.parse(
AnnotationMirrors.getAnnotationValue(annotation, "value").value.toString())
context.checker.check(query.errors.isEmpty(), executableElement,
query.errors.joinToString("\n"))
if (!executableElement.hasAnnotation(SkipQueryVerification::class)) {
query.resultInfo = dbVerifier?.analyze(query.original)
}
if (query.resultInfo?.error != null) {
context.logger.e(executableElement,
DatabaseVerificaitonErrors.cannotVerifyQuery(query.resultInfo!!.error!!))
}
context.checker.check(executableType.returnType.kind != TypeKind.ERROR,
executableElement, ProcessorErrors.CANNOT_RESOLVE_RETURN_TYPE,
executableElement)
query
} else {
ParsedQuery.MISSING
}
val returnTypeName = TypeName.get(executableType.returnType)
context.checker.notUnbound(returnTypeName, executableElement,
ProcessorErrors.CANNOT_USE_UNBOUND_GENERICS_IN_QUERY_METHODS)
if (query.type == QueryType.DELETE) {
context.checker.check(
returnTypeName == TypeName.VOID || returnTypeName == TypeName.INT,
executableElement,
ProcessorErrors.DELETION_METHODS_MUST_RETURN_VOID_OR_INT
)
}
val resultBinder = context.typeAdapterStore
.findQueryResultBinder(executableType.returnType, query)
context.checker.check(resultBinder.adapter != null || query.type != QueryType.SELECT,
executableElement, ProcessorErrors.CANNOT_FIND_QUERY_RESULT_ADAPTER)
if (resultBinder is LiveDataQueryResultBinder) {
context.checker.check(query.type == QueryType.SELECT, executableElement,
ProcessorErrors.LIVE_DATA_QUERY_WITHOUT_SELECT)
}
val inTransaction = when (query.type) {
QueryType.SELECT -> executableElement.hasAnnotation(Transaction::class)
else -> true
}
if (query.type == QueryType.SELECT && !inTransaction) {
// put a warning if it is has relations and not annotated w/ transaction
resultBinder.adapter?.rowAdapter?.let { rowAdapter ->
if (rowAdapter is PojoRowAdapter
&& rowAdapter.relationCollectors.isNotEmpty()) {
context.logger.w(Warning.RELATION_QUERY_WITHOUT_TRANSACTION,
executableElement, ProcessorErrors.TRANSACTION_MISSING_ON_RELATION)
}
}
}
val kotlinParameterNames = classMetadata?.getParameterNames(executableElement)
val parameters = executableElement.parameters
.mapIndexed { index, variableElement ->
QueryParameterProcessor(
baseContext = context,
containing = containing,
element = variableElement,
sqlName = kotlinParameterNames?.getOrNull(index)).process()
}
val queryMethod = QueryMethod(
element = executableElement,
query = query,
name = executableElement.simpleName.toString(),
returnType = executableType.returnType,
parameters = parameters,
inTransaction = inTransaction,
queryResultBinder = resultBinder)
val missing = queryMethod.sectionToParamMapping
.filter { it.second == null }
.map { it.first.text }
if (missing.isNotEmpty()) {
context.logger.e(executableElement,
ProcessorErrors.missingParameterForBindVariable(missing))
}
val unused = queryMethod.parameters.filterNot { param ->
queryMethod.sectionToParamMapping.any { it.second == param }
}.map(QueryParameter::sqlName)
if (unused.isNotEmpty()) {
context.logger.e(executableElement, ProcessorErrors.unusedQueryMethodParameter(unused))
}
return queryMethod
}
}
| apache-2.0 | b01d969056d53d2f9e44f4d6246cb620 | 42.680723 | 99 | 0.661426 | 5.292701 | false | false | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/ui/dialogs/PeriodWithTypePickerDialog.kt | 1 | 5217 | package com.orgzly.android.ui.dialogs
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.annotation.ArrayRes
import androidx.annotation.StringRes
import androidx.appcompat.app.AlertDialog
import com.orgzly.R
import com.orgzly.databinding.DialogPeriodWithTypeBinding
import com.orgzly.org.datetime.OrgInterval
/**
* A dialog that prompts the user for the repeater, delay or warning period.
*/
abstract class PeriodWithTypePickerDialog(
context: Context,
@StringRes private val titleId: Int,
@StringRes private val descriptionId: Int,
@ArrayRes private val typesId: Int?,
@ArrayRes private val typesDescriptionsId: Int,
private val initialValue: String
) : AlertDialog(context) {
abstract fun set(typeIndex: Int, interval: OrgInterval)
// Returns type index and OrgInterval
abstract fun parseValue(value: String): Pair<Int, OrgInterval>
private var binding: DialogPeriodWithTypeBinding =
DialogPeriodWithTypeBinding.inflate(LayoutInflater.from(context))
fun setup() {
setButton(DialogInterface.BUTTON_POSITIVE, context.getString(R.string.ok)) { _, _ ->
val typeIndex = binding.typePicker.value
val interval = getInterval(
binding.valuePicker.value,
binding.unitPicker.value)
set(typeIndex, interval)
}
setButton(DialogInterface.BUTTON_NEGATIVE, context.getString(R.string.cancel)) { _, _ ->
cancel()
}
if (typesId != null) {
val types = context.resources.getStringArray(typesId)
binding.typePicker.apply {
minValue = 0
maxValue = types.size - 1
displayedValues = types
setOnValueChangedListener { _, _, newVal ->
setTypeDescription(newVal)
}
}
} else {
binding.typePicker.visibility = View.GONE
}
binding.valuePicker.apply {
minValue = 1
maxValue = 100
wrapSelectorWheel = false
}
val units = context.resources.getStringArray(R.array.time_units)
binding.unitPicker.apply {
minValue = 0
maxValue = units.size - 1
displayedValues = units
wrapSelectorWheel = false
}
setView(binding.root)
setTitle(titleId)
setDescription()
setPickerValues(initialValue)
setTypeDescription(binding.typePicker.value)
}
private fun setDescription() {
binding.dialogDescription.text = context.getString(descriptionId)
}
private fun setPickerValues(value: String) {
val pair = parseValue(value)
val typeIndex = pair.first
val interval = pair.second
binding.typePicker.value = typeIndex
binding.valuePicker.let { valuePicker ->
// Increase the maximum if needed
if (valuePicker.maxValue < interval.value) {
valuePicker.maxValue = interval.value
/*
* Has to be called after setting minimum and maximum values,
* per http://stackoverflow.com/a/21065844.
*/
valuePicker.wrapSelectorWheel = false
}
valuePicker.value = interval.value
}
binding.unitPicker.value = interval.unit.ordinal
}
private fun setTypeDescription(index: Int) {
if (typesDescriptionsId == 0) {
binding.typeDescription.visibility = View.GONE
} else {
binding.typeDescription.text =
context.resources.getStringArray(typesDescriptionsId)[index]
binding.typeDescription.visibility = View.VISIBLE
}
}
private fun getInterval(value: Int, unitIndex: Int): OrgInterval {
val unit = unitIndex.let {
when (it) {
0 -> OrgInterval.Unit.HOUR
1 -> OrgInterval.Unit.DAY
2 -> OrgInterval.Unit.WEEK
3 -> OrgInterval.Unit.MONTH
4 -> OrgInterval.Unit.YEAR
else -> throw IllegalArgumentException("Unexpected unit spinner position ($it)")
}
}
return OrgInterval(value, unit)
}
override fun onSaveInstanceState(): Bundle {
return super.onSaveInstanceState().apply {
putInt(TYPE, binding.typePicker.value)
putInt(VALUE, binding.valuePicker.value)
putInt(UNIT, binding.unitPicker.value)
}
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
binding.typePicker.value = savedInstanceState.getInt(TYPE)
binding.valuePicker.value = savedInstanceState.getInt(VALUE)
binding.unitPicker.value = savedInstanceState.getInt(UNIT)
}
companion object {
private const val TYPE = "type"
private const val UNIT = "unit"
private const val VALUE = "value"
}
} | gpl-3.0 | a5b24394325da5e27be698d9b2ef0287 | 30.245509 | 96 | 0.617596 | 4.968571 | false | false | false | false |
spinnaker/kork | kork-plugins/src/test/kotlin/com/netflix/spinnaker/kork/plugins/update/repository/Front50UpdateRepositoryTest.kt | 3 | 3009 | /*
* Copyright 2020 Netflix, 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.netflix.spinnaker.kork.plugins.update.repository
import com.netflix.spinnaker.kork.plugins.update.internal.Front50Service
import com.netflix.spinnaker.kork.plugins.update.internal.SpinnakerPluginInfo
import com.netflix.spinnaker.kork.plugins.update.internal.SpinnakerPluginInfo.SpinnakerPluginRelease
import dev.minutest.junit.JUnit5Minutests
import dev.minutest.rootContext
import io.mockk.every
import io.mockk.mockk
import java.net.URL
import java.util.Collections
import org.pf4j.update.SimpleFileDownloader
import org.pf4j.update.verifier.CompoundVerifier
import retrofit2.Response
import strikt.api.expectThat
import strikt.assertions.get
import strikt.assertions.isA
import strikt.assertions.isEmpty
import strikt.assertions.isEqualTo
class Front50UpdateRepositoryTest : JUnit5Minutests {
fun tests() = rootContext<Fixture> {
fixture { Fixture() }
test("getPlugins populates the plugins cache, subsequent getPlugin returns cached item") {
every { front50Service.listAll().execute() } returns response
val plugins = subject.getPlugins()
expectThat(plugins)
.isA<MutableMap<String, SpinnakerPluginInfo>>()[pluginId]
.get { plugin.id }.isEqualTo(pluginId)
val plugin = subject.getPlugin(pluginId)
expectThat(plugin)
.isA<SpinnakerPluginInfo>()
.get { plugin.id }.isEqualTo(pluginId)
}
test("Response error results in empty plugin list") {
every { front50Service.listAll().execute() } returns Response.error(500, mockk(relaxed = true))
expectThat(subject.plugins).isEmpty()
}
test("Returns repository ID and URL") {
expectThat(subject.id).isEqualTo(repositoryName)
expectThat(subject.url).isEqualTo(front50Url)
}
}
private inner class Fixture {
val front50Service: Front50Service = mockk(relaxed = true)
val pluginId = "netflix.custom-stage"
val repositoryName = "front50"
val front50Url = URL("https://front50.com")
val subject = Front50UpdateRepository(
repositoryName,
front50Url,
SimpleFileDownloader(),
CompoundVerifier(),
front50Service
)
val plugin = SpinnakerPluginInfo()
val response: Response<Collection<SpinnakerPluginInfo>> = Response.success(Collections.singletonList(plugin))
init {
plugin.setReleases(listOf(SpinnakerPluginRelease(true)))
plugin.id = pluginId
}
}
}
| apache-2.0 | 58ef669830e02cdd2559aa5ab8a44a77 | 32.433333 | 113 | 0.74111 | 4.323276 | false | true | false | false |
EMResearch/EvoMaster | core/src/test/kotlin/org/evomaster/core/search/algorithms/onemax/ManipulatedOneMaxMutator.kt | 1 | 2169 | package org.evomaster.core.search.algorithms.onemax
import org.evomaster.core.search.EvaluatedIndividual
import org.evomaster.core.search.Individual
import org.evomaster.core.search.gene.Gene
import org.evomaster.core.search.service.mutator.MutatedGeneSpecification
import org.evomaster.core.search.service.mutator.Mutator
import kotlin.math.min
/**
* created by manzh on 2020-06-24
*/
class ManipulatedOneMaxMutator : Mutator<OneMaxIndividual>() {
var improve = false
override fun mutate(individual: EvaluatedIndividual<OneMaxIndividual>, targets: Set<Int>, mutatedGenes: MutatedGeneSpecification?): OneMaxIndividual {
return manipulate(individual, 0.25, improve = improve, mutatedGeneSpecification = mutatedGenes)
}
override fun genesToMutation(individual: OneMaxIndividual, evi: EvaluatedIndividual<OneMaxIndividual>, targets: Set<Int>): List<Gene> {
return individual.seeGenes(Individual.GeneFilter.ALL).filter { it.isMutable() }
}
override fun selectGenesToMutate(individual: OneMaxIndividual, evi: EvaluatedIndividual<OneMaxIndividual>, targets: Set<Int>, mutatedGenes: MutatedGeneSpecification?): List<Gene> {
return listOf()
}
override fun doesStructureMutation(evaluatedIndividual: EvaluatedIndividual<OneMaxIndividual>): Boolean = false
private fun manipulate(mutated: EvaluatedIndividual<OneMaxIndividual>, degree: Double, improve: Boolean, mutatedGeneSpecification: MutatedGeneSpecification?) : OneMaxIndividual{
val ind = mutated.individual.copy() as OneMaxIndividual
val index = if(improve)(0 until ind.n).firstOrNull{ind.getValue(it) < 1.0} else (0 until ind.n).filter{ind.getValue(it) >= 0.25}.run { if (isEmpty()) null else randomness.choose(this)}
index?:return ind
val previousValue = ind.getValue(index)
ind.setValue(index, if(improve) min(1.0, ind.getValue(index) + degree) else min(0.0, ind.getValue(index) - degree))
mutatedGeneSpecification?.addMutatedGene(isDb = false, isInit = false, valueBeforeMutation = previousValue.toString(), gene = ind.seeGenes()[index], localId = null, position = 0)
return ind
}
} | lgpl-3.0 | 421ff59318676608b8646927ee015169 | 47.222222 | 194 | 0.753804 | 4.355422 | false | false | false | false |
rohitsuratekar/NCBSinfo | app/src/main/java/com/rohitsuratekar/NCBSinfo/viewmodels/ConfirmTransportViewModel.kt | 1 | 7120 | package com.rohitsuratekar.NCBSinfo.viewmodels
import android.os.AsyncTask
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.rohitsuratekar.NCBSinfo.common.Constants
import com.rohitsuratekar.NCBSinfo.common.serverTimestamp
import com.rohitsuratekar.NCBSinfo.database.RouteData
import com.rohitsuratekar.NCBSinfo.database.TripData
import com.rohitsuratekar.NCBSinfo.di.Repository
import java.util.*
import kotlin.collections.HashMap
private const val TAG = "ConfirmTransport"
class ConfirmTransportViewModel : ViewModel() {
val error = MutableLiveData<Int>()
val success = MutableLiveData<Boolean>()
fun addTransport(
repository: Repository,
origin: String,
destination: String,
type: String,
frequency: List<Int>,
trips: List<String>,
force: Boolean
) {
AddNewTransport(repository, origin, destination, type, frequency, trips, object : OnNewRoute {
override fun conflict(int: Int) {
error.postValue(int)
}
override fun routeAdded() {
success.postValue(true)
}
}, force).execute()
}
class AddNewTransport(
private val repository: Repository, private val origin: String,
private val destination: String,
private val type: String,
private val frequency: List<Int>,
private val inputTrips: List<String>, private val listener: OnNewRoute,
private val force: Boolean
) :
AsyncTask<Void?, Void?, Void?>() {
private val timestamp = Calendar.getInstance().serverTimestamp()
override fun doInBackground(vararg params: Void?): Void? {
if ((repository.data().isRouteThere(origin, destination, type) == 0) or force) {
when {
frequency.sum() == 7 -> allDays()
(frequency.sum() == 6) and (frequency[0] == 0) -> weekDays()
(frequency.sum() == 2) and (frequency[0] == 1) and (frequency[6] == 1) -> weekEnd()
else -> specific()
}
} else {
listener.conflict(Constants.EDIT_ERROR_EXISTING_ROUTE)
}
return null
}
private fun checkOrCreateRoute(): RouteData {
val routeNo = repository.data().isRouteThere(origin, destination, type)
return if (routeNo == 0) {
val r = RouteData()
r.origin = origin
r.destination = destination
r.type = type
r.author = "User"
r.createdOn = timestamp
r.modifiedOn = timestamp
r.syncedOn = timestamp
r.favorite = "no"
val newNo = repository.data().addRoute(r)
Log.i(TAG, "New route is added")
repository.data().getRouteByNumber(newNo.toInt())
} else {
val r = repository.data().getRouteByNumber(routeNo)
repository.data().updateModifiedDate(r, timestamp)
r
}
}
private fun allDays() {
val r = checkOrCreateRoute()
repository.data().deleteTripsByRoute(r.routeID)
val t = TripData().apply {
routeID = r.routeID
day = Calendar.MONDAY
}
t.trips = inputTrips
repository.data().addTrips(t)
Log.i(TAG, "Route trips for ALL DAYS are updated")
listener.routeAdded()
}
private fun weekDays() {
val r = checkOrCreateRoute()
val tripList = repository.data().getTrips(r)
if (tripList.size == 1) {
Log.i(TAG, "Keeping Old trip for Sunday.")
val newTrip = TripData().apply {
routeID = r.routeID
day = Calendar.SUNDAY
trips = tripList[0].trips
}
repository.data().addTrips(newTrip)
} else {
for (t in tripList) {
if (t.day != Calendar.SUNDAY) {
repository.data().deleteTrip(t)
Log.i(TAG, "Old trip for week day deleted.")
}
}
}
val weekDayTrip = TripData().apply {
routeID = r.routeID
day = Calendar.MONDAY
}
weekDayTrip.trips = inputTrips
repository.data().addTrips(weekDayTrip)
Log.i(TAG, "WEEK DAYS trips added.")
listener.routeAdded()
}
private fun weekEnd() {
val r = checkOrCreateRoute()
val tripList = repository.data().getTrips(r)
for (t in tripList) {
if ((t.day == Calendar.SUNDAY) or (t.day == Calendar.SATURDAY)) {
repository.data().deleteTrip(t)
Log.i(TAG, "Old trip for weekend deleted.")
}
}
val newTrip = TripData().apply {
routeID = r.routeID
day = Calendar.SUNDAY
trips = inputTrips
}
repository.data().addTrips(newTrip)
Log.i(TAG, "New Sunday trips added")
newTrip.day = Calendar.SATURDAY
repository.data().addTrips(newTrip)
Log.i(TAG, "New Saturday trips added")
listener.routeAdded()
}
private fun specific() {
val dayList = mutableListOf(
Calendar.SUNDAY, Calendar.MONDAY, Calendar.TUESDAY,
Calendar.WEDNESDAY, Calendar.THURSDAY, Calendar.FRIDAY, Calendar.SATURDAY
)
val r = checkOrCreateRoute()
val tripList = repository.data().getTrips(r)
val map = HashMap<Int, TripData>()
for (t in tripList) {
map[t.day] = t
}
for (i in 0 until frequency.size) {
if (frequency[i] == 1) {
if (map.containsKey(dayList[i])) {
repository.data().deleteTrip(map[dayList[i]]!!)
Log.i(TAG, "Old day trip deleted")
}
}
}
val newTrip = TripData().apply {
routeID = r.routeID
trips = inputTrips
}
for (i in 0 until frequency.size) {
if (frequency[i] == 1) {
newTrip.day = dayList[i]
repository.data().addTrips(newTrip)
Log.i(TAG, "New day trip added")
}
}
listener.routeAdded()
}
}
interface OnNewRoute {
fun conflict(int: Int)
fun routeAdded()
}
} | mit | 3e91c0390d3ca2de689b12c1acfabcfa | 33.257426 | 103 | 0.501545 | 4.965132 | false | false | false | false |
savoirfairelinux/ring-client-android | ring-android/libjamiclient/src/main/kotlin/net/jami/services/HardwareService.kt | 1 | 8143 | /*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* Author: Thibault Wittemberg <[email protected]>
* Author: Adrien Béraud <[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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package net.jami.services
import io.reactivex.rxjava3.core.*
import io.reactivex.rxjava3.core.ObservableOnSubscribe
import io.reactivex.rxjava3.schedulers.Schedulers
import io.reactivex.rxjava3.subjects.BehaviorSubject
import io.reactivex.rxjava3.subjects.PublishSubject
import io.reactivex.rxjava3.subjects.Subject
import net.jami.model.Call.CallStatus
import net.jami.daemon.IntVect
import net.jami.daemon.UintVect
import net.jami.daemon.JamiService
import net.jami.daemon.StringMap
import net.jami.model.Conference
import net.jami.utils.Log
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
import kotlin.jvm.Synchronized
abstract class HardwareService(
private val mExecutor: ScheduledExecutorService,
val mPreferenceService: PreferencesService,
protected val mUiScheduler: Scheduler
) {
data class VideoEvent (
val callId: String? = null,
val start: Boolean = false,
val started: Boolean = false,
val w: Int = 0,
val h: Int = 0,
val rot: Int = 0
)
class BluetoothEvent (val connected: Boolean)
enum class AudioOutput {
INTERNAL, SPEAKERS, BLUETOOTH
}
class AudioState(val outputType: AudioOutput, val outputName: String? = null)
protected val videoEvents: Subject<VideoEvent> = PublishSubject.create()
protected val bluetoothEvents: Subject<BluetoothEvent> = PublishSubject.create()
protected val audioStateSubject: Subject<AudioState> = BehaviorSubject.createDefault(STATE_INTERNAL)
protected val connectivityEvents: Subject<Boolean> = BehaviorSubject.create()
fun getVideoEvents(): Observable<VideoEvent> {
return videoEvents
}
fun getBluetoothEvents(): Observable<BluetoothEvent> {
return bluetoothEvents
}
val audioState: Observable<AudioState>
get() = audioStateSubject
val connectivityState: Observable<Boolean>
get() = connectivityEvents
abstract fun initVideo(): Completable
abstract val isVideoAvailable: Boolean
abstract fun updateAudioState(state: CallStatus?, incomingCall: Boolean, isOngoingVideo: Boolean, isSpeakerOn: Boolean)
abstract fun closeAudioState()
abstract val isSpeakerphoneOn: Boolean
abstract fun toggleSpeakerphone(checked: Boolean)
abstract fun startRinging()
abstract fun stopRinging()
abstract fun abandonAudioFocus()
abstract fun decodingStarted(id: String, shmPath: String, width: Int, height: Int, isMixer: Boolean)
abstract fun decodingStopped(id: String, shmPath: String, isMixer: Boolean)
abstract fun hasInput(id: String): Boolean
abstract fun getCameraInfo(camId: String, formats: IntVect, sizes: UintVect, rates: UintVect)
abstract fun setParameters(camId: String, format: Int, width: Int, height: Int, rate: Int)
abstract fun startCapture(camId: String?)
abstract fun stopCapture(camId: String)
abstract fun hasMicrophone(): Boolean
abstract fun requestKeyFrame(camId: String)
abstract fun setBitrate(camId: String, bitrate: Int)
abstract fun addVideoSurface(id: String, holder: Any)
abstract fun updateVideoSurfaceId(currentId: String, newId: String)
abstract fun removeVideoSurface(id: String)
abstract fun addPreviewVideoSurface(holder: Any, conference: Conference?)
abstract fun updatePreviewVideoSurface(conference: Conference)
abstract fun removePreviewVideoSurface()
abstract fun switchInput(accountId:String, callId: String, setDefaultCamera: Boolean = false, screenCaptureSession: Any? = null)
abstract fun setPreviewSettings()
abstract fun hasCamera(): Boolean
abstract val cameraCount: Int
abstract val maxResolutions: Observable<Pair<Int?, Int?>>
abstract val isPreviewFromFrontCamera: Boolean
abstract fun shouldPlaySpeaker(): Boolean
abstract fun unregisterCameraDetectionCallback()
abstract fun startMediaHandler(mediaHandlerId: String?)
abstract fun stopMediaHandler()
fun connectivityChanged(isConnected: Boolean) {
Log.i(TAG, "connectivityChange() $isConnected")
connectivityEvents.onNext(isConnected)
mExecutor.execute { JamiService.connectivityChanged() }
}
protected fun switchInput(accountId:String, callId: String, uri: String) {
Log.i(TAG, "switchInput() $uri")
mExecutor.execute { JamiService.switchInput(accountId, callId, uri) }
}
fun setPreviewSettings(cameraMaps: Map<String, StringMap>) {
mExecutor.execute {
Log.i(TAG, "applySettings() thread running...")
for ((key, value) in cameraMaps) {
JamiService.applySettings(key, value)
}
}
}
fun startVideo(inputId: String, surface: Any, width: Int, height: Int): Long {
Log.i(TAG, "startVideo $inputId ${width}x$height")
val inputWindow = JamiService.acquireNativeWindow(surface)
if (inputWindow == 0L) {
return inputWindow
}
JamiService.setNativeWindowGeometry(inputWindow, width, height)
JamiService.registerVideoCallback(inputId, inputWindow)
return inputWindow
}
fun stopVideo(inputId: String, inputWindow: Long) {
Log.i(TAG, "stopVideo $inputId $inputWindow")
if (inputWindow == 0L) {
return
}
JamiService.unregisterVideoCallback(inputId, inputWindow)
JamiService.releaseNativeWindow(inputWindow)
}
abstract fun setDeviceOrientation(rotation: Int)
protected abstract val videoDevices: List<String>
private var logs: Observable<String>? = null
private var logEmitter: Emitter<String>? = null
@get:Synchronized
val isLogging: Boolean
get() = logs != null
@Synchronized
fun startLogs(): Observable<String> {
return logs ?: Observable.create(ObservableOnSubscribe { emitter: ObservableEmitter<String> ->
logEmitter = emitter
JamiService.monitor(true)
emitter.setCancellable {
synchronized(this@HardwareService) {
JamiService.monitor(false)
logEmitter = null
logs = null
}
}
} as ObservableOnSubscribe<String>)
.observeOn(Schedulers.io())
.scan(StringBuffer(1024)) { sb: StringBuffer, message: String -> sb.append(message).append('\n') }
.throttleLatest(500, TimeUnit.MILLISECONDS)
.map { obj: StringBuffer -> obj.toString() }
.replay(1)
.autoConnect()
.apply { logs = this }
}
@Synchronized
fun stopLogs() {
logEmitter?.let { emitter ->
Log.w(TAG, "stopLogs JamiService.monitor(false)")
JamiService.monitor(false)
emitter.onComplete()
logEmitter = null
logs = null
}
}
fun logMessage(message: String) {
if (message.isNotEmpty())
logEmitter?.onNext(message)
}
companion object {
private val TAG = HardwareService::class.simpleName!!
val STATE_SPEAKERS = AudioState(AudioOutput.SPEAKERS)
val STATE_INTERNAL = AudioState(AudioOutput.INTERNAL)
}
} | gpl-3.0 | 6801bca817a7d79ba9551d642375ab3e | 38.149038 | 132 | 0.695652 | 4.468716 | false | false | false | false |
firebase/quickstart-android | auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/PhoneAuthFragment.kt | 1 | 13716 | package com.google.firebase.quickstart.auth.kotlin
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.google.android.material.snackbar.Snackbar
import com.google.firebase.FirebaseException
import com.google.firebase.FirebaseTooManyRequestsException
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.PhoneAuthCredential
import com.google.firebase.auth.PhoneAuthOptions
import com.google.firebase.auth.PhoneAuthProvider
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import com.google.firebase.quickstart.auth.R
import com.google.firebase.quickstart.auth.databinding.FragmentPhoneAuthBinding
import java.util.concurrent.TimeUnit
class PhoneAuthFragment : Fragment() {
private lateinit var auth: FirebaseAuth
private var _binding: FragmentPhoneAuthBinding? = null
private val binding: FragmentPhoneAuthBinding
get() = _binding!!
private var verificationInProgress = false
private var storedVerificationId: String? = ""
private lateinit var resendToken: PhoneAuthProvider.ForceResendingToken
private lateinit var callbacks: PhoneAuthProvider.OnVerificationStateChangedCallbacks
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = FragmentPhoneAuthBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Restore instance state
savedInstanceState?.let { onViewStateRestored(it) }
// Assign click listeners
binding.buttonStartVerification.setOnClickListener {
if (!validatePhoneNumber()) {
return@setOnClickListener
}
startPhoneNumberVerification(binding.fieldPhoneNumber.text.toString())
}
binding.buttonVerifyPhone.setOnClickListener {
val code = binding.fieldVerificationCode.text.toString()
if (TextUtils.isEmpty(code)) {
binding.fieldVerificationCode.error = "Cannot be empty."
return@setOnClickListener
}
verifyPhoneNumberWithCode(storedVerificationId, code)
}
binding.buttonResend.setOnClickListener {
if (!validatePhoneNumber()) {
return@setOnClickListener
}
resendVerificationCode(binding.fieldPhoneNumber.text.toString(), resendToken)
}
binding.signOutButton.setOnClickListener { signOut() }
// Initialize Firebase Auth
auth = Firebase.auth
// Initialize phone auth callbacks
callbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
override fun onVerificationCompleted(credential: PhoneAuthCredential) {
// This callback will be invoked in two situations:
// 1 - Instant verification. In some cases the phone number can be instantly
// verified without needing to send or enter a verification code.
// 2 - Auto-retrieval. On some devices Google Play services can automatically
// detect the incoming verification SMS and perform verification without
// user action.
Log.d(TAG, "onVerificationCompleted:$credential")
verificationInProgress = false
// Update the UI and attempt sign in with the phone credential
updateUI(STATE_VERIFY_SUCCESS, credential)
signInWithPhoneAuthCredential(credential)
}
override fun onVerificationFailed(e: FirebaseException) {
// This callback is invoked in an invalid request for verification is made,
// for instance if the the phone number format is not valid.
Log.w(TAG, "onVerificationFailed", e)
verificationInProgress = false
if (e is FirebaseAuthInvalidCredentialsException) {
// Invalid request
binding.fieldPhoneNumber.error = "Invalid phone number."
} else if (e is FirebaseTooManyRequestsException) {
// The SMS quota for the project has been exceeded
Snackbar.make(view, "Quota exceeded.",
Snackbar.LENGTH_SHORT).show()
}
// Show a message and update the UI
updateUI(STATE_VERIFY_FAILED)
}
override fun onCodeSent(
verificationId: String,
token: PhoneAuthProvider.ForceResendingToken
) {
// The SMS verification code has been sent to the provided phone number, we
// now need to ask the user to enter the code and then construct a credential
// by combining the code with a verification ID.
Log.d(TAG, "onCodeSent:$verificationId")
// Save verification ID and resending token so we can use them later
storedVerificationId = verificationId
resendToken = token
// Update UI
updateUI(STATE_CODE_SENT)
}
}
}
override fun onStart() {
super.onStart()
// Check if user is signed in (non-null) and update UI accordingly.
val currentUser = auth.currentUser
updateUI(currentUser)
if (verificationInProgress && validatePhoneNumber()) {
startPhoneNumberVerification(binding.fieldPhoneNumber.text.toString())
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean(KEY_VERIFY_IN_PROGRESS, verificationInProgress)
}
override fun onViewStateRestored(savedInstanceState: Bundle?) {
super.onViewStateRestored(savedInstanceState)
savedInstanceState?.let { savedState ->
verificationInProgress = savedState.getBoolean(KEY_VERIFY_IN_PROGRESS)
}
}
private fun startPhoneNumberVerification(phoneNumber: String) {
val options = PhoneAuthOptions.newBuilder(auth)
.setPhoneNumber(phoneNumber) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(requireActivity()) // Activity (for callback binding)
.setCallbacks(callbacks) // OnVerificationStateChangedCallbacks
.build()
PhoneAuthProvider.verifyPhoneNumber(options)
verificationInProgress = true
}
private fun verifyPhoneNumberWithCode(verificationId: String?, code: String) {
val credential = PhoneAuthProvider.getCredential(verificationId!!, code)
signInWithPhoneAuthCredential(credential)
}
private fun resendVerificationCode(
phoneNumber: String,
token: PhoneAuthProvider.ForceResendingToken?
) {
val optionsBuilder = PhoneAuthOptions.newBuilder(auth)
.setPhoneNumber(phoneNumber) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(requireActivity()) // Activity (for callback binding)
.setCallbacks(callbacks) // OnVerificationStateChangedCallbacks
if (token != null) {
optionsBuilder.setForceResendingToken(token) // callback's ForceResendingToken
}
PhoneAuthProvider.verifyPhoneNumber(optionsBuilder.build())
}
private fun signInWithPhoneAuthCredential(credential: PhoneAuthCredential) {
auth.signInWithCredential(credential)
.addOnCompleteListener(requireActivity()) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success")
val user = task.result?.user
updateUI(STATE_SIGNIN_SUCCESS, user)
} else {
// Sign in failed, display a message and update the UI
Log.w(TAG, "signInWithCredential:failure", task.exception)
if (task.exception is FirebaseAuthInvalidCredentialsException) {
// The verification code entered was invalid
binding.fieldVerificationCode.error = "Invalid code."
}
// Update UI
updateUI(STATE_SIGNIN_FAILED)
}
}
}
private fun signOut() {
auth.signOut()
updateUI(STATE_INITIALIZED)
}
private fun updateUI(user: FirebaseUser?) {
if (user != null) {
updateUI(STATE_SIGNIN_SUCCESS, user)
} else {
updateUI(STATE_INITIALIZED)
}
}
private fun updateUI(uiState: Int, cred: PhoneAuthCredential) {
updateUI(uiState, null, cred)
}
private fun updateUI(
uiState: Int,
user: FirebaseUser? = auth.currentUser,
cred: PhoneAuthCredential? = null
) {
when (uiState) {
STATE_INITIALIZED -> {
// Initialized state, show only the phone number field and start button
enableViews(binding.buttonStartVerification, binding.fieldPhoneNumber)
disableViews(binding.buttonVerifyPhone, binding.buttonResend, binding.fieldVerificationCode)
binding.detail.text = null
}
STATE_CODE_SENT -> {
// Code sent state, show the verification field, the
enableViews(binding.buttonVerifyPhone, binding.buttonResend,
binding.fieldPhoneNumber, binding.fieldVerificationCode)
disableViews(binding.buttonStartVerification)
binding.detail.setText(R.string.status_code_sent)
}
STATE_VERIFY_FAILED -> {
// Verification has failed, show all options
enableViews(binding.buttonStartVerification, binding.buttonVerifyPhone,
binding.buttonResend, binding.fieldPhoneNumber,
binding.fieldVerificationCode)
binding.detail.setText(R.string.status_verification_failed)
}
STATE_VERIFY_SUCCESS -> {
// Verification has succeeded, proceed to firebase sign in
disableViews(binding.buttonStartVerification, binding.buttonVerifyPhone,
binding.buttonResend, binding.fieldPhoneNumber,
binding.fieldVerificationCode)
binding.detail.setText(R.string.status_verification_succeeded)
// Set the verification text based on the credential
if (cred != null) {
if (cred.smsCode != null) {
binding.fieldVerificationCode.setText(cred.smsCode)
} else {
binding.fieldVerificationCode.setText(R.string.instant_validation)
}
}
}
STATE_SIGNIN_FAILED ->
// No-op, handled by sign-in check
binding.detail.setText(R.string.status_sign_in_failed)
STATE_SIGNIN_SUCCESS -> {
}
} // Np-op, handled by sign-in check
if (user == null) {
// Signed out
binding.phoneAuthFields.visibility = View.VISIBLE
binding.signOutButton.visibility = View.GONE
binding.status.setText(R.string.signed_out)
} else {
// Signed in
binding.phoneAuthFields.visibility = View.GONE
binding.signOutButton.visibility = View.VISIBLE
enableViews(binding.fieldPhoneNumber, binding.fieldVerificationCode)
binding.fieldPhoneNumber.text = null
binding.fieldVerificationCode.text = null
binding.status.setText(R.string.signed_in)
binding.detail.text = getString(R.string.firebase_status_fmt, user.uid)
}
}
private fun validatePhoneNumber(): Boolean {
val phoneNumber = binding.fieldPhoneNumber.text.toString()
if (TextUtils.isEmpty(phoneNumber)) {
binding.fieldPhoneNumber.error = "Invalid phone number."
return false
}
return true
}
private fun enableViews(vararg views: View) {
for (v in views) {
v.isEnabled = true
}
}
private fun disableViews(vararg views: View) {
for (v in views) {
v.isEnabled = false
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
companion object {
private const val TAG = "PhoneAuthFragment"
private const val KEY_VERIFY_IN_PROGRESS = "key_verify_in_progress"
private const val STATE_INITIALIZED = 1
private const val STATE_VERIFY_FAILED = 3
private const val STATE_VERIFY_SUCCESS = 4
private const val STATE_CODE_SENT = 2
private const val STATE_SIGNIN_FAILED = 5
private const val STATE_SIGNIN_SUCCESS = 6
}
}
| apache-2.0 | bfc5d536ed2714332ff9a694892a2c80 | 40.438066 | 115 | 0.622631 | 5.312161 | false | false | false | false |
Szewek/Minecraft-Flux | src/main/java/szewek/mcflux/blocks/BlockWET.kt | 1 | 2522 | package szewek.mcflux.blocks
import net.minecraft.block.properties.PropertyDirection
import net.minecraft.block.properties.PropertyInteger
import net.minecraft.block.state.BlockStateContainer
import net.minecraft.block.state.IBlockState
import net.minecraft.entity.EntityLivingBase
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.item.ItemStack
import net.minecraft.util.EnumFacing
import net.minecraft.util.EnumHand
import net.minecraft.util.Mirror
import net.minecraft.util.Rotation
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
import szewek.fl.block.BlockContainerModeled
import szewek.mcflux.tileentities.TileEntityWET
class BlockWET : BlockContainerModeled() {
init {
setHardness(1f)
}
override fun createNewTileEntity(w: World, meta: Int) = TileEntityWET()
override fun getStateForPlacement(w: World, pos: BlockPos, facing: EnumFacing, hitX: Float, hitY: Float, hitZ: Float, meta: Int, placer: EntityLivingBase, hand: EnumHand?): IBlockState {
return defaultState.withProperty(FACING, EnumFacing.getDirectionFromEntityLiving(pos, placer)).withProperty(MODE, 0)
}
override fun onBlockPlacedBy(w: World, pos: BlockPos?, state: IBlockState, placer: EntityLivingBase?, stack: ItemStack?) {
w.setBlockState(pos!!, state.withProperty(FACING, EnumFacing.getDirectionFromEntityLiving(pos, placer!!)), 2)
}
override fun onBlockActivated(w: World?, bp: BlockPos?, ibs: IBlockState?, p: EntityPlayer?, h: EnumHand?, f: EnumFacing?, x: Float, y: Float, z: Float): Boolean {
val b = h == EnumHand.MAIN_HAND && p!!.getHeldItem(h).isEmpty
if (b && !w!!.isRemote)
w.setBlockState(bp!!, ibs!!.cycleProperty(MODE), 3)
return b
}
override fun getStateFromMeta(meta: Int): IBlockState {
return defaultState.withProperty(MODE, meta % 2).withProperty(FACING, EnumFacing.VALUES[meta / 2 % 6])
}
override fun getMetaFromState(state: IBlockState): Int {
return state.getValue(MODE) + 2 * state.getValue(FACING).index
}
override fun withRotation(state: IBlockState, rot: Rotation): IBlockState {
return state.withProperty(FACING, rot.rotate(state.getValue(FACING)))
}
override fun withMirror(state: IBlockState, mir: Mirror): IBlockState {
return state.withRotation(mir.toRotation(state.getValue(FACING)))
}
override fun createBlockState(): BlockStateContainer {
return BlockStateContainer(this, FACING, MODE)
}
companion object {
private val FACING = PropertyDirection.create("f")
val MODE = PropertyInteger.create("m", 0, 1)
}
}
| mit | 12b3a5b18b86cad466c6008d9bef187d | 37.8 | 187 | 0.773592 | 3.775449 | false | false | false | false |
xwiki-contrib/android-authenticator | app/src/main/java/org/xwiki/android/sync/contactdb/ContactManager.kt | 1 | 12045 | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.android.sync.contactdb
import android.content.ContentResolver
import android.content.ContentUris
import android.content.Context
import android.net.Uri
import android.provider.ContactsContract
import android.provider.ContactsContract.RawContacts
import android.util.Log
import org.xwiki.android.sync.ACCOUNT_TYPE
import org.xwiki.android.sync.appContext
import org.xwiki.android.sync.bean.XWikiUserFull
import org.xwiki.android.sync.dataSaverModeEnabled
import org.xwiki.android.sync.resolveApiManager
import org.xwiki.android.sync.rest.BaseApiManager
import retrofit2.HttpException
import rx.Observable
import rx.Observer
import rx.functions.Action1
import java.io.IOException
import java.util.*
/**
* Class for managing contacts sync related mOperations.
*
* @version $Id: be8481217cc0fc4ab1ff4ab9e6f1b9d1fb4f5fc3 $
*/
class ContactManager(
private val apiManager: BaseApiManager
) {
private val TAG = "ContactManager"
companion object {
/**
* Subscribe to observable to get [XWikiUserFull] objects and save locally.
*
* @param context The context of Authenticator Activity
* @param account The username for the account
* @param observable Will be used to subscribe to get stream of users
*
* @since 0.4
*/
suspend fun updateContacts(
context: Context,
account: UserAccount,
observable: Observable<XWikiUserFull>
) {
val apiManager = resolveApiManager(account)
val contactManager = ContactManager(apiManager)
val resolver = context.contentResolver
val batchOperation = BatchOperation(resolver)
val localUserMaps = contactManager.getAllContactsIdMap(resolver, account.accountName)
observable.subscribe(
object : Observer<XWikiUserFull> {
override fun onCompleted() {
for (id in localUserMaps.keys) {
val rawId = localUserMaps[id]
if (batchOperation.size() >= 100) {
batchOperation.execute()
}
}
batchOperation.execute()
}
override fun onError(e: Throwable) {
try {
val asHttpException = e as HttpException
if (asHttpException.code() == 401) {//Unauthorized
apiManager.xWikiHttp.relogin(
context
)
}
} catch (e1: ClassCastException) {
Log.e(contactManager.TAG, "Can't synchronize users", e)
}
}
override fun onNext(xWikiUserFull: XWikiUserFull) {
val operationList = xWikiUserFull.toContentProviderOperations(
resolver,
account.accountName
)
for (operation in operationList) {
batchOperation.add(operation)
}
if (batchOperation.size() >= 100) {
batchOperation.execute()
}
if (!appContext.dataSaverModeEnabled) {
contactManager.updateAvatar(
resolver,
contactManager.lookupRawContact(resolver, xWikiUserFull.id),
xWikiUserFull
)
}
}
}
)
}
}
/**
* Initiate procedure of contact avatar updating
*
* @param contentResolver Resolver to get contact photo file
* @param rawId UserAccount row id in local store
* @param xwikiUser Xwiki user info to find avatar
*
* @see .writeDisplayPhoto
* @since 0.4
*/
fun updateAvatar(
contentResolver: ContentResolver,
rawId: Long,
xwikiUser: XWikiUserFull
) {
if (xwikiUser.avatar.isNullOrEmpty()) {
Log.e(TAG, "Avatar url is null or empty")
return
}
val gettingAvatarObservable = apiManager.xWikiPhotosManager
.downloadAvatar(
xwikiUser.pageName,
xwikiUser.avatar
)
if (gettingAvatarObservable != null) {
gettingAvatarObservable.subscribe(
Action1<ByteArray> { bytes ->
if (bytes != null) {
try {
writeDisplayPhoto(contentResolver, rawId, bytes)
} catch (e: IOException) {
Log.e(
TAG,
"Can't update avatar of user",
e
)
}
}
},
Action1<Throwable> { throwable ->
Log.e(
TAG,
"Can't update avatar of user",
throwable
)
}
)
}
}
/**
* Write photo of contact from bytes to file
*
* @param contentResolver Will be used to get file descriptor of contact
* @param rawContactId Contact id
* @param photo Photo bytes which can be get from server
*
* @see ContentResolver.openAssetFileDescriptor
* @see Uri.withAppendedPath
* @since 0.4
*/
@Throws(IOException::class)
private fun writeDisplayPhoto(
contentResolver: ContentResolver,
rawContactId: Long,
photo: ByteArray?
) {
val rawContactPhotoUri = Uri.withAppendedPath(
ContentUris.withAppendedId(
RawContacts.CONTENT_URI,
rawContactId
),
RawContacts.DisplayPhoto.CONTENT_DIRECTORY
)
val fd = contentResolver.openAssetFileDescriptor(rawContactPhotoUri, "rw")
val os = fd?.createOutputStream()
os?.write(photo)
os?.close()
fd?.close()
}
/**
* Read database and get maps with id's.
*
* @param resolver Resolver to find users
* @param accountName Account to get data from resolver
* @return Map with pairs **server_id** to **user_id**
*
* @since 0.4
*/
private fun getAllContactsIdMap(
resolver: ContentResolver,
accountName: String
): HashMap<String, Long> {
val allMaps = HashMap<String, Long>()
val c = resolver.query(
AllQuery.CONTENT_URI,
AllQuery.PROJECTION,
AllQuery.SELECTION,
arrayOf(accountName), null
) ?: error("Can't get all contacts for $accountName (returned cursor is null)")
c.use { cursor ->
while (cursor.moveToNext()) {
val serverId = cursor.getString(AllQuery.COLUMN_SERVER_ID)
val rawId = cursor.getLong(AllQuery.COLUMN_RAW_CONTACT_ID)
allMaps[serverId] = rawId
}
}
return allMaps
}
/**
* Returns the RawContact id for a sample SyncAdapter contact, or 0 if the
* sample SyncAdapter user isn't found.
*
* @param resolver the content resolver to use
* @param serverContactId the sample SyncAdapter user ID to lookup
* @return the RawContact id, or 0 if not found
*
* @since 0.4
*/
private fun lookupRawContact(resolver: ContentResolver, serverContactId: String): Long {
var rawContactId: Long = 0
val c = resolver.query(
UserIdQuery.CONTENT_URI,
UserIdQuery.PROJECTION,
UserIdQuery.SELECTION,
arrayOf(serverContactId), null
)
c.use { cursor ->
if (cursor != null && cursor.moveToFirst()) {
rawContactId = cursor.getLong(UserIdQuery.COLUMN_RAW_CONTACT_ID)
}
}
return rawContactId
}
/**
* Constants for a query to find a contact given a sample SyncAdapter user
* ID.
*
* @since 0.3.0
*/
private object UserIdQuery {
/**
* Projection of columns to use in
* [ContentResolver.query]
*
* @see ContentResolver.query
* @see ContentResolver.query
* @see ContentResolver.query
*/
internal val PROJECTION = arrayOf(RawContacts._ID, RawContacts.CONTACT_ID)
/**
* Column which contains user raw id
*/
internal val COLUMN_RAW_CONTACT_ID = 0
/**
* Will be used to set uri path in
* [ContentResolver.query] and similar
*
* @see ContentResolver.query
* @see ContentResolver.query
* @see ContentResolver.query
*/
internal val CONTENT_URI = RawContacts.CONTENT_URI
/**
* Selection for getting user by type [Constants.ACCOUNT_TYPE] and source id
*/
internal val SELECTION = (
RawContacts.ACCOUNT_TYPE + "='"
+ ACCOUNT_TYPE + "' AND "
+ RawContacts.SOURCE_ID + "=?")
}
/**
* Nobody must not create instance of this class
*/
/**
* Getting all rows id's helper class
*
* @since 0.3.0
*/
private object AllQuery {
/**
* Projection of columns to use in
* [ContentResolver.query]
*
* @see ContentResolver.query
* @see ContentResolver.query
* @see ContentResolver.query
*/
internal val PROJECTION = arrayOf(RawContacts._ID, RawContacts.SOURCE_ID)
/**
* Column which contains raw id
*/
internal val COLUMN_RAW_CONTACT_ID = 0
/**
* Column which contains server id
*/
internal val COLUMN_SERVER_ID = 1
/**
* Will be used to set uri path in
* [ContentResolver.query] and similar
*
* @see ContentResolver.query
* @see ContentResolver.query
* @see ContentResolver.query
*/
internal val CONTENT_URI = RawContacts.CONTENT_URI
.buildUpon()
.appendQueryParameter(
ContactsContract.CALLER_IS_SYNCADAPTER,
"true"
)
.build()
/**
* Selection for getting data by [Constants.ACCOUNT_TYPE] and account name
*/
internal val SELECTION = (
RawContacts.ACCOUNT_TYPE + "='"
+ ACCOUNT_TYPE + "' AND "
+ RawContacts.ACCOUNT_NAME + "=?")
}
/**
* Nobody must not create instance of this class
*/
}
| lgpl-2.1 | f2a54381842fd4d651df4958df16e88e | 31.820163 | 97 | 0.540971 | 5.097334 | false | false | false | false |
duftler/orca | orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/messages.kt | 2 | 14392 | /*
* Copyright 2017 Netflix, 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.netflix.spinnaker.orca.q
import com.fasterxml.jackson.annotation.JsonTypeName
import com.netflix.spinnaker.orca.ExecutionStatus
import com.netflix.spinnaker.orca.Task
import com.netflix.spinnaker.orca.pipeline.model.Execution
import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType
import com.netflix.spinnaker.orca.pipeline.model.Stage
import com.netflix.spinnaker.orca.pipeline.model.SyntheticStageOwner
import com.netflix.spinnaker.orca.pipeline.model.SyntheticStageOwner.STAGE_BEFORE
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.q.Attribute
import com.netflix.spinnaker.q.Message
import java.time.Duration
/**
* Messages used internally by the queueing system.
*/
interface ApplicationAware {
val application: String
}
interface ExecutionLevel : ApplicationAware {
val executionType: ExecutionType
val executionId: String
}
interface StageLevel : ExecutionLevel {
val stageId: String
}
interface TaskLevel : StageLevel {
val taskId: String
}
@JsonTypeName("startTask")
data class StartTask(
override val executionType: ExecutionType,
override val executionId: String,
override val application: String,
override val stageId: String,
override val taskId: String
) : Message(), TaskLevel {
constructor(source: ExecutionLevel, stageId: String, taskId: String) :
this(source.executionType, source.executionId, source.application, stageId, taskId)
constructor(source: StageLevel, taskId: String) :
this(source, source.stageId, taskId)
constructor(source: Stage, taskId: String) :
this(source.execution.type, source.execution.id, source.execution.application, source.id, taskId)
constructor(source: Stage, task: com.netflix.spinnaker.orca.pipeline.model.Task) :
this(source.execution.type, source.execution.id, source.execution.application, source.id, task.id)
}
@JsonTypeName("completeTask")
data class CompleteTask(
override val executionType: ExecutionType,
override val executionId: String,
override val application: String,
override val stageId: String,
override val taskId: String,
val status: ExecutionStatus,
val originalStatus: ExecutionStatus?
) : Message(), TaskLevel {
constructor(source: TaskLevel, status: ExecutionStatus) :
this(source, status, status)
constructor(source: TaskLevel, status: ExecutionStatus, originalStatus: ExecutionStatus) :
this(
source.executionType,
source.executionId,
source.application,
source.stageId,
source.taskId,
status,
originalStatus
)
}
@JsonTypeName("pauseTask")
data class PauseTask(
override val executionType: ExecutionType,
override val executionId: String,
override val application: String,
override val stageId: String,
override val taskId: String
) : Message(), TaskLevel {
constructor(message: TaskLevel) :
this(message.executionType, message.executionId, message.application, message.stageId, message.taskId)
}
@JsonTypeName("resumeTask")
data class ResumeTask(
override val executionType: ExecutionType,
override val executionId: String,
override val application: String,
override val stageId: String,
override val taskId: String
) : Message(), TaskLevel {
constructor(message: StageLevel, taskId: String) :
this(message.executionType, message.executionId, message.application, message.stageId, taskId)
}
@JsonTypeName("runTask")
data class RunTask(
override val executionType: ExecutionType,
override val executionId: String,
override val application: String,
override val stageId: String,
override val taskId: String,
val taskType: Class<out Task>
) : Message(), TaskLevel {
override val ackTimeoutMs = Duration.ofMinutes(10).toMillis()
constructor(message: StageLevel, taskId: String, taskType: Class<out Task>) :
this(message.executionType, message.executionId, message.application, message.stageId, taskId, taskType)
constructor(message: TaskLevel, taskType: Class<out Task>) :
this(message.executionType, message.executionId, message.application, message.stageId, message.taskId, taskType)
constructor(source: ExecutionLevel, stageId: String, taskId: String, taskType: Class<out Task>) :
this(source.executionType, source.executionId, source.application, stageId, taskId, taskType)
}
@JsonTypeName("startStage")
data class StartStage(
override val executionType: ExecutionType,
override val executionId: String,
override val application: String,
override val stageId: String
) : Message(), StageLevel {
constructor(source: ExecutionLevel, stageId: String) :
this(source.executionType, source.executionId, source.application, stageId)
constructor(source: StageLevel) :
this(source, source.stageId)
constructor(source: Stage) :
this(source.execution.type, source.execution.id, source.execution.application, source.id)
}
@JsonTypeName("continueParentStage")
data class ContinueParentStage(
override val executionType: ExecutionType,
override val executionId: String,
override val application: String,
override val stageId: String,
/**
* The phase that just completed, either before or after stages.
*/
val phase: SyntheticStageOwner = STAGE_BEFORE
) : Message(), StageLevel {
constructor(source: StageLevel, phase: SyntheticStageOwner) :
this(source.executionType, source.executionId, source.application, source.stageId, phase)
constructor(source: Stage, phase: SyntheticStageOwner) :
this(source.execution.type, source.execution.id, source.execution.application, source.id, phase)
}
@JsonTypeName("completeStage")
data class CompleteStage(
override val executionType: ExecutionType,
override val executionId: String,
override val application: String,
override val stageId: String
) : Message(), StageLevel {
constructor(source: ExecutionLevel, stageId: String) :
this(source.executionType, source.executionId, source.application, stageId)
constructor(source: StageLevel) :
this(source.executionType, source.executionId, source.application, source.stageId)
constructor(source: Stage) :
this(source.execution.type, source.execution.id, source.execution.application, source.id)
}
@JsonTypeName("skipStage")
data class SkipStage(
override val executionType: ExecutionType,
override val executionId: String,
override val application: String,
override val stageId: String
) : Message(), StageLevel {
constructor(source: StageLevel) :
this(source.executionType, source.executionId, source.application, source.stageId)
constructor(source: Stage) :
this(source.execution.type, source.execution.id, source.execution.application, source.id)
}
@JsonTypeName("abortStage")
data class AbortStage(
override val executionType: ExecutionType,
override val executionId: String,
override val application: String,
override val stageId: String
) : Message(), StageLevel {
constructor(source: StageLevel) :
this(source.executionType, source.executionId, source.application, source.stageId)
constructor(source: Stage) :
this(source.execution.type, source.execution.id, source.execution.application, source.id)
}
@JsonTypeName("pauseStage")
data class PauseStage(
override val executionType: ExecutionType,
override val executionId: String,
override val application: String,
override val stageId: String
) : Message(), StageLevel {
constructor(source: StageLevel) :
this(source, source.stageId)
constructor(source: ExecutionLevel, stageId: String) :
this(source.executionType, source.executionId, source.application, stageId)
}
@JsonTypeName("restartStage")
data class RestartStage(
override val executionType: ExecutionType,
override val executionId: String,
override val application: String,
override val stageId: String,
val user: String?
) : Message(), StageLevel {
constructor(source: Execution, stageId: String, user: String?) :
this(source.type, source.id, source.application, stageId, user)
constructor(stage: Stage, user: String?) :
this(stage.execution.type, stage.execution.id, stage.execution.application, stage.id, user)
}
@JsonTypeName("resumeStage")
data class ResumeStage(
override val executionType: ExecutionType,
override val executionId: String,
override val application: String,
override val stageId: String
) : Message(), StageLevel {
constructor(source: ExecutionLevel, stageId: String) :
this(source.executionType, source.executionId, source.application, stageId)
constructor(source: Stage) :
this(source.execution.type, source.execution.id, source.execution.application, source.id)
}
@JsonTypeName("cancelStage")
data class CancelStage(
override val executionType: ExecutionType,
override val executionId: String,
override val application: String,
override val stageId: String
) : Message(), StageLevel {
constructor(source: StageLevel) :
this(source.executionType, source.executionId, source.application, source.stageId)
constructor(stage: Stage) :
this(stage.execution.type, stage.execution.id, stage.execution.application, stage.id)
}
@JsonTypeName("startExecution")
data class StartExecution(
override val executionType: ExecutionType,
override val executionId: String,
override val application: String
) : Message(), ExecutionLevel {
constructor(source: Execution) :
this(source.type, source.id, source.application)
}
@JsonTypeName("rescheduleExecution")
data class RescheduleExecution(
override val executionType: ExecutionType,
override val executionId: String,
override val application: String
) : Message(), ExecutionLevel {
constructor(source: Execution) :
this(source.type, source.id, source.application)
}
@JsonTypeName("completeExecution")
data class CompleteExecution(
override val executionType: ExecutionType,
override val executionId: String,
override val application: String
) : Message(), ExecutionLevel {
constructor(source: ExecutionLevel) :
this(source.executionType, source.executionId, source.application)
constructor(source: Execution) :
this(source.type, source.id, source.application)
}
@JsonTypeName("resumeExecution")
data class ResumeExecution(
override val executionType: ExecutionType,
override val executionId: String,
override val application: String
) : Message(), ExecutionLevel {
constructor(source: Execution) :
this(source.type, source.id, source.application)
}
@JsonTypeName("cancelExecution")
data class CancelExecution(
override val executionType: ExecutionType,
override val executionId: String,
override val application: String,
val user: String?,
val reason: String?
) : Message(), ExecutionLevel {
constructor(source: Execution, user: String?, reason: String?) :
this(source.type, source.id, source.application, user, reason)
constructor(source: Execution) :
this(source.type, source.id, source.application, null, null)
constructor(source: ExecutionLevel) :
this(source.executionType, source.executionId, source.application, null, null)
}
@JsonTypeName("startWaitingExecutions")
data class StartWaitingExecutions(
val pipelineConfigId: String,
val purgeQueue: Boolean = false
) : Message()
/**
* Fatal errors in processing the execution configuration.
*/
sealed class ConfigurationError : Message(), ExecutionLevel
/**
* Execution id was not found in the [ExecutionRepository].
*/
@JsonTypeName("invalidExecutionId")
data class InvalidExecutionId(
override val executionType: ExecutionType,
override val executionId: String,
override val application: String
) : ConfigurationError() {
constructor(source: ExecutionLevel) :
this(source.executionType, source.executionId, source.application)
}
/**
* Stage id was not found in the execution.
*/
@JsonTypeName("invalidStageId")
data class InvalidStageId(
override val executionType: ExecutionType,
override val executionId: String,
override val application: String,
override val stageId: String
) : ConfigurationError(), StageLevel {
constructor(source: StageLevel) :
this(source.executionType, source.executionId, source.application, source.stageId)
}
/**
* Task id was not found in the stage.
*/
@JsonTypeName("invalidTaskId")
data class InvalidTaskId(
override val executionType: ExecutionType,
override val executionId: String,
override val application: String,
override val stageId: String,
override val taskId: String
) : ConfigurationError(), TaskLevel {
constructor(source: TaskLevel) :
this(source.executionType, source.executionId, source.application, source.stageId, source.taskId)
}
/**
* No such [Task] class.
*/
@JsonTypeName("invalidTaskType")
data class InvalidTaskType(
override val executionType: ExecutionType,
override val executionId: String,
override val application: String,
override val stageId: String,
val className: String
) : ConfigurationError(), StageLevel {
constructor(source: StageLevel, className: String) :
this(source.executionType, source.executionId, source.application, source.stageId, className)
}
@JsonTypeName("noDownstreamTasks")
data class NoDownstreamTasks(
override val executionType: ExecutionType,
override val executionId: String,
override val application: String,
override val stageId: String,
override val taskId: String
) : ConfigurationError(), TaskLevel {
constructor(source: TaskLevel) :
this(source.executionType, source.executionId, source.application, source.stageId, source.taskId)
}
@Deprecated("Kept only to support old messages on the queue without having to do a migration")
@JsonTypeName("totalThrottleTime")
data class TotalThrottleTimeAttribute(var totalThrottleTimeMs: Long = 0) : Attribute {
fun add(throttleTimeMs: Long) {
this.totalThrottleTimeMs += throttleTimeMs
}
}
| apache-2.0 | c9cdea2beab083985fdd5e74391b5310 | 32.704918 | 116 | 0.766954 | 4.358571 | false | false | false | false |
AsynkronIT/protoactor-kotlin | proto-remote/src/main/kotlin/actor/proto/remote/Messages.kt | 1 | 1668 | package actor.proto.remote
import actor.proto.PID
import com.google.protobuf.ByteString
data class EndpointTerminatedEvent(var address: String)
data class RemoteTerminate(val watcher: PID, val watchee: PID)
data class RemoteWatch(val watcher: PID, val watchee: PID)
data class RemoteUnwatch(val watcher: PID, val watchee: PID)
data class RemoteDeliver(val message: Any, val target: PID, val sender: PID?, val serializerId: Int)
data class JsonMessage(val typeName: String, val json: String)
fun ActorPidRequest(kind: String, name: String): RemoteProtos.ActorPidRequest {
val builder = RemoteProtos.ActorPidRequest.newBuilder()
builder.kind = kind
builder.name = name
return builder.build()
}
fun MessageEnvelope(bytes: ByteString, sender: PID?, targetId: Int, typeId: Int, serializerId: Int): RemoteProtos.MessageEnvelope {
val builder = RemoteProtos.MessageEnvelope.newBuilder()
builder.messageData = bytes
if (sender != null) {
builder.sender = sender
}
builder.target = targetId
builder.typeId = typeId
builder.serializerId = serializerId
return builder.build()
}
fun ConnectRequest(): RemoteProtos.ConnectRequest {
val builder = RemoteProtos.ConnectRequest.newBuilder()
return builder.build()
}
fun ActorPidResponse(pid: PID): RemoteProtos.ActorPidResponse {
val builder = RemoteProtos.ActorPidResponse.newBuilder()
builder.pid = pid
return builder.build()
}
fun ConnectResponse(defaultSerializerId: Int): RemoteProtos.ConnectResponse? {
val builder = RemoteProtos.ConnectResponse.newBuilder()
builder.defaultSerializerId = defaultSerializerId
return builder.build()
} | apache-2.0 | 398b47de4fe57bd12ce2aefc5d29637d | 33.770833 | 131 | 0.757794 | 4.068293 | false | false | false | false |
lvtanxi/TanxiNote | app/src/main/java/com/lv/note/util/CommonUtils.kt | 1 | 10020 | package com.lv.note.util
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.util.DisplayMetrics
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.lv.note.R
import com.plattysoft.leonids.ParticleSystem
import java.io.File
import java.io.FileOutputStream
import java.lang.ref.WeakReference
/**
* @author andy he
* *
* @ClassName: CommonUtils
* *
* @Description: 通用、不好归类的工具
* *
* @date 2016年1月15日 上午10:18:53
*/
object CommonUtils {
fun isNetworkAvailable(context: Context): Boolean {
val connectivity = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (connectivity != null) {
val info = connectivity.activeNetworkInfo
if (info != null && info.isConnected) {
if (info.state == NetworkInfo.State.CONNECTED) {
return true
}
}
}
return false
}
/**
* 获取版本名称
*/
fun versionName(context: Context): String {
try {
return context.packageManager.getPackageInfo(context.packageName, 0).versionName
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
return ""
}
/**
* 获取版本号
*/
fun versionCode(context: Context): Int {
val manager = context.packageManager
val info = manager.getPackageInfo(context.packageName, 0)
return info.versionCode.toInt()// 版本号
}
/**
* 显示键盘
* @param context 内容上下文
*/
fun showKeyBoard(context: Context) {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
}
/**
* 隐藏键盘
* @param view 控件
*/
fun hiddenKeyBoard(view: View) {
val imm = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
if (imm.isActive)
imm.hideSoftInputFromWindow(view.applicationWindowToken, 0)
}
/**
* 检查SDK是否存在
* @return
*/
fun checkSDCardAvailable(): Boolean {
return android.os.Environment.getExternalStorageState() == android.os.Environment.MEDIA_MOUNTED
}
/**
* 获取屏幕
* @param context
* *
* @return
*/
fun getDisplayMetrics(context: Context): DisplayMetrics {
val dm = DisplayMetrics()
(context as Activity).windowManager.defaultDisplay.getMetrics(dm)
return dm
}
fun getErrorMessage(code: Int): String {
when (code) {
9001 ->
return "Application Id为空,请初始化"
9002 ->
return "解析返回数据出错"
9003 ->
return "上传文件出错"
9004 ->
return "文件上传失败"
9005 ->
return "批量操作只支持最多50条"
9006 ->
return "objectId为空"
9007 ->
return "文件大小超过10M"
9008 ->
return "上传文件不存在"
9009 ->
return "没有缓存数据"
9010 ->
return "网络超时"
9011 ->
return "BmobUser类不支持批量操作"
9012 ->
return "上下文为空"
9013 ->
return "BmobObject(数据表名称)格式不正确"
9014 ->
return "第三方账号授权失败"
9015 ->
return "未知错误"
9016 ->
return "无网络连接,请检查您的手机网络"
9017 ->
return "第三方登录失败"
9018 ->
return "参数不能为空"
9019 ->
return "格式不正确"
else -> return ""
}
}
fun convertToBitmap(path: String, w: Int, h: Int): Bitmap? {
try {
val opts = BitmapFactory.Options()
// 设置为ture只获取图片大小
opts.inJustDecodeBounds = true
opts.inPreferredConfig = Bitmap.Config.ARGB_8888
// 返回为空
BitmapFactory.decodeFile(path, opts)
val width = opts.outWidth
val height = opts.outHeight
var scaleWidth = 0.0f
var scaleHeight = 0.0f
if (width > w || height > h) {
// 缩放
scaleWidth = width.toFloat() / w
scaleHeight = height.toFloat() / h
}
opts.inJustDecodeBounds = false
val scale = Math.max(scaleWidth, scaleHeight)
opts.inSampleSize = scale.toInt()
val weak = WeakReference(BitmapFactory.decodeFile(path, opts))
val bMapRotate = Bitmap.createBitmap(weak.get(), 0, 0, weak.get()!!.width, weak.get()!!.height, null, true)
if (bMapRotate != null) {
return bMapRotate
}
return null
} catch (e: Exception) {
e.printStackTrace()
return null
}
}
fun savePhotoToSDCard(photoBitmap: Bitmap?, path: String) {
if (checkSDCardAvailable()) {
val photoFile = File(path)
var fileOutputStream: FileOutputStream? = null
try {
fileOutputStream = FileOutputStream(photoFile)
if (photoBitmap != null) {
if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)) {
fileOutputStream.flush()
}
}
} catch (e: Exception) {
photoFile.delete()
e.printStackTrace()
} finally {
try {
fileOutputStream!!.close()
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
fun showSuccess(activity: Activity, tageView: View, back: CountDown.CountDownBack?) {
ParticleSystem(activity, 800, R.mipmap.star_pink, 1000)
.setSpeedRange(0.1f, 0.25f)
.oneShot(tageView, 100)
CountDown(1000)
.setActivity(activity)
.setDownBack(back)
.start();
}
fun forMat(str: String?): String {
str?.let {
val length = str.length
val sb = StringBuffer()
for (i in 0..length - 1) {
sb.append(str[i])
if ((i + 1) % 10 == 0) {
sb.append("\n")
}
}
return sb.toString()
}
return ""
}
fun displayRoundImage(imageView: ImageView, url: String) {
Glide.with(imageView.context)
.load(url)
.placeholder(R.mipmap.header)
.error(R.mipmap.header)
.crossFade()
.into(imageView)
}
fun getWeatherTypeImageID(type: String?, isDay: Boolean): Int {
if (null == type)
return R.mipmap.ic_weather_no
val weatherId: Int
when (type) {
"晴" -> if (isDay) {
weatherId = R.mipmap.ic_weather_sunny_day
} else {
weatherId = R.mipmap.ic_weather_sunny_night
}
"多云" -> if (isDay) {
weatherId = R.mipmap.ic_weather_cloudy_day
} else {
weatherId = R.mipmap.ic_weather_cloudy_night
}
"阴" -> weatherId = R.mipmap.ic_weather_overcast
"雷阵雨", "雷阵雨伴有冰雹" -> weatherId = R.mipmap.ic_weather_thunder_shower
"雨夹雪" -> weatherId = R.mipmap.ic_weather_sleet
"冻雨" -> weatherId = R.mipmap.ic_weather_ice_rain
"小雨", "小到中雨", "阵雨" -> weatherId = R.mipmap.ic_weather_light_rain_or_shower
"中雨", "中到大雨" -> weatherId = R.mipmap.ic_weather_moderate_rain
"大雨", "大到暴雨" -> weatherId = R.mipmap.ic_weather_heavy_rain
"暴雨", "大暴雨", "特大暴雨", "暴雨到大暴雨", "大暴雨到特大暴雨" -> weatherId = R.mipmap.ic_weather_storm
"阵雪", "小雪", "小到中雪" -> weatherId = R.mipmap.ic_weather_light_snow
"中雪", "中到大雪" -> weatherId = R.mipmap.ic_weather_moderate_snow
"大雪", "大到暴雪" -> weatherId = R.mipmap.ic_weather_heavy_snow
"暴雪" -> weatherId = R.mipmap.ic_weather_snowstrom
"雾" -> weatherId = R.mipmap.ic_weather_foggy
"霾" -> weatherId = R.mipmap.ic_weather_haze
"沙尘暴" -> weatherId = R.mipmap.ic_weather_duststorm
"强沙尘暴" -> weatherId = R.mipmap.ic_weather_sandstorm
"浮尘", "扬沙" -> weatherId = R.mipmap.ic_weather_sand_or_dust
else -> if (type.contains("尘") || type.contains("沙")) {
weatherId = R.mipmap.ic_weather_sand_or_dust
} else if (type.contains("雾") || type.contains("霾")) {
weatherId = R.mipmap.ic_weather_foggy
} else if (type.contains("雨")) {
weatherId = R.mipmap.ic_weather_ice_rain
} else if (type.contains("雪") || type.contains("冰雹")) {
weatherId = R.mipmap.ic_weather_moderate_snow
} else {
weatherId = R.mipmap.ic_weather_no
}
}
return weatherId
}
}
| apache-2.0 | 567585b0a536463bdbaf0adc07d550bc | 30.884746 | 119 | 0.526366 | 3.988974 | false | false | false | false |
YiiGuxing/TranslationPlugin | src/main/kotlin/cn/yiiguxing/plugin/translate/util/UrlBuilder.kt | 1 | 947 | package cn.yiiguxing.plugin.translate.util
@Suppress("unused")
/**
* UrlBuilder
*/
class UrlBuilder(private val baseUrl: String) {
private val queryParameters = mutableListOf<Pair<String, String>>()
fun addQueryParameter(name: String, value: String) = apply {
queryParameters += name to value
}
fun addQueryParameters(name: String, vararg values: String) = apply {
queryParameters += values.map { name to it }
}
fun addQueryParameters(vararg parameters: Pair<String, String>) = apply {
queryParameters += parameters
}
fun build(): String {
if (queryParameters.isEmpty()) {
return baseUrl
}
return StringBuilder(baseUrl).apply {
queryParameters.forEachIndexed { index, (name, value) ->
append(if (index == 0) "?" else "&")
append(name, "=", value.urlEncode())
}
}.toString()
}
} | mit | 82035553089adc51ba61251fe0605d55 | 25.333333 | 77 | 0.600845 | 4.711443 | false | false | false | false |
itachi1706/CheesecakeUtilities | app/src/main/java/com/itachi1706/cheesecakeutilities/modules/gpaCalculator/objects/GpaModule.kt | 1 | 383 | package com.itachi1706.cheesecakeutilities.modules.gpaCalculator.objects
/**
* Created by Kenneth on 26/6/2019.
* for com.itachi1706.cheesecakeutilities.modules.gpaCalculator.objects in CheesecakeUtilities
*/
data class GpaModule(val name: String = "", val courseCode: String = "", val gradeTier: Int = -1, val credits: Int = 0, val passFail: Boolean = false, val color: Int = 0) | mit | 7efbf23b6243eda1f01627349dd15195 | 53.857143 | 170 | 0.754569 | 3.682692 | false | false | false | false |
Kotlin/anko | anko/library/generator/src/org/jetbrains/android/anko/utils/ClassInfo.kt | 4 | 2350 | /*
* Copyright 2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.android.anko.utils
import org.jetbrains.android.anko.isConstructor
import org.objectweb.asm.Opcodes
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.MethodNode
data class MethodNodeWithClass(var clazz: ClassNode, val method: MethodNode) {
val identifier = "${clazz.fqName}#${method.name}"
}
internal val ClassNode.fqName: String
get() = name.replace('/', '.').replace('$', '.')
internal val ClassNode.packageName: String
get() = fqName.substringBeforeLast('.')
internal val ClassNode.fqNameWithTypeArguments: String
get() = fqName + buildTypeParams()
internal val ClassNode.simpleName: String
get() {
val name = fqName
return if (name.indexOf('$') >= 0) name.substringAfterLast('$') else name.substringAfterLast('.')
}
internal fun ClassNode.buildTypeParams(): String {
return if (signature != null) {
val genericMethodSignature = parseGenericMethodSignature(signature)
if (genericMethodSignature.typeParameters.isEmpty()) return ""
genericMethodSignature.typeParameters
.map { it.upperBounds.fold("") { s, bound -> s + "out " + genericTypeToKType(bound) } }
.joinToString(prefix = "<", postfix = ">")
} else ""
}
val ClassNode.isInner: Boolean
get() = name.contains("$")
internal val ClassNode.isPublic: Boolean
get() = ((access and Opcodes.ACC_PUBLIC) != 0)
internal val ClassNode.isInterface: Boolean
get() = ((access and Opcodes.ACC_INTERFACE) != 0)
internal val ClassNode.isAbstract: Boolean
get() = ((access and Opcodes.ACC_ABSTRACT) != 0)
internal fun ClassNode.getConstructors(): List<MethodNode> {
return (methods as List<MethodNode>).filter { it.isConstructor }
} | apache-2.0 | 517e6f5fc3bb7b75c5e847e3243d3a21 | 33.573529 | 105 | 0.705532 | 4.319853 | false | false | false | false |
google/grpc-kapt | processor/src/main/kotlin/com/google/api/grpc/kapt/generator/proto/ProtobufTypeMapper.kt | 1 | 5946 | /*
* Copyright 2019 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 com.google.api.grpc.kapt.generator.proto
import com.google.common.base.CaseFormat
import com.google.protobuf.DescriptorProtos
import com.squareup.kotlinpoet.ClassName
/** Maps proto names to kotlin names */
internal class ProtobufTypeMapper private constructor() {
private val typeMap = mutableMapOf<String, String>()
private val serviceMap = mutableMapOf<String, String>()
private val knownProtoTypes = mutableMapOf<String, DescriptorProtos.DescriptorProto>()
private val knownProtoEnums = mutableMapOf<String, DescriptorProtos.EnumDescriptorProto>()
/** Lookup the Kotlin type given the proto type. */
fun getKotlinType(protoType: String) =
ClassName.bestGuess(
typeMap[protoType]
?: throw IllegalArgumentException("proto type: $protoType is not recognized")
)
/** Get all Kotlin types (excluding enums and map types) */
fun getAllKotlinTypes() = knownProtoTypes.keys
.asSequence()
.filter { !(knownProtoTypes[it]?.options?.mapEntry ?: false) }
.map { typeMap[it] ?: throw IllegalStateException("unknown type: $it") }
.toList()
fun getAllTypes() = knownProtoTypes.keys.map { TypeNamePair(it, typeMap[it]!!) }
/** Checks if the message type is in this mapper */
fun hasProtoTypeDescriptor(type: String) = knownProtoTypes.containsKey(type)
/** Lookup up a known proto message type by name */
fun getProtoTypeDescriptor(type: String) = knownProtoTypes[type]
?: throw IllegalArgumentException("unknown type: $type")
/** Checks if the enum type is in this mapper */
fun hasProtoEnumDescriptor(type: String) = knownProtoEnums.containsKey(type)
/** Lookup a known proto enum type by name */
fun getProtoEnumDescriptor(type: String) = knownProtoEnums[type]
?: throw IllegalArgumentException("unknown enum: $type")
override fun toString(): String {
val ret = StringBuilder("Types:")
typeMap.forEach { k, v -> ret.append("\n $k -> $v") }
return ret.toString()
}
companion object {
/** Create a map from a set of proto descriptors */
fun fromProtos(descriptors: Collection<DescriptorProtos.FileDescriptorProto>): ProtobufTypeMapper {
val map = ProtobufTypeMapper()
descriptors.map { proto ->
val protoPackage = if (proto.hasPackage()) "." + proto.`package` else ""
val javaPackage = if (proto.options.hasJavaPackage())
proto.options.javaPackage
else
proto.`package`
val enclosingClassName = if (proto.options?.javaMultipleFiles != false)
null
else
getOuterClassname(proto)
fun addMsg(p: DescriptorProtos.DescriptorProto, parent: String) {
val key = "$protoPackage$parent.${p.name}"
map.typeMap[key] = listOfNotNull("$javaPackage$parent", enclosingClassName, p.name)
.joinToString(".")
map.knownProtoTypes[key] = p
}
fun addEnum(p: DescriptorProtos.EnumDescriptorProto, parent: String) {
val key = "$protoPackage$parent.${p.name}"
map.typeMap[key] = listOfNotNull("$javaPackage$parent", enclosingClassName, p.name)
.joinToString(".")
map.knownProtoEnums[key] = p
}
fun addService(p: DescriptorProtos.ServiceDescriptorProto, parent: String) {
map.serviceMap["$protoPackage$parent.${p.name}"] =
listOfNotNull("$javaPackage$parent", enclosingClassName, p.name)
.joinToString(".")
}
fun addNested(p: DescriptorProtos.DescriptorProto, parent: String) {
addMsg(p, parent)
p.enumTypeList.forEach { addEnum(it, "$parent.${p.name}") }
p.nestedTypeList.forEach { addNested(it, "$parent.${p.name}") }
}
// process top level types and services
proto.messageTypeList.forEach { addNested(it, "") }
proto.serviceList.forEach { addService(it, "") }
proto.enumTypeList.forEach { addEnum(it, "") }
}
return map
}
private fun getOuterClassname(proto: DescriptorProtos.FileDescriptorProto): String {
if (proto.options.hasJavaOuterClassname()) {
return proto.options.javaOuterClassname
}
var fileName = proto.name.substring(0, proto.name.length - ".proto".length)
if (fileName.contains("/")) {
fileName = fileName.substring(fileName.lastIndexOf('/') + 1)
}
fileName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, fileName)
if (proto.enumTypeList.any { it.name == fileName } ||
proto.messageTypeList.any { it.name == fileName } ||
proto.serviceList.any { it.name == fileName }) {
fileName += "OuterClass"
}
return fileName
}
}
}
internal data class TypeNamePair(val protoName: String, val kotlinName: String)
| apache-2.0 | 54f213a5f8dee8d00096a159573a23d3 | 40.873239 | 107 | 0.610831 | 4.955 | false | false | false | false |
jabbink/PokemonGoBot | src/main/kotlin/ink/abb/pogo/scraper/util/data/ItemData.kt | 2 | 757 | /**
* Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information)
* This program comes with ABSOLUTELY NO WARRANTY;
* This is free software, and you are welcome to redistribute it under certain conditions.
*
* For more information, refer to the LICENSE file in this repositories root directory
*/
package ink.abb.pogo.scraper.util.data
import POGOProtos.Inventory.Item.ItemIdOuterClass
data class ItemData(
var itemId: Int? = null,
var itemName: String? = null,
var count: Int? = null
) {
fun buildFromItem(item: ItemIdOuterClass.ItemId, count: Int): ItemData {
this.itemId = item.number
this.itemName = item.name
this.count = count
return this
}
}
| gpl-3.0 | e4b2fbf54ec168f3034c8e906ca48007 | 30.541667 | 97 | 0.693527 | 4.136612 | false | false | false | false |
ujpv/intellij-rust | src/main/kotlin/org/rust/lang/core/types/visitors/impl/RustHashCodeComputingTypeVisitor.kt | 1 | 2741 | package org.rust.lang.core.types.visitors.impl
import org.rust.lang.core.types.*
import org.rust.lang.core.types.unresolved.*
import org.rust.lang.core.types.visitors.RustInvariantTypeVisitor
import org.rust.lang.core.types.visitors.RustTypeVisitor
import org.rust.lang.core.types.visitors.RustUnresolvedTypeVisitor
open class RustHashCodeComputingTypeVisitor
: RustHashCodeComputingTypeVisitorBase()
, RustTypeVisitor<Int> {
protected fun visit(type: RustType): Int = type.accept(this)
override fun visitStruct(type: RustStructType): Int = type.item.hashCode() * 10067 + 9631
override fun visitEnum(type: RustEnumType): Int = type.item.hashCode() * 12289 + 9293
override fun visitTypeParameter(type: RustTypeParameterType): Int = type.parameter.hashCode() * 13859 + 9419
override fun visitTrait(type: RustTraitType): Int = type.trait.hashCode() * 12757 + 10061
override fun visitTupleType(type: RustTupleType): Int =
type.types.fold(0, { h, ty -> h * 8741 + visit(ty) }) + 17387
override fun visitFunctionType(type: RustFunctionType): Int =
sequenceOf(*type.paramTypes.toTypedArray(), type.retType).fold(0, { h, ty -> h * 11173 + visit(ty) }) + 8929
override fun visitReference(type: RustReferenceType): Int =
visit(type.referenced) * 13577 + (if (type.mutable) 3331 else 0) + 9901
}
open class RustHashCodeComputingUnresolvedTypeVisitor
: RustHashCodeComputingTypeVisitorBase()
, RustUnresolvedTypeVisitor<Int> {
protected fun visit(type: RustUnresolvedType): Int = type.accept(this)
override fun visitPathType(type: RustUnresolvedPathType): Int = type.path.hashCode()
override fun visitTupleType(type: RustUnresolvedTupleType): Int =
type.types.fold(0, { h, ty -> h * 7927 + visit(ty) }) + 16823
override fun visitFunctionType(type: RustUnresolvedFunctionType): Int =
sequenceOf(*type.paramTypes.toTypedArray(), type.retType).fold(0, { h, ty -> h * 13591 + visit(ty) }) + 9187
override fun visitReference(type: RustUnresolvedReferenceType): Int =
visit(type.referenced) * 10103 + (if (type.mutable) 5953 else 0) + 11159
}
open class RustHashCodeComputingTypeVisitorBase : RustInvariantTypeVisitor<Int> {
override fun visitInteger(type: RustIntegerType): Int = type.kind.hashCode()
override fun visitFloat(type: RustFloatType): Int = type.kind.hashCode()
override fun visitUnitType(type: RustUnitType): Int = 9049
override fun visitString(type: RustStringSliceType): Int = 10709
override fun visitChar(type: RustCharacterType): Int = 10099
override fun visitBoolean(type: RustBooleanType): Int = 10427
override fun visitUnknown(type: RustUnknownType): Int = 10499
}
| mit | 521ec3eb5632dec5eb4e2b8afbe2aab6 | 37.605634 | 116 | 0.732215 | 3.871469 | false | false | false | false |
LorittaBot/Loritta | pudding/client/src/main/kotlin/net/perfectdreams/loritta/cinnamon/pudding/tables/CoinFlipBetGlobalMatchmakingQueue.kt | 1 | 558 | package net.perfectdreams.loritta.cinnamon.pudding.tables
import net.perfectdreams.exposedpowerutils.sql.javatime.timestampWithTimeZone
import org.jetbrains.exposed.dao.id.LongIdTable
object CoinFlipBetGlobalMatchmakingQueue : LongIdTable() {
val user = reference("user", Profiles).index()
val userInteractionToken = text("user_interaction_token")
val quantity = long("quantity").index()
val language = text("language")
val timestamp = timestampWithTimeZone("timestamp")
val expiresAt = timestampWithTimeZone("expires_at").index()
} | agpl-3.0 | 49db749f5d285053f096a7a7e3cbb54a | 42 | 77 | 0.775986 | 4.393701 | false | false | false | false |
lzanita09/KotlinHackerNews | app/src/main/java/com/reindeercrafts/hackernews/data/SharedPrefsHelper.kt | 1 | 710 | package com.reindeercrafts.hackernews.data
import android.content.Context
class SharedPrefsHelper(private val context: Context) {
private val PREFS_NAME = "prefs"
private val PREFS_KEY_ID = "id"
fun saveId(id: String) {
val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
prefs.edit().putString(PREFS_KEY_ID, id).apply()
}
fun getId(): String? {
val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
return prefs.getString(PREFS_KEY_ID, null)
}
fun clearId() {
val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
prefs.edit().remove(PREFS_KEY_ID).apply()
}
} | mit | ae2ac82c700a0c6b12e2a92f3c2b1d02 | 29.913043 | 82 | 0.680282 | 3.837838 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/website/utils/WebsiteAssetsHashes.kt | 1 | 1050 | package net.perfectdreams.loritta.morenitta.website.utils
import org.apache.commons.codec.digest.DigestUtils
import java.io.File
import java.util.concurrent.ConcurrentHashMap
object WebsiteAssetsHashes {
val websiteFileHashes = ConcurrentHashMap<String, String>()
val legacyWebsiteFileHashes = ConcurrentHashMap<String, String>()
fun getAssetHash(assetName: String): String {
return if (websiteFileHashes.containsKey(assetName)) {
websiteFileHashes[assetName]!!
} else {
val md5 = DigestUtils.md5Hex(File("${net.perfectdreams.loritta.morenitta.website.LorittaWebsite.FOLDER}/static/v2/$assetName").inputStream())
websiteFileHashes[assetName] = md5
md5
}
}
fun getLegacyAssetHash(assetName: String): String {
return if (legacyWebsiteFileHashes.containsKey(assetName)) {
legacyWebsiteFileHashes[assetName]!!
} else {
val md5 = DigestUtils.md5Hex(File("${net.perfectdreams.loritta.morenitta.website.LorittaWebsite.FOLDER}/static/$assetName").inputStream())
legacyWebsiteFileHashes[assetName] = md5
md5
}
}
} | agpl-3.0 | 08ca3f35d77efc2edfb4ee7d66b6de3b | 34.033333 | 144 | 0.778095 | 3.804348 | false | false | false | false |
zyyoona7/KExtensions | lib/src/main/java/com/zyyoona7/extensions/resources.kt | 1 | 3519 | package com.zyyoona7.extensions
import android.app.Fragment
import android.content.Context
import android.content.res.AssetManager
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.support.annotation.ColorRes
import android.support.annotation.DrawableRes
import android.support.annotation.RawRes
import android.support.v4.content.ContextCompat
import android.util.TypedValue
import android.view.View
import java.io.File
import java.io.IOException
import java.io.InputStream
/**
* Created by zyyoona7 on 2017/8/26.
* 资源相关的扩展函数
*
*/
/*
---------- Context ----------
*/
fun Context.loadColor(@ColorRes id: Int): Int = ContextCompat.getColor(this, id)
fun Context.loadDrawable(@DrawableRes id: Int): Drawable? = ContextCompat.getDrawable(this, id)
fun Context.loadRaw(@RawRes id: Int): InputStream? = resources.openRawResource(id)
fun Context.loadRaw(@RawRes id: Int, value: TypedValue): InputStream? = resources.openRawResource(id, value)
fun Context.loadAsset(fileName: String, accessMode: Int = AssetManager.ACCESS_STREAMING): InputStream? {
return try {
assets.open(fileName, accessMode)
} catch (e: IOException) {
e.printStackTrace()
null
}
}
fun Context.loadTypefaceFromAsset(fileName: String): Typeface = Typeface.createFromAsset(assets, fileName)
fun loadTypefaceFromFile(filePath: String): Typeface = Typeface.createFromFile(filePath)
fun loadTypefaceFromFile(file: File): Typeface = Typeface.createFromFile(file)
/*
---------- Fragment ----------
*/
fun Fragment.loadColor(@ColorRes id: Int): Int = activity?.loadColor(id) ?: 0
fun Fragment.loadDrawable(@DrawableRes id: Int): Drawable? = activity?.loadDrawable(id)
fun Fragment.loadRaw(@RawRes id: Int): InputStream? = activity?.loadRaw(id)
fun Fragment.loadRaw(@RawRes id: Int, value: TypedValue): InputStream? = activity?.loadRaw(id, value)
fun Fragment.loadAsset(fileName: String, accessMode: Int = AssetManager.ACCESS_STREAMING): InputStream? = activity?.loadAsset(fileName, accessMode)
fun Fragment.loadTypefaceFromAsset(fileName: String): Typeface? = activity?.loadTypefaceFromAsset(fileName)
fun android.support.v4.app.Fragment.loadColor(@ColorRes id: Int): Int = activity?.loadColor(id) ?: 0
fun android.support.v4.app.Fragment.loadDrawable(@DrawableRes id: Int): Drawable? = activity?.loadDrawable(id)
fun android.support.v4.app.Fragment.loadRaw(@RawRes id: Int): InputStream? = activity?.loadRaw(id)
fun android.support.v4.app.Fragment.loadRaw(@RawRes id: Int, value: TypedValue): InputStream? = activity?.loadRaw(id, value)
fun android.support.v4.app.Fragment.loadAsset(fileName: String, accessMode: Int = AssetManager.ACCESS_STREAMING): InputStream? = activity?.loadAsset(fileName, accessMode)
fun android.support.v4.app.Fragment.loadTypefaceFromAsset(fileName: String): Typeface? = activity?.loadTypefaceFromAsset(fileName)
/*
---------- View ----------
*/
fun View.loadColor(@ColorRes id: Int): Int = context.loadColor(id)
fun View.loadDrawable(@ColorRes id: Int): Drawable? = context.loadDrawable(id)
fun View.loadRaw(@RawRes id: Int): InputStream? = context.loadRaw(id)
fun View.loadRaw(@RawRes id: Int, value: TypedValue): InputStream? = context.loadRaw(id, value)
fun View.loadAsset(fileName: String, accessMode: Int = AssetManager.ACCESS_STREAMING): InputStream? = context.loadAsset(fileName, accessMode)
fun View.loadTypefaceFromAsset(fileName: String): Typeface = context.loadTypefaceFromAsset(fileName)
| apache-2.0 | f7f06b2ada0baa5939b3f2da93a6f2d4 | 37.054348 | 170 | 0.761782 | 3.784865 | false | false | false | false |
Magneticraft-Team/Magneticraft | ignore/test/guide/components/Recipe.kt | 2 | 3013 | package com.cout970.magneticraft.guide.components
import com.cout970.magneticraft.guide.IPageComponent
import com.cout970.magneticraft.guide.BookPage
import com.cout970.magneticraft.util.resource
import com.cout970.magneticraft.util.shuffled
import com.cout970.magneticraft.util.vector.Vec2d
import com.cout970.magneticraft.util.vector.contains
import net.minecraft.client.renderer.GlStateManager
import net.minecraft.item.ItemStack
class Recipe(
position: Vec2d,
val recipe: Array<out Array<out List<ItemStack>>>,
val result: ItemStack
) : PageComponent(position) {
companion object {
const val DISPLAY_TIME = 20
val GRID_TEXTURE = resource("textures/gui/guide/grid.png")
val GRID_SIZE = Vec2d(88, 56)
val STACK_OFFSET = Array(3) { row ->
Array(3) { column ->
Vec2d(2 + 18 * column, 2 + 18 * row)
}
}
val STACK_SIZE = Vec2d(16, 16)
val RESULT_OFFSET = Vec2d(68, 20)
}
override val id: String = "recipe"
override val size = Vec2d(70, 44)
override fun toGuiComponent(parent: BookPage.Gui): IPageComponent = Gui(parent)
private inner class Gui(parent: BookPage.Gui) : PageComponent.Gui(parent) {
val slots = recipe.map { it.map { it.shuffled() } }
override fun draw(mouse: Vec2d, time: Double) {
parent.gui.drawTexture(drawPos, GRID_SIZE, GRID_TEXTURE)
GlStateManager.pushMatrix()
GlStateManager.color(1f, 1f, 1f, 1f)
GlStateManager.enableBlend()
GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA)
slots.forEachIndexed { rowN, row ->
row.forEachIndexed { columnN, stacks ->
if (stacks.isNotEmpty()) {
val displayIndex = ((time.toInt() / DISPLAY_TIME) % stacks.size)
parent.gui.drawStack(stacks[displayIndex], drawPos + STACK_OFFSET[rowN][columnN])
}
}
}
parent.gui.drawStack(result, drawPos + RESULT_OFFSET)
GlStateManager.popMatrix()
}
override fun postDraw(mouse: Vec2d, time: Double) {
val mouseRelative = mouse - drawPos
if (mouseRelative in RESULT_OFFSET toPoint (RESULT_OFFSET + STACK_SIZE)) {
parent.gui.renderToolTip(result, mouse)
return
}
for (row in (0..2)) {
for (column in (0..2)) {
val offset = STACK_OFFSET[row][column]
if (mouseRelative in offset toPoint (offset + STACK_SIZE) && slots[row][column].isNotEmpty()) {
val displayIndex = ((time / DISPLAY_TIME) % slots[row][column].size).toInt()
parent.gui.renderToolTip(slots[row][column][displayIndex], mouse)
}
}
}
}
}
} | gpl-2.0 | 48c936b52926dc3cd6e6745a578b990e | 33.643678 | 122 | 0.590441 | 4.155862 | false | false | false | false |
robinverduijn/gradle | subprojects/kotlin-dsl-provider-plugins/src/main/kotlin/org/gradle/kotlin/dsl/provider/plugins/DefaultProjectSchemaProvider.kt | 1 | 7120 | /*
* 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.provider.plugins
import org.gradle.api.NamedDomainObjectCollectionSchema
import org.gradle.api.NamedDomainObjectCollectionSchema.NamedDomainObjectSchema
import org.gradle.api.NamedDomainObjectContainer
import org.gradle.api.Project
import org.gradle.api.artifacts.dsl.DependencyHandler
import org.gradle.api.plugins.ExtensionAware
import org.gradle.api.reflect.HasPublicType
import org.gradle.api.reflect.TypeOf
import org.gradle.api.tasks.SourceSet
import org.gradle.api.tasks.SourceSetContainer
import org.gradle.api.tasks.TaskContainer
import org.gradle.kotlin.dsl.accessors.ProjectSchema
import org.gradle.kotlin.dsl.accessors.ProjectSchemaEntry
import org.gradle.kotlin.dsl.accessors.ProjectSchemaProvider
import org.gradle.kotlin.dsl.accessors.SchemaType
import org.gradle.kotlin.dsl.accessors.TypedProjectSchema
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
import kotlin.reflect.KClass
import kotlin.reflect.KVisibility
import kotlin.reflect.full.superclasses
class DefaultProjectSchemaProvider : ProjectSchemaProvider {
override fun schemaFor(project: Project): TypedProjectSchema =
targetSchemaFor(project, typeOfProject).let { targetSchema ->
ProjectSchema(
targetSchema.extensions,
targetSchema.conventions,
targetSchema.tasks,
targetSchema.containerElements,
accessibleConfigurationsOf(project)
).map(::SchemaType)
}
}
private
data class TargetTypedSchema(
val extensions: List<ProjectSchemaEntry<TypeOf<*>>>,
val conventions: List<ProjectSchemaEntry<TypeOf<*>>>,
val tasks: List<ProjectSchemaEntry<TypeOf<*>>>,
val containerElements: List<ProjectSchemaEntry<TypeOf<*>>>
)
private
fun targetSchemaFor(target: Any, targetType: TypeOf<*>): TargetTypedSchema {
val extensions = mutableListOf<ProjectSchemaEntry<TypeOf<*>>>()
val conventions = mutableListOf<ProjectSchemaEntry<TypeOf<*>>>()
val tasks = mutableListOf<ProjectSchemaEntry<TypeOf<*>>>()
val containerElements = mutableListOf<ProjectSchemaEntry<TypeOf<*>>>()
fun collectSchemaOf(target: Any, targetType: TypeOf<*>) {
if (target is ExtensionAware) {
accessibleContainerSchema(target.extensions.extensionsSchema).forEach { schema ->
extensions.add(ProjectSchemaEntry(targetType, schema.name, schema.publicType))
collectSchemaOf(target.extensions.getByName(schema.name), schema.publicType)
}
}
if (target is Project) {
accessibleConventionsSchema(target.convention.plugins).forEach { (name, type) ->
conventions.add(ProjectSchemaEntry(targetType, name, type))
collectSchemaOf(target.convention.plugins[name]!!, type)
}
accessibleContainerSchema(target.tasks.collectionSchema).forEach { schema ->
tasks.add(ProjectSchemaEntry(typeOfTaskContainer, schema.name, schema.publicType))
}
collectSchemaOf(target.dependencies, typeOfDependencyHandler)
// WARN eagerly realize all source sets
sourceSetsOf(target)?.forEach { sourceSet ->
collectSchemaOf(sourceSet, typeOfSourceSet)
}
}
if (target is NamedDomainObjectContainer<*>) {
accessibleContainerSchema(target.collectionSchema).forEach { schema ->
containerElements.add(ProjectSchemaEntry(targetType, schema.name, schema.publicType))
}
}
}
collectSchemaOf(target, targetType)
return TargetTypedSchema(
extensions,
conventions,
tasks,
containerElements
)
}
private
fun accessibleConventionsSchema(plugins: Map<String, Any>) =
plugins.filterKeys(::isPublic).mapValues { inferPublicTypeOfConvention(it.value) }
private
fun accessibleContainerSchema(collectionSchema: NamedDomainObjectCollectionSchema) =
collectionSchema.elements
.filter { isPublic(it.name) }
.map(NamedDomainObjectSchema::toFirstKotlinPublicOrSelf)
private
fun NamedDomainObjectSchema.toFirstKotlinPublicOrSelf() =
publicType.concreteClass.kotlin.let { kotlinType ->
// Because a public Java class might not correspond necessarily to a
// public Kotlin type due to Kotlin `internal` semantics, we check
// whether the public Java class is also the first public Kotlin type,
// otherwise we compute a new schema entry with the correct Kotlin type.
val firstPublicKotlinType = kotlinType.firstKotlinPublicOrSelf
when {
firstPublicKotlinType === kotlinType -> this
else -> ProjectSchemaNamedDomainObjectSchema(
name,
firstPublicKotlinType.asTypeOf()
)
}
}
private
val KClass<*>.firstKotlinPublicOrSelf
get() = firstKotlinPublicOrNull ?: this
private
val KClass<*>.firstKotlinPublicOrNull: KClass<*>?
get() = takeIf { visibility == KVisibility.PUBLIC }
?: superclasses.firstNotNullResult { it.firstKotlinPublicOrNull }
private
class ProjectSchemaNamedDomainObjectSchema(
private val objectName: String,
private val objectPublicType: TypeOf<*>
) : NamedDomainObjectSchema {
override fun getName() = objectName
override fun getPublicType() = objectPublicType
}
private
fun sourceSetsOf(project: Project) =
project.extensions.findByName("sourceSets") as? SourceSetContainer
private
fun inferPublicTypeOfConvention(instance: Any) =
if (instance is HasPublicType) instance.publicType
else TypeOf.typeOf(instance::class.java.firstNonSyntheticOrSelf)
private
val Class<*>.firstNonSyntheticOrSelf
get() = firstNonSyntheticOrNull ?: this
private
val Class<*>.firstNonSyntheticOrNull: Class<*>?
get() = takeIf { !isSynthetic } ?: superclass?.firstNonSyntheticOrNull
private
fun accessibleConfigurationsOf(project: Project) =
project.configurations.names.filter(::isPublic)
private
fun isPublic(name: String): Boolean =
!name.startsWith("_")
private
val typeOfProject = typeOf<Project>()
private
val typeOfSourceSet = typeOf<SourceSet>()
private
val typeOfDependencyHandler = typeOf<DependencyHandler>()
private
val typeOfTaskContainer = typeOf<TaskContainer>()
internal
inline fun <reified T> typeOf(): TypeOf<T> =
object : TypeOf<T>() {}
private
fun KClass<out Any>.asTypeOf() =
TypeOf.typeOf(java)
| apache-2.0 | 9b6533f0f98f45579a04489698a73a0d | 31.072072 | 101 | 0.722612 | 4.69657 | false | false | false | false |
mozilla-mobile/focus-android | app/src/main/java/org/mozilla/focus/menu/browser/DefaultBrowserMenu.kt | 1 | 8505 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.menu.browser
import android.content.Context
import androidx.annotation.VisibleForTesting
import mozilla.components.browser.menu.WebExtensionBrowserMenuBuilder
import mozilla.components.browser.menu.item.BrowserMenuDivider
import mozilla.components.browser.menu.item.BrowserMenuImageSwitch
import mozilla.components.browser.menu.item.BrowserMenuImageText
import mozilla.components.browser.menu.item.BrowserMenuItemToolbar
import mozilla.components.browser.menu.item.TwoStateBrowserMenuImageText
import mozilla.components.browser.menu.item.WebExtensionPlaceholderMenuItem
import mozilla.components.browser.state.selector.selectedTab
import mozilla.components.browser.state.state.TabSessionState
import mozilla.components.browser.state.store.BrowserStore
import mozilla.components.feature.webcompat.reporter.WebCompatReporterFeature
import org.mozilla.focus.R
import org.mozilla.focus.menu.ToolbarMenu
import org.mozilla.focus.state.AppStore
import org.mozilla.focus.theme.resolveAttribute
import org.mozilla.focus.topsites.DefaultTopSitesStorage.Companion.TOP_SITES_MAX_LIMIT
/**
* The overflow menu shown in the BrowserFragment containing page actions like "Refresh", "Share" etc.
*/
class DefaultBrowserMenu(
private val context: Context,
private val appStore: AppStore,
private val store: BrowserStore,
private val isPinningSupported: Boolean,
private val onItemTapped: (ToolbarMenu.Item) -> Unit = {},
) : ToolbarMenu {
private val selectedSession: TabSessionState?
get() = store.state.selectedTab
override val menuBuilder by lazy {
WebExtensionBrowserMenuBuilder(
items = mvpMenuItems,
store = store,
showAddonsInMenu = false,
)
}
override val menuToolbar by lazy {
val back = BrowserMenuItemToolbar.TwoStateButton(
primaryImageResource = R.drawable.mozac_ic_back,
primaryContentDescription = context.getString(R.string.content_description_back),
primaryImageTintResource = context.theme.resolveAttribute(R.attr.primaryText),
isInPrimaryState = {
selectedSession?.content?.canGoBack ?: true
},
secondaryImageTintResource = context.theme.resolveAttribute(R.attr.disabled),
disableInSecondaryState = true,
longClickListener = { onItemTapped.invoke(ToolbarMenu.Item.Back) },
) {
onItemTapped.invoke(ToolbarMenu.Item.Back)
}
val forward = BrowserMenuItemToolbar.TwoStateButton(
primaryImageResource = R.drawable.mozac_ic_forward,
primaryContentDescription = context.getString(R.string.content_description_forward),
primaryImageTintResource = context.theme.resolveAttribute(R.attr.primaryText),
isInPrimaryState = {
selectedSession?.content?.canGoForward ?: true
},
secondaryImageTintResource = context.theme.resolveAttribute(R.attr.disabled),
disableInSecondaryState = true,
longClickListener = { onItemTapped.invoke(ToolbarMenu.Item.Forward) },
) {
onItemTapped.invoke(ToolbarMenu.Item.Forward)
}
val refresh = BrowserMenuItemToolbar.TwoStateButton(
primaryImageResource = R.drawable.mozac_ic_refresh,
primaryContentDescription = context.getString(R.string.content_description_reload),
primaryImageTintResource = context.theme.resolveAttribute(R.attr.primaryText),
isInPrimaryState = {
selectedSession?.content?.loading == false
},
secondaryImageResource = R.drawable.mozac_ic_stop,
secondaryContentDescription = context.getString(R.string.content_description_stop),
secondaryImageTintResource = context.theme.resolveAttribute(R.attr.primaryText),
disableInSecondaryState = false,
longClickListener = { onItemTapped.invoke(ToolbarMenu.Item.Reload) },
) {
if (selectedSession?.content?.loading == true) {
onItemTapped.invoke(ToolbarMenu.Item.Stop)
} else {
onItemTapped.invoke(ToolbarMenu.Item.Reload)
}
}
val share = BrowserMenuItemToolbar.Button(
imageResource = R.drawable.mozac_ic_share,
contentDescription = context.getString(R.string.menu_share),
iconTintColorResource = context.theme.resolveAttribute(R.attr.primaryText),
listener = {
onItemTapped.invoke(ToolbarMenu.Item.Share)
},
)
BrowserMenuItemToolbar(listOf(back, forward, share, refresh))
}
private val mvpMenuItems by lazy {
val shortcuts = TwoStateBrowserMenuImageText(
primaryLabel = context.getString(R.string.menu_add_to_shortcuts),
primaryStateIconResource = R.drawable.mozac_ic_pin,
secondaryLabel = context.getString(R.string.menu_remove_from_shortcuts),
secondaryStateIconResource = R.drawable.mozac_ic_pin_remove,
isInPrimaryState = {
appStore.state.topSites.find { it.url == selectedSession?.content?.url } == null &&
selectedSession?.content?.url != null && appStore.state.topSites.size < TOP_SITES_MAX_LIMIT
},
isInSecondaryState = {
appStore.state.topSites.find { it.url == selectedSession?.content?.url } != null
},
primaryStateAction = { onItemTapped.invoke(ToolbarMenu.Item.AddToShortcuts) },
secondaryStateAction = { onItemTapped.invoke(ToolbarMenu.Item.RemoveFromShortcuts) },
)
val shortcutsDivider = BrowserMenuDivider().apply {
visible = shortcuts.visible
}
val findInPage = BrowserMenuImageText(
label = context.getString(R.string.find_in_page),
imageResource = R.drawable.mozac_ic_search,
) {
onItemTapped.invoke(ToolbarMenu.Item.FindInPage)
}
val desktopMode = BrowserMenuImageSwitch(
imageResource = R.drawable.mozac_ic_device_desktop,
label = context.getString(R.string.preference_performance_request_desktop_site2),
initialState = {
selectedSession?.content?.desktopMode ?: false
},
) { checked ->
onItemTapped.invoke(ToolbarMenu.Item.RequestDesktop(checked))
}
val reportSiteIssuePlaceholder = WebExtensionPlaceholderMenuItem(
id = WebCompatReporterFeature.WEBCOMPAT_REPORTER_EXTENSION_ID,
iconTintColorResource = context.theme.resolveAttribute(R.attr.primaryText),
)
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
fun canAddToHomescreen(): Boolean =
selectedSession != null && isPinningSupported
val addToHomescreen = BrowserMenuImageText(
label = context.getString(R.string.menu_add_to_home_screen),
imageResource = R.drawable.mozac_ic_add_to_home_screen,
) {
onItemTapped.invoke(ToolbarMenu.Item.AddToHomeScreen)
}
val openInApp = BrowserMenuImageText(
label = context.getString(R.string.menu_open_with_a_browser2),
imageResource = R.drawable.mozac_ic_open_in,
textColorResource = context.theme.resolveAttribute(R.attr.primaryText),
) {
onItemTapped.invoke(ToolbarMenu.Item.OpenInApp)
}
val settings = BrowserMenuImageText(
label = context.getString(R.string.menu_settings),
imageResource = R.drawable.mozac_ic_settings,
textColorResource = context.theme.resolveAttribute(R.attr.primaryText),
) {
onItemTapped.invoke(ToolbarMenu.Item.Settings)
}
listOfNotNull(
menuToolbar,
BrowserMenuDivider(),
shortcuts,
shortcutsDivider,
findInPage,
desktopMode,
reportSiteIssuePlaceholder,
BrowserMenuDivider(),
addToHomescreen.apply { visible = ::canAddToHomescreen },
openInApp,
BrowserMenuDivider(),
settings,
)
}
}
| mpl-2.0 | fb690503c07a7163427e80ec53886b3a | 43.067358 | 111 | 0.667725 | 4.704093 | false | false | false | false |
Zomis/UltimateTTT | uttt-common/src/main/kotlin/net/zomis/tttultimate/TTBase.kt | 1 | 3045 | package net.zomis.tttultimate
class TTBase(val parent: TTBase?, val x: Int, val y: Int,
val mnkParameters: TTMNKParameters, factory: TicFactory?) : Winnable, HasSub<TTBase> {
private val subs: Array<Array<TTBase>>
override val winConds: List<TTWinCondition>
override var wonBy: TTPlayer = TTPlayer.NONE
override val sizeX: Int
get() = this.mnkParameters.width
override val sizeY: Int
get() = this.mnkParameters.height
override val consecutiveRequired: Int
get() = this.mnkParameters.consecutiveRequired
val isWon: Boolean
get() = wonBy !== TTPlayer.NONE
val globalX: Int
get() {
if (parent == null) {
return 0
}
return if (parent.parent == null) x else parent.x * parent.parent.sizeX + this.x
}
val globalY: Int
get() {
if (parent == null) {
return 0
}
return if (parent.parent == null) y else parent.y * parent.parent.sizeY + this.y
}
constructor(parent: TTBase?, parameters: TTMNKParameters, factory: TicFactory) : this(parent, 0, 0, parameters, factory)
init {
this.subs = Array(mnkParameters.height) { yy ->
Array(mnkParameters.width) { xx ->
factory!!.invoke(this, xx, yy)
}
}
this.winConds = TicUtils.setupWins(this)
}
fun determineWinner() {
var winner: TTPlayer = TTPlayer.NONE
for (cond in this.winConds) {
winner = winner.or(cond.determineWinnerNew())
}
if (winner == TTPlayer.NONE && subs().all { it.isWon }) {
winner = TTPlayer.BLOCKED
}
this.wonBy = winner
}
fun subs(): List<TTBase> {
if (!hasSubs()) {
return emptyList()
}
return subs.flatMap { it.toList() }
}
override fun getSub(x: Int, y: Int): TTBase? {
if (!hasSubs() && x == 0 && y == 0) {
return this
}
if (x < 0 || y < 0) {
return null
}
return if (x >= sizeX || y >= sizeY) null else subs[y][x]
}
fun setPlayedBy(playedBy: TTPlayer) {
this.wonBy = playedBy
}
override fun hasSubs(): Boolean {
return sizeX != 0 && sizeY != 0
}
override fun toString(): String {
return "{Pos $x, $y; Size $sizeX, $sizeY; Played by $wonBy. Parent is $parent}"
}
fun reset() {
this.setPlayedBy(TTPlayer.NONE)
subs().forEach { it.reset() }
}
fun getSmallestTile(x: Int, y: Int): TTBase? {
val topLeft = getSub(0, 0) ?: return null
val grandParent = topLeft.hasSubs()
if (!grandParent) {
return this.getSub(x, y)
}
val subX = x / topLeft.sizeX
val subY = y / topLeft.sizeY
val board = getSub(subX, subY) ?: throw NullPointerException("No such smallest tile found: $x, $y")
return board.getSub(x - subX * sizeX, y - subY * sizeY)
}
}
| mit | 20cd282d7506b8fc28337c7ef7889d88 | 26.681818 | 124 | 0.545813 | 3.80625 | false | false | false | false |
jksiezni/xpra-client | xpra-client-android/src/main/java/com/github/jksiezni/xpra/config/ServerDetailsDataStore.kt | 1 | 2923 | /*
* 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 androidx.preference.PreferenceDataStore
import io.reactivex.Single
import io.reactivex.schedulers.Schedulers
import org.jetbrains.annotations.NotNull
import xpra.protocol.PictureEncoding
/**
*
*/
class ServerDetailsDataStore(
val serverDetails: ServerDetails,
private val dao: @NotNull ConnectionDao) : PreferenceDataStore() {
companion object {
const val PREF_CONNECTION_TYPE = "connection_type"
const val PREF_NAME = "name"
const val PREF_HOST = "host"
const val PREF_PORT = "port"
const val PREF_USERNAME = "username"
const val PREF_PRIVATE_KEY = "private_keyfile"
const val PREF_DISPLAY_ID = "display_id"
const val PREF_PICTURE_ENC = "picture_encoding"
}
override fun getString(key: String, defValue: String?): String? {
return when (key) {
PREF_CONNECTION_TYPE -> serverDetails.type.name
PREF_NAME -> serverDetails.name
PREF_HOST -> serverDetails.host
PREF_PORT -> serverDetails.port.toString()
PREF_USERNAME -> serverDetails.username
PREF_DISPLAY_ID -> serverDetails.displayId.toString()
PREF_PICTURE_ENC -> serverDetails.pictureEncoding.name
else -> throw UnsupportedOperationException("$key is not supported")
}
}
override fun putString(key: String, value: String?) {
when (key) {
PREF_CONNECTION_TYPE -> serverDetails.type = enumValueOf(value ?: ConnectionType.TCP.name)
PREF_NAME -> serverDetails.name = value
PREF_HOST -> serverDetails.host = value
PREF_PORT -> serverDetails.port = value?.toInt() ?: 0
PREF_USERNAME -> serverDetails.username = value
PREF_DISPLAY_ID -> serverDetails.displayId = value?.toInt() ?: -1
PREF_PICTURE_ENC -> serverDetails.pictureEncoding = enumValueOf(value ?: PictureEncoding.jpeg.name)
}
}
fun save() {
Single.just(serverDetails).subscribeOn(Schedulers.io()).subscribe(dao.save())
}
} | gpl-3.0 | 10ecd1b78b6dd8b0dccfeacc9aa87240 | 39.054795 | 111 | 0.664044 | 4.435508 | false | false | false | false |
FredJul/TaskGame | TaskGame-Hero/src/main/java/net/fred/taskgame/hero/models/Level.kt | 1 | 6831 | /*
* Copyright (c) 2012-2017 Frederic Julian
*
* 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:></http:>//www.gnu.org/licenses/>.
*/
package net.fred.taskgame.hero.models
import android.content.Context
import android.support.annotation.DrawableRes
import android.support.annotation.RawRes
import android.util.Pair
import android.util.SparseBooleanArray
import net.fred.taskgame.hero.R
import net.frju.androidquery.annotation.DbField
import net.frju.androidquery.annotation.DbModel
import net.frju.androidquery.gen.LEVEL
import org.parceler.Parcel
import java.util.*
@Parcel(Parcel.Serialization.BEAN)
@DbModel(databaseProvider = LocalDatabaseProvider::class)
class Level {
@DbField(primaryKey = true)
var levelNumber: Int = 0
@DbField
var isCompleted: Boolean = false
var isBossLevel: Boolean = false
var enemyCards: MutableList<Card> = ArrayList()
@RawRes
var battleMusicResId = INVALID_ID
@RawRes
var startStoryMusicResId = INVALID_ID
@RawRes
var endStoryMusicResId = INVALID_ID
@DrawableRes
fun getEnemyIcon(context: Context): Int {
return STORY_CHARS_INFO_MAP[context.resources.getStringArray(R.array.level_stories)[levelNumber * 3 - 3]]?.second ?: 0
}
fun getStartStory(context: Context): String {
return context.resources.getStringArray(R.array.level_stories)[levelNumber * 3 - 2]
}
fun getEndStory(context: Context): String {
return context.resources.getStringArray(R.array.level_stories)[levelNumber * 3 - 1]
}
private fun addEnemyCard(cardId: Int): Level {
Card.allCardsMap[cardId]?.let {
enemyCards.add(it)
}
return this
}
companion object {
val INVALID_ID = 0
val STORY_CHARS_INFO_MAP: Map<String, Pair<Int, Int>> = object : HashMap<String, Pair<Int, Int>>() {
init {
put("hero", Pair(R.string.hero_name, R.drawable.invoker_female))
put("school_friend", Pair(R.string.school_friend_name, R.drawable.invoker_male))
put("school_master", Pair(R.string.school_master_name, R.drawable.high_invoker_male))
put("officer", Pair(R.string.officer_name, R.drawable.officer))
put("counselor", Pair(R.string.counselor_name, R.drawable.counselor))
put("king", Pair(R.string.king_name, R.drawable.king))
put("priest", Pair(R.string.priest_name, R.drawable.priest))
put("outlaw", Pair(R.string.outlaw_name, R.drawable.outlaw))
}
}
private val ALL_LEVELS_LIST = ArrayList<Level>()
val allLevelsList: List<Level>
get() = ALL_LEVELS_LIST
val correspondingDeckSlots: Int
get() {
val lastCompletedLevel = ALL_LEVELS_LIST
.takeWhile { it.isCompleted }
.count()
return getCorrespondingDeckSlots(lastCompletedLevel)
}
fun getCorrespondingDeckSlots(lastCompletedLevelNumber: Int): Int {
// Increase quickly, but then slow down
// See graph on: http://fooplot.com/plot/lpum8k6yac
return Math.pow(Math.log10(Math.pow((lastCompletedLevelNumber + 3).toDouble(), 3.0)), 2.0).toInt()
}
fun populate() {
ALL_LEVELS_LIST.clear()
val completedList = SparseBooleanArray()
for (level in LEVEL.select().query().toArray()) {
completedList.append(level.levelNumber, level.isCompleted)
}
var levelNumber = 1
/**************** Level 1 to 10 *****************
* Available slots == levelNumber + 1
*/
var level = generateLevel(levelNumber++, completedList)
level.addEnemyCard(Card.CREATURE_SYLPH)
level = generateLevel(levelNumber++, completedList)
level.addEnemyCard(Card.CREATURE_SKELETON).addEnemyCard(Card.CREATURE_SYLPH)
level = generateLevel(levelNumber++, completedList)
level.addEnemyCard(Card.CREATURE_SYLPH).addEnemyCard(Card.CREATURE_MERMAN).addEnemyCard(Card.CREATURE_SKELETON)
level = generateLevel(levelNumber++, completedList)
level.isBossLevel = true
level.battleMusicResId = R.raw.boss_theme
level.addEnemyCard(Card.CREATURE_SKELETON).addEnemyCard(Card.SUPPORT_POWER_POTION).addEnemyCard(Card.SUPPORT_MEDICAL_ATTENTION)
level = generateLevel(levelNumber++, completedList)
level.addEnemyCard(Card.CREATURE_SKELETON).addEnemyCard(Card.CREATURE_TROLL).addEnemyCard(Card.CREATURE_SYLPH_2)
level = generateLevel(levelNumber++, completedList)
level.addEnemyCard(Card.CREATURE_SKELETON).addEnemyCard(Card.CREATURE_LICH)
level = generateLevel(levelNumber++, completedList)
level.addEnemyCard(Card.CREATURE_EMPTY_ARMOR).addEnemyCard(Card.SUPPORT_MEDICAL_ATTENTION).addEnemyCard(Card.SUPPORT_MEDICAL_ATTENTION)
level = generateLevel(levelNumber++, completedList)
level.isBossLevel = true
level.battleMusicResId = R.raw.boss_theme
level.startStoryMusicResId = R.raw.story_suspens
level.endStoryMusicResId = R.raw.story_suspens
level.addEnemyCard(Card.CREATURE_EMPTY_ARMOR).addEnemyCard(Card.CREATURE_GRUNT)
level = generateLevel(levelNumber++, completedList)
level.startStoryMusicResId = R.raw.story_suspens
level.endStoryMusicResId = R.raw.story_suspens
level.addEnemyCard(Card.CREATURE_EMPTY_ARMOR).addEnemyCard(Card.CREATURE_EMPTY_ARMOR)
level = generateLevel(levelNumber++, completedList)
level.addEnemyCard(Card.CREATURE_GRUNT).addEnemyCard(Card.CREATURE_GRUNT_2).addEnemyCard(Card.SUPPORT_CONFUSION).addEnemyCard(Card.CREATURE_GRUNT)
}
private fun generateLevel(levelNumber: Int, completedList: SparseBooleanArray): Level {
val level = Level()
level.levelNumber = levelNumber
level.isCompleted = completedList.get(level.levelNumber)
ALL_LEVELS_LIST.add(level)
return level
}
}
}
| gpl-3.0 | 49525cf69ef5442cc55dcb59016647e1 | 38.947368 | 158 | 0.659201 | 3.950839 | false | false | false | false |
JiangKlijna/blog | src/main/java/com/jiangKlijna/web/app/ContextWrapper.kt | 1 | 1287 | package com.jiangKlijna.web.app
import com.jiangKlijna.web.util.DesUtils
import org.springframework.context.ApplicationContext
import org.springframework.web.context.ContextLoader
import org.springframework.web.context.WebApplicationContext
import org.springframework.web.context.support.WebApplicationContextUtils
import java.util.concurrent.Executors
import javax.servlet.ServletContext
open class ContextWrapper {
val webApplicationContext: WebApplicationContext
get() = ContextLoader.getCurrentWebApplicationContext()
val servletContext: ServletContext
get() = webApplicationContext.servletContext
val applicationContext: ApplicationContext by lazy {
WebApplicationContextUtils.getWebApplicationContext(servletContext)
}
// 上下文无关
companion object {
// 线程池,主要作用是生成message对象,并发布
private val pool = Executors.newCachedThreadPool()
val execute = fun(command: Runnable) = pool.execute(command)
// 加密解密字符串
val encrypt = fun(s: String) = DesUtils.du.encrypt(s)
val decrypt = fun(s: String) = DesUtils.du.decrypt(s)
// fun reString(s: String): String = s.toByteArray(Charset.forName("iso8859-1")).let { String(it) }
}
}
| gpl-2.0 | a0571e0673aa4f15c089663707a58b29 | 36.363636 | 110 | 0.746148 | 4.435252 | false | false | false | false |
charlesmadere/smash-ranks-android | smash-ranks-android/app/src/main/java/com/garpr/android/data/converters/AbsTournamentConverter.kt | 1 | 2308 | package com.garpr.android.data.converters
import com.garpr.android.data.models.AbsTournament
import com.garpr.android.data.models.FullTournament
import com.garpr.android.data.models.LiteTournament
import com.squareup.moshi.FromJson
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import com.squareup.moshi.ToJson
object AbsTournamentConverter {
private val MATCHES = 0 to "matches"
private val PLAYERS = 1 to "players"
private val OPTIONS = JsonReader.Options.of(MATCHES.second, PLAYERS.second)
@FromJson
fun fromJson(
reader: JsonReader,
fullTournamentAdapter: JsonAdapter<FullTournament>,
liteTournamentAdapter: JsonAdapter<LiteTournament>
): AbsTournament? {
if (reader.peek() == JsonReader.Token.NULL) {
return reader.nextNull()
}
val innerReader = reader.peekJson()
innerReader.beginObject()
var hasMatches = false
var hasPlayers = false
while (innerReader.hasNext()) {
when (innerReader.selectName(OPTIONS)) {
MATCHES.first -> {
hasMatches = true
innerReader.skipValue()
}
PLAYERS.first -> {
hasPlayers = true
innerReader.skipValue()
}
else -> {
innerReader.skipName()
innerReader.skipValue()
}
}
}
innerReader.endObject()
return if (hasMatches || hasPlayers) {
fullTournamentAdapter.fromJson(reader)
} else {
liteTournamentAdapter.fromJson(reader)
}
}
@ToJson
fun toJson(
writer: JsonWriter,
value: AbsTournament?,
fullTournamentAdapter: JsonAdapter<FullTournament>,
liteTournamentAdapter: JsonAdapter<LiteTournament>
) {
if (value == null) {
return
}
when (value.kind) {
AbsTournament.Kind.FULL -> fullTournamentAdapter.toJson(writer, value as FullTournament)
AbsTournament.Kind.LITE -> liteTournamentAdapter.toJson(writer, value as LiteTournament)
}
}
}
| unlicense | b7c555b2143256bcd9c6f595b42b6ab9 | 28.589744 | 100 | 0.597487 | 4.921109 | false | false | false | false |
ntemplon/legends-of-omterra | core/src/com/jupiter/europa/entity/ability/spell/JumpSpell.kt | 1 | 4345 | /*
* The MIT License
*
* Copyright 2015 Nathan Templon.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package com.jupiter.europa.entity.ability.spell
import com.badlogic.ashley.core.Entity
import com.badlogic.gdx.graphics.g2d.TextureAtlas
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.jupiter.europa.EuropaGame
import com.jupiter.europa.entity.Families
import com.jupiter.europa.entity.Mappers
import com.jupiter.europa.entity.ability.Ability
import com.jupiter.europa.entity.ability.AbilityCategory
import com.jupiter.europa.entity.ability.Action
import com.jupiter.europa.entity.ability.Cost
import com.jupiter.europa.entity.component.ResourceComponent
import com.jupiter.europa.entity.messaging.Message
import com.jupiter.europa.entity.messaging.TeleportCompleteMessage
import com.jupiter.europa.entity.messaging.TeleportRequestMessage
import com.jupiter.europa.entity.stats.characterclass.Magus
import com.jupiter.europa.io.FileLocations
import com.jupiter.europa.world.Level
import com.jupiter.ganymede.event.Listener
import java.awt.Point
import java.awt.Rectangle
import kotlin.properties.Delegates
/**
* Created by nathan on 5/25/15.
*/
Spell(characterClass = javaClass<Magus>(), level = 1)
public class JumpSpell(private val entity: Entity) : Ability {
// Public Methods
override val name: String = "Jump"
override val description: String = "Jumps to any point within 30 feet."
override val cost: Cost = COST
override val category: AbilityCategory = SpellCategories.LEVEL_ONE
override val icon: TextureRegion = INNER_ICON
override val action: Action = object : Action(this.entity), Listener<Message> {
override val targets: List<(Level, Point) -> Boolean> = listOf(
{ level, point ->
if (Families.positionables.matches(entity)) {
val currentPosition = Mappers.position[this.entity].tilePosition
val dist = Math.abs(currentPosition.x - point.x) + Math.abs(currentPosition.y - point.y)
if (dist <= RANGE) {
val rect = Rectangle(point.x, point.y, 1, 1)
!level.collides(rect)
} else {
false
}
} else {
false
}
}
)
override fun apply(targets: List<Point>) {
EuropaGame.game.messageSystem.subscribe(this, javaClass<TeleportCompleteMessage>())
EuropaGame.game.messageSystem.publish(TeleportRequestMessage(entity, targets[0]))
}
override fun handle(message: Message) {
if (message is TeleportCompleteMessage && message.entity === entity) {
EuropaGame.game.messageSystem.unsubscribe(this, javaClass<TeleportCompleteMessage>())
this.complete()
}
}
}
companion object {
// Static Members
private val COST = Cost.constant(ResourceComponent.Resources.MANA, 1)
private val INNER_ICON: TextureRegion by Delegates.lazy({ EuropaGame.game.assetManager!!.get(FileLocations.ICON_ATLAS, javaClass<TextureAtlas>()).findRegion("jump-spell") })
public val RANGE: Int = 6
}
}
| mit | d05b2a926601a44c7e9f7805ae53b07a | 41.598039 | 181 | 0.690219 | 4.507261 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/ide/intentions/RemoveCurlyBracesIntention.kt | 2 | 2768 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.isSelf
import org.rust.lang.core.psi.ext.parentOfType
/**
* Removes the curly braces on singleton imports, changing from this
*
* ```
* import std::{mem};
* ```
*
* to this:
*
* ```
* import std::mem;
* ```
*/
class RemoveCurlyBracesIntention : RsElementBaseIntentionAction<RemoveCurlyBracesIntention.Context>() {
override fun getText() = "Remove curly braces"
override fun getFamilyName() = text
data class Context(
val useItem: RsUseItem,
val usePath: RsPath,
val useGlobList: RsUseGlobList,
val useGlobIdentifier: PsiElement
)
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): RemoveCurlyBracesIntention.Context? {
val useItem = element.parentOfType<RsUseItem>() ?: return null
val useItemPath = useItem.path ?: return null
val useGlobList = useItem.useGlobList ?: return null
if (useGlobList.children.size != 1) return null
val listItem = useGlobList.children[0]
if (listItem !is RsUseGlob || listItem.isSelf) return null
return Context(
useItem,
useItemPath,
useGlobList,
listItem
)
}
override fun invoke(project: Project, editor: Editor, ctx: Context) {
val (useItem, path, globList, identifier) = ctx
// Save the cursor position, adjusting for curly brace removal
val caret = editor.caretModel.offset
val newOffset = when {
caret < identifier.textOffset -> caret
caret < identifier.textOffset + identifier.textLength -> caret - 1
else -> caret - 2
}
// Conjure up a new use item to make a new path containing the
// identifier we want; then grab the relevant parts
val newUseItem = RsPsiFactory(project).createUseItem("dummy::${identifier.text}")
val newPath = newUseItem.path ?: return
val newSubPath = newPath.path ?: return
val newAlias = newUseItem.alias
// Attach the identifier to the old path, then splice that path into
// the use item. Delete the old glob list and attach the alias, if any.
newSubPath.replace(path.copy())
path.replace(newPath)
useItem.coloncolon?.delete()
globList.delete()
newAlias?.let { useItem.addBefore(it, useItem.semicolon) }
editor.caretModel.moveToOffset(newOffset)
}
}
| mit | bd408b0be409942ef5b3a74fd9656ae2 | 31.952381 | 132 | 0.658598 | 4.421725 | false | false | false | false |
john9x/jdbi | kotlin/src/main/kotlin/org/jdbi/v3/core/kotlin/Jdbi858Extensions.kt | 2 | 6556 | /*
* 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.jdbi.v3.core.kotlin
import org.jdbi.v3.core.Handle
import org.jdbi.v3.core.HandleCallback
import org.jdbi.v3.core.HandleConsumer
import org.jdbi.v3.core.Jdbi
import org.jdbi.v3.core.extension.ExtensionCallback
import org.jdbi.v3.core.extension.ExtensionConsumer
import org.jdbi.v3.core.transaction.TransactionIsolationLevel
import kotlin.reflect.KClass
// The extensions in this file were created in response to these issues :
// https://github.com/jdbi/jdbi/issues/858
// https://youtrack.jetbrains.com/issue/KT-5464
// These extensions are temporary and will be removed when Kotlin's type inference
// is improved and this isn't an issue anymore.
/**
* Temporary extension function for [Jdbi.withHandle].
*
* This function WILL be deprecated and removed when not needed anymore.
*
* @see <a href="https://github.com/jdbi/jdbi/issues/858">Github issue</a>
* @see <a href="https://youtrack.jetbrains.com/issue/KT-5464">Kotlin issue</a>
* @see [Jdbi.withHandle]
*/
inline fun <R> Jdbi.withHandleUnchecked(crossinline block: (Handle) -> R): R {
return withHandle(HandleCallback<R, RuntimeException> { handle ->
block(handle)
})
}
/**
* Temporary extension function for [Jdbi.useHandle].
*
* This function WILL be deprecated and removed when not needed anymore.
*
* @see <a href="https://github.com/jdbi/jdbi/issues/858">Github issue</a>
* @see <a href="https://youtrack.jetbrains.com/issue/KT-5464">Kotlin issue</a>
* @see [Jdbi.useHandle]
*/
inline fun Jdbi.useHandleUnchecked(crossinline block: (Handle) -> Unit) {
useHandle(HandleConsumer<RuntimeException> { handle ->
block(handle)
})
}
/**
* Temporary extension function for [Jdbi.inTransaction].
*
* This function WILL be deprecated and removed when not needed anymore.
*
* @see <a href="https://github.com/jdbi/jdbi/issues/858">Github issue</a>
* @see <a href="https://youtrack.jetbrains.com/issue/KT-5464">Kotlin issue</a>
* @see [Jdbi.inTransaction]
*/
inline fun <R> Jdbi.inTransactionUnchecked(crossinline block: (Handle) -> R): R {
return inTransaction(HandleCallback<R, RuntimeException> { handle ->
block(handle)
})
}
/**
* Temporary extension function for [Jdbi.useTransaction].
*
* This function WILL be deprecated and removed when not needed anymore.
*
* @see <a href="https://github.com/jdbi/jdbi/issues/858">Github issue</a>
* @see <a href="https://youtrack.jetbrains.com/issue/KT-5464">Kotlin issue</a>
* @see [Jdbi.useTransaction]
*/
inline fun Jdbi.useTransactionUnchecked(crossinline block: (Handle) -> Unit) {
useTransaction(HandleConsumer<RuntimeException> { handle ->
block(handle)
})
}
/**
* Temporary extension function for [Jdbi.inTransaction].
*
* This function WILL be deprecated and removed when not needed anymore.
*
* @see <a href="https://github.com/jdbi/jdbi/issues/858">Github issue</a>
* @see <a href="https://youtrack.jetbrains.com/issue/KT-5464">Kotlin issue</a>
* @see [Jdbi.inTransaction]
*/
inline fun <R> Jdbi.inTransactionUnchecked(level: TransactionIsolationLevel, crossinline block: (Handle) -> R): R {
return inTransaction(level, HandleCallback<R, RuntimeException> { handle ->
block(handle)
})
}
/**
* Temporary extension function for [Jdbi.useTransaction].
*
* This function WILL be deprecated and removed when not needed anymore.
*
* @see <a href="https://github.com/jdbi/jdbi/issues/858">Github issue</a>
* @see <a href="https://youtrack.jetbrains.com/issue/KT-5464">Kotlin issue</a>
* @see [Jdbi.useTransaction]
*/
inline fun Jdbi.useTransactionUnchecked(level: TransactionIsolationLevel, crossinline block: (Handle) -> Unit) {
useTransaction(level, HandleConsumer<RuntimeException> { handle ->
block(handle)
})
}
/**
* Temporary extension function for [Jdbi.withExtension].
*
* This function WILL be deprecated and removed when not needed anymore.
*
* @see <a href="https://github.com/jdbi/jdbi/issues/858">Github issue</a>
* @see <a href="https://youtrack.jetbrains.com/issue/KT-5464">Kotlin issue</a>
* @see [Jdbi.withExtension]
*/
inline fun <E, R> Jdbi.withExtensionUnchecked(extensionType: Class<E>, crossinline callback: (E) -> R): R {
return withExtension(extensionType, ExtensionCallback<R, E, RuntimeException> { dao ->
callback(dao)
})
}
/**
* Temporary extension function for [Jdbi.withExtension].
*
* This function WILL be deprecated and removed when not needed anymore.
*
* @see <a href="https://github.com/jdbi/jdbi/issues/858">Github issue</a>
* @see <a href="https://youtrack.jetbrains.com/issue/KT-5464">Kotlin issue</a>
* @see [Jdbi.withExtension]
*/
inline fun <E: Any, R> Jdbi.withExtensionUnchecked(extensionType: KClass<E>, crossinline callback: (E) -> R): R {
return withExtension(extensionType, ExtensionCallback<R, E, RuntimeException> { dao ->
callback(dao)
})
}
/**
* Temporary extension function for [Jdbi.useExtension].
*
* This function WILL be deprecated and removed when not needed anymore.
*
* @see <a href="https://github.com/jdbi/jdbi/issues/858">Github issue</a>
* @see <a href="https://youtrack.jetbrains.com/issue/KT-5464">Kotlin issue</a>
* @see [Jdbi.useExtension]
*/
inline fun <E> Jdbi.useExtensionUnchecked(extensionType: Class<E>, crossinline callback: (E) -> Unit) {
useExtension(extensionType, ExtensionConsumer<E, RuntimeException> { dao ->
callback(dao)
})
}
/**
* Temporary extension function for [Jdbi.useExtension].
*
* This function WILL be deprecated and removed when not needed anymore.
*
* @see <a href="https://github.com/jdbi/jdbi/issues/858">Github issue</a>
* @see <a href="https://youtrack.jetbrains.com/issue/KT-5464">Kotlin issue</a>
* @see [Jdbi.useExtension]
*/
inline fun <E: Any> Jdbi.useExtensionUnchecked(extensionType: KClass<E>, crossinline callback: (E) -> Unit) {
useExtension(extensionType, ExtensionConsumer<E, RuntimeException> { dao ->
callback(dao)
})
}
| apache-2.0 | cc36f593f7d74f261db4f6fa6d4a7562 | 35.422222 | 115 | 0.71385 | 3.534232 | false | false | false | false |
msebire/intellij-community | plugins/devkit/devkit-core/src/inspections/missingApi/MissingRecentApiInspection.kt | 1 | 3314 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.devkit.inspections.missingApi
import com.intellij.codeInspection.AbstractBaseJavaLocalInspectionTool
import com.intellij.codeInspection.InspectionProfileEntry
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.util.BuildNumber
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.xml.XmlFile
import org.jetbrains.idea.devkit.actions.DevkitActionsUtil
import org.jetbrains.idea.devkit.module.PluginModuleType
import org.jetbrains.idea.devkit.util.DescriptorUtil
import org.jetbrains.idea.devkit.util.PsiUtil
/**
* Inspection that warns plugin authors if they use IntelliJ Platform's APIs that aren't available
* in some IDE versions specified as compatible with the plugin via the "since-until" constraints.
*
* Suppose a plugin specifies `183.1; 181.9` as compatibility range, but some IntelliJ Platform's API
* in use appeared only in `183.5`. Then the plugin won't work in `[181.1, 181.5)`
* and this inspection's goal is to prevent it.
*
* *Implementation details*.
* Info on when APIs were first introduced is obtained from "available since" artifacts.
* They are are built on the build server for each IDE build and uploaded to
* [IntelliJ artifacts repository](https://www.jetbrains.com/intellij-repository/releases/),
* containing external annotations [org.jetbrains.annotations.ApiStatus.AvailableSince]
* where APIs' introduction versions are specified.
*/
class MissingRecentApiInspection : AbstractBaseJavaLocalInspectionTool() {
companion object {
val INSPECTION_SHORT_NAME = InspectionProfileEntry.getShortName(MissingRecentApiInspection::class.simpleName!!)
}
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
if (PsiUtil.isIdeaProject(holder.project)) {
return PsiElementVisitor.EMPTY_VISITOR
}
val module = ModuleUtil.findModuleForPsiElement(holder.file) ?: return PsiElementVisitor.EMPTY_VISITOR
val targetedSinceUntilRanges = getTargetedSinceUntilRanges(module)
if (targetedSinceUntilRanges.isEmpty()) {
return PsiElementVisitor.EMPTY_VISITOR
}
return MissingRecentApiVisitor(holder, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, targetedSinceUntilRanges)
}
private fun getTargetedSinceUntilRanges(module: Module): List<SinceUntilRange> {
return DevkitActionsUtil.getCandidatePluginModules(module)
.mapNotNull { PluginModuleType.getPluginXml(it) }
.mapNotNull { getSinceUntilRange(it) }
.filterNot { it.sinceBuild == null }
}
private fun getSinceUntilRange(pluginXml: XmlFile): SinceUntilRange? {
val ideaPlugin = DescriptorUtil.getIdeaPlugin(pluginXml) ?: return null
val ideaVersion = ideaPlugin.rootElement.ideaVersion
val sinceBuild = ideaVersion.sinceBuild.stringValue.orEmpty().let { BuildNumber.fromStringOrNull(it) }
val untilBuild = ideaVersion.untilBuild.stringValue.orEmpty().let { BuildNumber.fromStringOrNull(it) }
return SinceUntilRange(sinceBuild, untilBuild)
}
} | apache-2.0 | fd41ac03f0c1a27e19e3b6e8c5ac1164 | 49.227273 | 140 | 0.795413 | 4.508844 | false | false | false | false |
Aptoide/aptoide-client-v8 | aptoide-views/src/main/java/cm/aptoide/aptoideviews/recyclerview/GridItemSpacingDecorator.kt | 1 | 832 | package cm.aptoide.aptoideviews.recyclerview
import android.graphics.Rect
import android.view.View
import androidx.annotation.Px
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
class GridItemSpacingDecorator(@Px var spacingPx: Int = 0) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView,
state: RecyclerView.State) {
outRect.setEmpty()
val layout = parent.layoutManager as GridLayoutManager
val position = parent.getChildAdapterPosition(view)
val row: Int = position / layout.spanCount
val marginLeft = if (position % layout.spanCount != 0) spacingPx else 0
val marginTop = if (row != 0) spacingPx else 0
outRect.set(marginLeft, marginTop, 0, 0)
}
} | gpl-3.0 | e5a1f7c0d5479925344eba98780e7f3d | 32.32 | 92 | 0.740385 | 4.648045 | false | false | false | false |
Gu3pardo/PasswordSafe-AndroidClient | mobile/src/main/java/guepardoapps/passwordsafe/extensions/StringExtension.kt | 1 | 1132 | package guepardoapps.passwordsafe.extensions
import androidx.annotation.NonNull
import guepardoapps.passwordsafe.common.Constants
internal fun String.occurenceCount(@NonNull find: String): Int {
var lastIndex = 0
var count = 0
while (lastIndex != -1) {
lastIndex = this.indexOf(find, lastIndex)
if (lastIndex != -1) {
count++
lastIndex += find.length
}
}
return count
}
internal fun String.charPositions(char: Char): List<Int> {
return this
.mapIndexed { index, c -> if (c == char) index else -1 }
.filter { x -> x != -1 }
}
internal fun String.obfuscate(char: Char): String {
return this.obfuscate(char.toString())
}
internal fun String.obfuscate(string: String): String {
return this.replace(Regex(Constants.Regex.Point), string)
}
internal fun Array<String>.areEqual(): Boolean {
return this.all { x -> this.all { y -> x == y } }
}
internal fun Array<String>.excludeAndFindString(@NonNull exclude: String, @NonNull find: String): String? {
return this.find { x -> !x.contains(exclude) && x.contains(find) }
} | mit | 5527687c4b0e608a651ff7063430abc0 | 26.634146 | 107 | 0.64841 | 3.863481 | false | false | false | false |
andersonlucasg3/SpriteKit-Android | SpriteKitLib/src/main/java/br/com/insanitech/spritekit/graphics/SKSize.kt | 1 | 1021 | package br.com.insanitech.spritekit.graphics
import br.com.insanitech.spritekit.opengl.model.GLSize
/**
* Created by anderson on 7/4/15.
*/
class SKSize {
internal val size: GLSize
var width: Float
get() = this.size.width
set(value) { this.size.width = value }
var height: Float
get() = this.size.height
set(value) { this.size.height = value }
constructor() {
this.size = GLSize()
}
constructor(width: Float, height: Float) {
this.size = GLSize(width, height)
}
constructor(other: SKSize) : this(other.size)
internal constructor(other: GLSize) : this(other.width, other.height)
internal constructor(other: GLSize, reference: Boolean) {
if (reference) this.size = other
else this.size = GLSize(other.width, other.height)
}
override fun toString(): String = "{ w: ${this.width}, h: ${this.height} }"
internal fun assignByValue(size: SKSize) {
this.size.assignByValue(size.size)
}
}
| bsd-3-clause | 0b7ce84d527d7cc0e8af489c18a4eb09 | 23.902439 | 79 | 0.630754 | 3.646429 | false | false | false | false |
harningt/atomun-keygen | src/main/java/us/eharning/atomun/keygen/KeyGeneratorBuilder.kt | 1 | 3605 | /*
* Copyright 2015, 2017 Thomas Harning Jr. <[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 us.eharning.atomun.keygen
import com.google.common.collect.ImmutableList
import us.eharning.atomun.core.ValidationException
import us.eharning.atomun.keygen.internal.spi.bip0032.BIP0032KeyGeneratorServiceProvider
import us.eharning.atomun.keygen.internal.spi.bip0032.BIP0044KeyGeneratorServiceProvider
import us.eharning.atomun.keygen.spi.BuilderParameter
import us.eharning.atomun.keygen.spi.KeyGeneratorBuilderSpi
import java.util.*
/**
* Builder class to help simplify the process of setting up key generators.
*/
class KeyGeneratorBuilder private constructor(
private val spi: KeyGeneratorBuilderSpi
) {
/* Current known number of parameters - internal detail.
* Current slot dictates:
* 1 - seed
* 2 - path
*/
private val parameters = arrayOfNulls<BuilderParameter>(2)
/**
* Build a key generator with the applied configuration.
*
* @return a key generator.
*/
@Throws(ValidationException::class)
fun build(): DeterministicKeyGenerator {
try {
spi.validate(*parameters)
} catch (e: Exception) {
throw IllegalStateException(e)
}
return spi.createGenerator(*parameters)
}
/**
* Set the seed for the key generator builder.
*
* @param seedParameter
* algorithmic base for the keys.
*
* @return self.
*/
fun setSeed(seedParameter: SeedParameter): KeyGeneratorBuilder {
this.parameters[0] = seedParameter
spi.validate(*parameters)
return this
}
/**
* Set the path used to derive the final builder from the base.
*
* @param pathParameter
* base path to use.
*
* @return self.
*/
fun setPath(pathParameter: PathParameter): KeyGeneratorBuilder {
this.parameters[1] = pathParameter
spi.validate(*parameters)
return this
}
/**
* Reset the builder to a clean state for clean re-use.
*
* @return self.
*/
fun reset(): KeyGeneratorBuilder {
Arrays.fill(parameters, null)
return this
}
companion object {
private val SERVICE_PROVIDERS = ImmutableList.of(
BIP0032KeyGeneratorServiceProvider(),
BIP0044KeyGeneratorServiceProvider()
)
/**
* Create a new builder for the given algorithm.
* @param algorithm
* type of builder to return.
*
* @return a builder instance.
*/
@JvmStatic
fun newBuilder(algorithm: KeyGeneratorAlgorithm): KeyGeneratorBuilder {
for (provider in SERVICE_PROVIDERS) {
val spi = provider.getKeyGeneratorBuilder(algorithm)
if (null != spi) {
return KeyGeneratorBuilder(spi)
}
}
throw UnsupportedOperationException("Unsupported algorithm: " + algorithm)
}
}
}
| apache-2.0 | 7c37123d14ca0178b3870fd48e6fa2a4 | 29.550847 | 88 | 0.643273 | 4.657623 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/ui/FeedFilterFormatter.kt | 1 | 4791 | package com.pr0gramm.app.ui
import android.content.Context
import com.pr0gramm.app.R
import com.pr0gramm.app.feed.FeedFilter
import com.pr0gramm.app.feed.FeedType
import com.pr0gramm.app.orm.asFeedFilter
import com.pr0gramm.app.services.BookmarkService
import com.pr0gramm.app.util.di.injector
object FeedFilterFormatter {
/**
* Simple utility function to format a [com.pr0gramm.app.feed.FeedFilter] to some
* string. The resulting value can not be parsed back or anything interesting, it is just for
* display purposes
*/
fun format(context: Context, filter: FeedFilter): FeedTitle {
val category = feedTypeToString(context, filter)
if (!filter.isBasic) {
// TODO improve formatting logic
filter.tags?.let { tags ->
// 'Katze in Top'
val tagsClean = cleanTags(tags)
return FeedTitle(category, tagsClean, "$tagsClean in $category")
}
filter.collectionTitle?.let { collectionTitle ->
val titleCollectionOf =
context.getString(R.string.filter_format_collection_of, collectionTitle, filter.username)
return FeedTitle(titleCollectionOf, subtitle = "", singleline = titleCollectionOf)
}
filter.username?.let { username ->
val title = when (filter.feedType) {
FeedType.NEW -> context.getString(R.string.uploads)
else -> context.getString(R.string.uploads_in, category)
}
val subtitle = context.getString(R.string.filter_format_tag_by) + " " + username
return FeedTitle(title, subtitle, "$subtitle in $category")
}
}
return FeedTitle(feedTypeToString(context, filter), "", "")
}
fun feedTypeToString(context: Context, filter: FeedFilter): String {
if (filter.collectionTitle != null && filter.username != null) {
return context.getString(R.string.collection_x_of_user, filter.collectionTitle, filter.username)
}
if (filter.username != null) {
return context.getString(R.string.uploads_of, filter.username)
}
return when (filter.feedType) {
FeedType.NEW -> context.getString(R.string.filter_format_new)
FeedType.BESTOF -> context.getString(R.string.filter_format_bestof)
FeedType.RANDOM -> context.getString(R.string.filter_format_random)
FeedType.STALK -> context.getString(R.string.filter_format_premium)
FeedType.PROMOTED -> context.getString(R.string.filter_format_top)
FeedType.CONTROVERSIAL -> context.getString(R.string.filter_format_controversial)
}
}
fun toTitle(context: Context, filter: FeedFilter): TitleFragment.Title {
// format the current filter
val formatted = format(context, filter)
// get a more specific title from a bookmark if possible
val bookmarkTitle = bookmarkTitleOf(context, filter)
return when {
bookmarkTitle != null ->
TitleFragment.Title(bookmarkTitle, context.getString(R.string.bookmark))
else ->
TitleFragment.Title(formatted.title, formatted.subtitle, useSubtitleInTitle = true)
}
}
private fun bookmarkTitleOf(context: Context, filter: FeedFilter): String? {
val bookmarkService: BookmarkService = context.injector.instance()
val directTitle = bookmarkService.byFilter(filter)?.title
if (directTitle != null) {
return directTitle
}
// check if the filter might match the inverse of any bookmark
val bookmarkInverse = bookmarkService.all.firstOrNull { bookmark ->
filter == bookmark.asFeedFilter().invert()
}
if (bookmarkInverse != null) {
return context.getString(R.string.bookmark_inverse_title, bookmarkInverse.title)
}
return null
}
private fun cleanTags(tags: String): String {
var result = tags.trimStart('?', '!').trim()
result = trim(result, '(', ')').trim()
result = trim(result, '"', '"').trim()
result = trim(result, '\'', '\'').trim()
result = result.replace(" ([|&-]) ".toRegex(), "$1").trim()
return result
}
private fun trim(text: String, left: Char, right: Char): String {
if (!text.startsWith(left) || !text.endsWith(right) || text.length <= 2)
return text
val mid = text.substring(1, text.lastIndex)
if (left in mid || right in mid) {
return text
}
return mid
}
class FeedTitle(val title: String, val subtitle: String, val singleline: String)
}
| mit | 96ee98448bb757ae333cf7176610ac4e | 36.429688 | 109 | 0.618451 | 4.37135 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.