repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
drimachine/grakmat | src/main/kotlin/org/drimachine/grakmat/PredefinedRules.kt | 1 | 6834 | /*
* Copyright (c) 2016 Drimachine.org
*
* 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.
*/
@file:JvmName("PredefinedRules")
package org.drimachine.grakmat
val SEMICOLON: Parser<Char> = char(';')
.withName("';'")
val COLON: Parser<Char> = char(':')
.withName("':'")
val DOUBLE_QUOTE: Parser<Char> = char('\"')
.withName("'\"'")
val QUOTE: Parser<Char> = char('\'')
.withName("'\\''")
val ASTERISK: Parser<Char> = char('*')
.withName("'*'")
val LEFT_BRACKET: Parser<Char> = char('[')
.withName("'['")
val RIGHT_BRACKET: Parser<Char> = char(']')
.withName("']'")
val LEFT_BRACE: Parser<Char> = char('{')
.withName("'{'")
val RIGHT_BRACE: Parser<Char> = char('}')
.withName("'}'")
val CARET: Parser<Char> = char('^')
.withName("'^'")
val COMMA: Parser<Char> = char(',')
.withName("','")
val MINUS: Parser<Char> = char('-')
.withName("'-'")
val PLUS: Parser<Char> = char('+')
.withName("'+'")
val SLASH: Parser<Char> = char('/')
.withName("'/'")
val BACKSLASH: Parser<Char> = char('\\')
.withName("'\\'")
val GREATER_THAN_SIGN: Parser<Char> = char('>')
.withName("'>'")
val LESS_THAN_SIGN: Parser<Char> = char('<')
.withName("'<'")
val LEFT_PAREN: Parser<Char> = char('(')
.withName("'('")
val RIGHT_PAREN: Parser<Char> = char(')')
.withName("')'")
val DOT: Parser<Char> = char('.')
.withName("'.'")
val UNDERSCORE: Parser<Char> = char('_')
.withName("'_'")
val VERTICAL_BAR: Parser<Char> = char('|')
.withName("'|'")
val AMPERSAND: Parser<Char> = char('&')
.withName("'&'")
val QUESTION_MARK: Parser<Char> = char('?')
.withName("'?'")
val EQUALS_SIGN: Parser<Char> = char('=')
.withName("'='")
val EXCLAMATION_MARK: Parser<Char> = char('!')
.withName("'!'")
val AT_SIGN: Parser<Char> = char('@')
.withName("'@'")
val HASH: Parser<Char> = char('#')
.withName("'#'")
val DIGIT: Parser<Char> = anyOf('0'..'9')
.withName("DIGIT")
val NUMBER: Parser<String> = (oneOrMore(DIGIT))
.map { digits: List<Char> -> digits.joinToString("") }
.withName("NUMBER")
val IDENTIFIER: Parser<String> = oneOrMore(anyOf(('a'..'z') + ('A'..'Z') + ('0'..'9') + '_'))
.map { it: List<Char> -> it.joinToString("") }
.withName("IDENTIFIER")
object Numbers {
private fun <A> listOf(head: A, tail: List<A>): List<A> = arrayListOf(head).apply { addAll(tail) }
private fun List<Char>.digitsToInt(): Int {
val (multiplier: Int, result: Int) =
this.foldRight(1 to 0) { digit: Char, (multiplier: Int, result: Int) ->
(multiplier * 10) to (result + Character.getNumericValue(digit) * multiplier) }
return result
}
// fragment zeroInteger: (Int) = '0' { ... };
private val zeroInteger: Parser<Int> = char('0') map { 0 }
// POSITIVE_INTEGER: (Int) = [1-9] ([0-9])* { ... };
val POSITIVE_INTEGER: Parser<Int> = (anyOf('1'..'9') and zeroOrMore(DIGIT))
.map { (headDigit: Char, tailDigits: List<Char>) -> listOf(headDigit, tailDigits).digitsToInt() }
.withName("POSITIVE INTEGER")
// fragment zeroOrPositiveInteger: (Int) = zeroInteger | positiveInteger;
private val zeroOrPositiveInteger: Parser<Int> = zeroInteger or POSITIVE_INTEGER
// INTEGER: (Int) = ('-')? positiveInteger { ... };
val INTEGER: Parser<Int> = (optional(char('-')) and zeroOrPositiveInteger)
.map { (minus: Char?, integer: Int) ->
if (minus == null) integer else -integer }
.withName("INTEGER")
// fragment exp: (Pair<Char, Int>) = [Ee] > ([+\-])? positiveInteger { ... };
private val exp: Parser<Pair<Char, Int>> = (anyOf('E', 'e') then optional(anyOf('+', '-')) and zeroOrPositiveInteger)
.map { (operator: Char?, integer: Int) ->
if (operator == null) '+' to integer else operator to integer }
// fragment zeroOrPositiveFloating: (Double) = INTEGER < '.' (DIGIT)+ { ... };
@Suppress("RemoveCurlyBracesFromTemplate")
private val zeroOrPositiveFloating: Parser<Double> = (INTEGER before DOT and oneOrMore(DIGIT))
.map { (integer: Int, fracDigits: List<Char>) ->
"${integer}.${fracDigits.joinToString("")}".toDouble() }
// fragment floatingWithExp: (Number) = FLOATING (exp)? { ... };
private val floatingWithExp: Parser<Double> = (zeroOrPositiveFloating and optional(exp))
.map { (floating: Double, exp: Pair<Char, Int>?) ->
if (exp != null) {
val (expOperator: Char, expInt: Int) = exp
if (expOperator == '+')
(floating * Math.pow(10.0, expInt.toDouble()))
else // expOperator will be always '-'
(floating / Math.pow(10.0, expInt.toDouble()))
} else {
floating
}
}
// FLOATING: (Double) = ('-')? positiveInteger { ... };
val FLOATING: Parser<Double> = (optional(char('-')) and floatingWithExp)
.map { (minus: Char?, floating: Double) ->
if (minus == null) floating else -floating }
.withName("FLOATING")
// fragment numberFromInteger: (Number) = INTEGER (exp)? { ... };
@Suppress("USELESS_CAST")
private val numberFromInteger: Parser<Number> = (INTEGER and optional(exp))
.map { (integer: Int, exp: Pair<Char, Int>?) ->
// Compiler implicitly casts Double and Int results to Any, so I have to use explicit cast
if (exp != null) {
val (expOperator: Char, expInt: Int) = exp
if (expOperator == '+')
(integer.toDouble() * Math.pow(10.0, expInt.toDouble())) as Number // <-- Double
else // expOperator will be always '-'
(integer.toDouble() / Math.pow(10.0, expInt.toDouble())) as Number // <-- Double
} else {
integer as Number // <-- Int
}
}
// NUMBER: (Number) = FLOATING | numberFromInteger;
val NUMBER: Parser<Number> = (FLOATING or numberFromInteger)
.withName("NUMBER")
}
| apache-2.0 | 20ac7585ff44ab023e4c3cf50e39eb4b | 42.253165 | 121 | 0.555604 | 3.964037 | false | false | false | false |
asymmetric-team/secure-messenger-android | exchange-symmetric-key-core/src/test/java/com/safechat/conversation/symmetrickey/post/PostSymmetricKeyControllerTest.kt | 1 | 3293 | package com.safechat.conversation.symmetrickey.post
import com.nhaarman.mockito_kotlin.*
import org.junit.Before
import org.junit.Test
import rx.Observable.error
import rx.Observable.just
import rx.observers.TestSubscriber
class PostSymmetricKeyControllerTest {
val service = mock<PostSymmetricKeyService>()
val repository = mock<PostSymmetricKeyRepository>()
val encryptor = mock<PostSymmetricKeyEncryptor>()
val controller = PostSymmetricKeyControllerImpl(encryptor, repository, service)
val subscriber = TestSubscriber<Unit>()
@Before
fun setUp() {
stubGenerator()
stubRepository()
stubService()
}
@Test
fun shouldGenerateKey() {
startController()
verify(encryptor).generateSymmetricKey()
}
@Test
fun shouldSaveGeneratedKey() {
startController()
verify(repository).saveDecryptedSymmetricKey("otherPublicKey", "newSymmetricKey")
}
@Test
fun shouldEncryptGeneratedKey() {
startController()
verify(encryptor).encryptSymmetricKey("otherPublicKey", "myPrivateKey", "newSymmetricKey")
}
@Test
fun shouldPostEncryptedKey() {
startController()
verify(service).postSymmetricKey("myPublicKey", "otherPublicKey", "encryptedSymmetricKey")
}
@Test
fun shouldNotSaveKeyIfPostFails() {
whenever(service.postSymmetricKey(any(), any(), any())).thenReturn(error(RuntimeException()))
startController()
verify(repository, never()).saveDecryptedSymmetricKey(any(), any())
}
@Test
fun shouldReturnErrorIfPostFails() {
val runtimeException = RuntimeException()
whenever(service.postSymmetricKey(any(), any(), any())).thenReturn(error(runtimeException))
startController()
subscriber.assertError(runtimeException)
}
@Test
fun shouldReturnErrorIfGenerationFails() {
val runtimeException = RuntimeException()
whenever(encryptor.generateSymmetricKey()).thenReturn(error(runtimeException))
startController()
subscriber.assertError(runtimeException)
}
@Test
fun shouldReturnErrorIfEncryptionFails() {
val runtimeException = RuntimeException()
whenever(encryptor.encryptSymmetricKey(any(), any(), any())).thenReturn(error(runtimeException))
startController()
subscriber.assertError(runtimeException)
}
@Test
fun shouldReturnUnitIfEverythingGoesRight() {
startController()
subscriber.assertValue(Unit)
}
private fun startController() {
controller.postKey("otherPublicKey").subscribe(subscriber)
}
private fun stubGenerator() {
whenever(encryptor.encryptSymmetricKey("otherPublicKey", "myPrivateKey", "newSymmetricKey")).thenReturn(just("encryptedSymmetricKey"))
whenever(encryptor.generateSymmetricKey()).thenReturn(just("newSymmetricKey"))
}
private fun stubRepository() {
whenever(repository.getPublicKeyString()).thenReturn("myPublicKey")
whenever(repository.getPrivateKeyString()).thenReturn("myPrivateKey")
}
private fun stubService() {
whenever(service.postSymmetricKey("myPublicKey", "otherPublicKey", "encryptedSymmetricKey")).thenReturn(just(Unit))
}
} | apache-2.0 | e805c9938217c6f92d4cc030730a2d60 | 30.980583 | 142 | 0.700881 | 5.425041 | false | true | false | false |
ankidroid/Anki-Android | AnkiDroid/src/test/java/com/ichi2/anki/servicelayer/scopedstorage/OperationTest.kt | 1 | 4300 | /*
* Copyright (c) 2022 David Allison <[email protected]>
* Copyright (c) 2022 Arthur Milchior <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.anki.servicelayer.scopedstorage
import com.ichi2.anki.servicelayer.scopedstorage.migrateuserdata.MigrateUserData.*
import com.ichi2.anki.servicelayer.scopedstorage.migrateuserdata.MigrateUserData.Operation
import com.ichi2.compat.CompatHelper
import com.ichi2.testutils.TestException
import com.ichi2.testutils.createTransientDirectory
import org.mockito.invocation.InvocationOnMock
import org.mockito.kotlin.any
import org.mockito.kotlin.doAnswer
import org.mockito.kotlin.spy
import org.mockito.kotlin.whenever
import timber.log.Timber
import java.io.File
interface OperationTest {
val executionContext: MockMigrationContext
/** Helper function: executes an [Operation] and all sub-operations */
fun executeAll(vararg ops: Operation) =
MockExecutor(ArrayDeque(ops.toList())) { executionContext }
.execute()
/**
* Executes an [Operation] without executing the sub-operations
* @return the sub-operations returned from the execution of the operation
*/
fun Operation.execute(): List<Operation> = this.execute(executionContext)
/** Creates an empty TMP directory to place the output files in */
fun generateDestinationDirectoryRef(): File {
val createDirectory = createTransientDirectory()
Timber.d("test: deleting $createDirectory")
CompatHelper.compat.deleteFile(createDirectory)
return createDirectory
}
/**
* Allow to get a MoveDirectoryContent that works for at most three files and fail on the second one.
* It keeps track of which files is the failed one and which are before and after; since directory can list its file in
* any order, it ensure that we know which file failed. It also allows to test that move still occurs after a failure.
*/
class SpyMoveDirectoryContent(private val moveDirectoryContent: MoveDirectoryContent) {
/**
* The first file moved, before the failed file. Null if no moved occurred.
*/
var beforeFile: File? = null
private set
/**
* The second file, it moves fails. Null if no moved occurred.
*/
var failedFile: File? = null // ensure the second file fails
private set
/**
* The last file moved, after the failed file. Null if no moved occurred.
*/
var afterFile: File? = null
private set
var movesProcessed = 0
private set
fun toMoveOperation(op: InvocationOnMock): Operation {
val sourceFile = op.arguments[0] as File
when (movesProcessed++) {
0 -> beforeFile = sourceFile
1 -> {
failedFile = sourceFile
return FailMove()
}
2 -> afterFile = sourceFile
else -> throw IllegalStateException("only 3 files expected")
}
return op.callRealMethod() as Operation
}
/**
* The [MoveDirectoryContent] that performs the action mentioned in the class description.
*/
val spy: MoveDirectoryContent
get() = spy(moveDirectoryContent) {
doAnswer { toMoveOperation(it) }.whenever(it).toMoveOperation(any())
}
}
}
/** A move operation which fails */
class FailMove : Operation() {
override fun execute(context: MigrationContext): List<Operation> {
throw TestException("should fail but not crash")
}
}
| gpl-3.0 | 4c4d6e9771ae4b6bef04540475b0d110 | 38.449541 | 123 | 0.672791 | 4.799107 | false | true | false | false |
skatset/KotlinFXML | src/main/kotlin/eu/stosdev/Binders.kt | 1 | 635 | package eu.stosdev
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
public class bindFXML<T : Any> : ReadOnlyProperty<Any?, T> {
private var value: T? = null
public override fun getValue(thisRef: Any?, property: KProperty<*>): T {
val v = value
if (v == null) {
throw IllegalStateException("Node was not properly injected")
}
return v
}
}
public class bindOptionalFXML<T : Any> : ReadOnlyProperty<Any?, T?> {
private var value: T? = null
public override fun getValue(thisRef: Any?, property: KProperty<*>): T? {
return value
}
}
| apache-2.0 | 035b12cf4c10e9dad9e27d1c5d52d9a7 | 25.458333 | 77 | 0.64252 | 4.233333 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/model/OrderEntity.kt | 2 | 5849 | package org.wordpress.android.fluxc.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import org.wordpress.android.fluxc.model.LocalOrRemoteId.LocalId
import org.wordpress.android.fluxc.model.order.FeeLine
import org.wordpress.android.fluxc.model.order.LineItem
import org.wordpress.android.fluxc.model.order.OrderAddress
import org.wordpress.android.fluxc.model.order.ShippingLine
import org.wordpress.android.fluxc.model.order.TaxLine
import java.math.BigDecimal
@Entity(
tableName = "OrderEntity",
indices = [Index(
value = ["localSiteId", "orderId"]
)],
primaryKeys = ["localSiteId", "orderId"]
)
data class OrderEntity(
@ColumnInfo(name = "localSiteId")
val localSiteId: LocalId,
val orderId: Long,
val number: String = "", // The, order number to display to the user
val status: String = "",
val currency: String = "",
val orderKey: String = "",
val dateCreated: String = "", // ISO 8601-formatted date in UTC, e.g. 1955-11-05T14:15:00Z
val dateModified: String = "", // ISO 8601-formatted date in UTC, e.g. 1955-11-05T14:15:00Z
val total: String = "", // Complete total, including taxes
val totalTax: String = "", // The total amount of tax (from products, shipping, discounts, etc.)
val shippingTotal: String = "", // The total shipping cost (excluding tax)
val paymentMethod: String = "", // Payment method code e.g. 'cod' 'stripe'
val paymentMethodTitle: String = "", // Displayable payment method e.g. 'Cash on delivery' 'Credit Card (Stripe)'
val datePaid: String = "",
val pricesIncludeTax: Boolean = false,
val customerNote: String = "", // Note left by the customer during order submission
val discountTotal: String = "",
val discountCodes: String = "",
val refundTotal: BigDecimal = BigDecimal.ZERO, // The total refund value for this order (usually a negative number)
val billingFirstName: String = "",
val billingLastName: String = "",
val billingCompany: String = "",
val billingAddress1: String = "",
val billingAddress2: String = "",
val billingCity: String = "",
val billingState: String = "",
val billingPostcode: String = "",
val billingCountry: String = "",
val billingEmail: String = "",
val billingPhone: String = "",
val shippingFirstName: String = "",
val shippingLastName: String = "",
val shippingCompany: String = "",
val shippingAddress1: String = "",
val shippingAddress2: String = "",
val shippingCity: String = "",
val shippingState: String = "",
val shippingPostcode: String = "",
val shippingCountry: String = "",
val shippingPhone: String = "",
val lineItems: String = "",
val shippingLines: String = "",
val feeLines: String = "",
val taxLines: String = "",
val metaData: String = "", // this is a small subset of the metadata, see OrderMetaDataEntity for full metadata
@ColumnInfo(name = "paymentUrl", defaultValue = "")
val paymentUrl: String = "",
@ColumnInfo(name = "isEditable", defaultValue = "1")
val isEditable: Boolean = true
) {
companion object {
private val gson by lazy { Gson() }
}
/**
* Returns true if there are shipping details defined for this order,
* which are different from the billing details.
*
* If no separate shipping details are defined, the billing details should be used instead,
* as the shippingX properties will be empty.
*/
fun hasSeparateShippingDetails() = shippingCountry.isNotEmpty()
/**
* Returns the billing details wrapped in a [OrderAddress].
*/
fun getBillingAddress() = OrderAddress.Billing(this)
/**
* Returns the shipping details wrapped in a [OrderAddress].
*/
fun getShippingAddress() = OrderAddress.Shipping(this)
/**
* Deserializes the JSON contained in [lineItems] into a list of [LineItem] objects.
*/
fun getLineItemList(): List<LineItem> {
val responseType = object : TypeToken<List<LineItem>>() {}.type
return gson.fromJson(lineItems, responseType) as? List<LineItem> ?: emptyList()
}
/**
* Returns the order subtotal (the sum of the subtotals of each line item in the order).
*/
fun getOrderSubtotal(): Double {
return getLineItemList().sumByDouble { it.subtotal?.toDoubleOrNull() ?: 0.0 }
}
/**
* Deserializes the JSON contained in [shippingLines] into a list of [ShippingLine] objects.
*/
fun getShippingLineList(): List<ShippingLine> {
val responseType = object : TypeToken<List<ShippingLine>>() {}.type
return gson.fromJson(shippingLines, responseType) as? List<ShippingLine> ?: emptyList()
}
/**
* Deserializes the JSON contained in [feeLines] into a list of [FeeLine] objects.
*/
fun getFeeLineList(): List<FeeLine> {
val responseType = object : TypeToken<List<FeeLine>>() {}.type
return gson.fromJson(feeLines, responseType) as? List<FeeLine> ?: emptyList()
}
/**
* Deserializes the JSON contained in [taxLines] into a list of [TaxLine] objects.
*/
fun getTaxLineList(): List<TaxLine> {
val responseType = object : TypeToken<List<TaxLine>>() {}.type
return gson.fromJson(taxLines, responseType) as? List<TaxLine> ?: emptyList()
}
/**
* Deserializes the JSON contained in [metaData] into a list of [WCMetaData] objects.
*/
fun getMetaDataList(): List<WCMetaData> {
val responseType = object : TypeToken<List<WCMetaData>>() {}.type
return gson.fromJson(metaData, responseType) as? List<WCMetaData> ?: emptyList()
}
fun isMultiShippingLinesAvailable() = getShippingLineList().size > 1
}
| gpl-2.0 | b26450bcd5f5d6bf8a9376bb1e6c25db | 39.061644 | 119 | 0.668661 | 4.332593 | false | false | false | false |
youkai-app/Youkai | app/src/main/kotlin/app/youkai/data/service/Api.kt | 1 | 15876 | package app.youkai.data.service
import app.youkai.data.models.*
import app.youkai.data.remote.Client
import app.youkai.util.SerializationUtils
import app.youkai.util.ext.append
import app.youkai.util.ext.capitalizeFirstLetter
import com.github.jasminb.jsonapi.JSONAPIDocument
import com.github.jasminb.jsonapi.retrofit.JSONAPIConverterFactory
import io.reactivex.Observable
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.jackson.JacksonConverterFactory
object Api {
private val JSON_API_CONTENT_TYPE = "application/vnd.api+json"
val BASE = "https://kitsu.io/api/"
private val CLIENT_ID = "dd031b32d2f56c990b1425efe6c42ad847e7fe3ab46bf1299f05ecd856bdb7dd"
private val CLIENT_SECRET = "54d7307928f63414defd96399fc31ba847961ceaecef3a5fd93144e960c0e151"
/**
* Lazy modifier only instantiates when the value is first used.
* See: https://kotlinlang.org/docs/reference/delegated-properties.html
*/
private val converterFactory by lazy {
val converterFactory = JSONAPIConverterFactory(ResourceConverters.mainConverter)
converterFactory.setAlternativeFactory(JacksonConverterFactory.create())
converterFactory
}
private val service: Service by lazy {
val retrofit: Retrofit = Retrofit.Builder()
.client(Client)
.baseUrl(BASE)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(converterFactory)
.build()
retrofit.create(Service::class.java)
}
/**
* Authentication
*/
fun login(username: String, password: String) = service.postLogin(username, password, "password", CLIENT_ID, CLIENT_SECRET)
fun refreshAuthToken(refreshToken: String) = service.refreshAuthToken(refreshToken, "refresh_token", CLIENT_ID, CLIENT_SECRET)
private fun createAuthorizationParam(tokenType: String, authToken: String): String
= tokenType.capitalizeFirstLetter().append(authToken, " ")
/**
* Anime
*/
private val getAllAnimeCall = {
_: String, h: Map<String, String>, m: Map<String, String> ->
service.getAllAnime(m)
}
fun allAnime(): RequestBuilder<Observable<JSONAPIDocument<List<Anime>>>>
= RequestBuilder("", getAllAnimeCall)
private val getAnimeCall = {
id: String, h: Map<String, String>, m: Map<String, String> ->
service.getAnime(id, h, m)
}
fun anime(id: String): RequestBuilder<Observable<JSONAPIDocument<Anime>>>
= RequestBuilder(id, getAnimeCall)
fun searchAnime(query: String): RequestBuilder<Observable<JSONAPIDocument<List<Anime>>>>
= RequestBuilder("", getAllAnimeCall).filter("text", query)
private val getAnimeLanguagesCall = {
id: String, h: Map<String, String>, m: Map<String, String> ->
service.getAnimeLanguages(id, h, m)
}
fun languagesForAnime(animeId: String): RequestBuilder<Observable<List<String>>>
= RequestBuilder(animeId, getAnimeLanguagesCall)
private val getAnimeEpisodesCall = {
id: String, h: Map<String, String>, m: Map<String, String> ->
service.getAnimeEpisodes(id, h, m)
}
fun episodesForAnime(animeId: String): RequestBuilder<Observable<JSONAPIDocument<List<Episode>>>>
= RequestBuilder(animeId, getAnimeEpisodesCall)
private val getAnimeMediaRelationshipsCall = {
id: String, h: Map<String, String>, m: Map<String, String> ->
service.getAnimeMediaRelationships(id, h, m)
}
fun mediaRelationshipsForAnime(animeId: String): RequestBuilder<Observable<JSONAPIDocument<List<MediaRelationship>>>>
= RequestBuilder(animeId, getAnimeMediaRelationshipsCall)
/**
* Manga
*/
private val getAllMangaCall = {
_: String, h: Map<String, String>, m: Map<String, String> ->
service.getAllManga(m)
}
fun allManga(): RequestBuilder<Observable<JSONAPIDocument<List<Manga>>>>
= RequestBuilder("", getAllMangaCall)
private val getMangaCall = {
id: String, h: Map<String, String>, m: Map<String, String> ->
service.getManga(id, h, m)
}
fun manga(id: String): RequestBuilder<Observable<JSONAPIDocument<Manga>>>
= RequestBuilder(id, getMangaCall)
fun searchManga(query: String): RequestBuilder<Observable<JSONAPIDocument<List<Manga>>>>
= RequestBuilder("", getAllMangaCall).filter("text", query)
private val getMangaChaptersCall = {
id: String, h: Map<String, String>, m: Map<String, String> ->
service.getMangaChapters(id, h, m)
}
fun chaptersForManga(mangaId: String): RequestBuilder<Observable<JSONAPIDocument<List<Chapter>>>>
= RequestBuilder(mangaId, getMangaChaptersCall)
private val getMangaMediaRelationshipsCall = {
id: String, h: Map<String, String>, m: Map<String, String> ->
service.getMangaMediaRelationships(id, h, m)
}
/**
* Not implemented on server.
*/
fun mediaRelationshipsForManga(mangaId: String): RequestBuilder<Observable<JSONAPIDocument<List<MediaRelationship>>>>
= RequestBuilder(mangaId, getMangaMediaRelationshipsCall)
/**
* Library
*/
private val getAllLibraryEntriesCall = {
_: String, h: Map<String, String>, m: Map<String, String> ->
service.getAllLibraryEntries(m)
}
fun allLibraryEntries(): RequestBuilder<Observable<JSONAPIDocument<List<LibraryEntry>>>>
= RequestBuilder("", getAllLibraryEntriesCall)
private val getLibraryCall = {
id: String, h: Map<String, String>, m: Map<String, String> ->
service.getLibrary(id, h, m)
}
fun library(id: String): RequestBuilder<Observable<JSONAPIDocument<List<LibraryEntry>>>>
= RequestBuilder(id, getLibraryCall)
private val getLibraryEntryCall = {
id: String, h: Map<String, String>, m: Map<String, String> ->
service.getLibraryEntry(id, h, m)
}
fun libraryEntry(id: String): RequestBuilder<Observable<JSONAPIDocument<LibraryEntry>>>
= RequestBuilder(id, getLibraryEntryCall)
private fun libraryEntryForMedia(userId: String, mediaId: String, mediaType: String)
: RequestBuilder<Observable<JSONAPIDocument<List<LibraryEntry>>>> {
return RequestBuilder("", getAllLibraryEntriesCall)
.filter("userId", userId)
.filter("kind", mediaType)
.filter(mediaType + "Id", mediaId)
.page("limit", 1)
}
fun libraryEntryForAnime(userId: String, animeId: String): RequestBuilder<Observable<JSONAPIDocument<List<LibraryEntry>>>>
= libraryEntryForMedia(userId, animeId, "anime")
fun libraryEntryForManga(userId: String, mangaId: String): RequestBuilder<Observable<JSONAPIDocument<List<LibraryEntry>>>>
= libraryEntryForMedia(userId, mangaId, "manga")
fun createLibraryEntry(libraryEntry: LibraryEntry, authToken: String, tokenType: String = "bearer")
: Observable<Response<ResponseBody>> {
libraryEntry.id = "temporary_id"
var body: String = ResourceConverters
.mainConverter
.writeDocument(JSONAPIDocument<LibraryEntry>(libraryEntry))
.toString(Charsets.UTF_8)
// remove the ID as it should not be sent (the resource has not been create yet so throws an error on the server)
body = SerializationUtils.removeFirstIdFromJson(body)
return service.createLibraryEntry(
createAuthorizationParam(tokenType, authToken),
RequestBody.create(MediaType.parse(JSON_API_CONTENT_TYPE), body)
)
}
fun updateLibraryEntry(libraryEntry: LibraryEntry, authToken: String, tokenType: String = "bearer"): Observable<JSONAPIDocument<LibraryEntry>> {
val body = ResourceConverters.mainConverter.writeDocument(JSONAPIDocument<LibraryEntry>(libraryEntry))
return service.updateLibraryEntry(
createAuthorizationParam(tokenType, authToken),
libraryEntry.id!!,
RequestBody.create(MediaType.parse(JSON_API_CONTENT_TYPE), body)
)
}
fun deleteLibraryEntry(id: String, authToken: String, tokenType: String = "bearer"): Observable<Response<Void>>
= service.deleteLibraryEntry(createAuthorizationParam(tokenType, authToken), id)
/**
* Favorites
*/
private val getAllFavoritesCall = {
_: String, h: Map<String, String>, m: Map<String, String> ->
service.getAllFavorites(h, m)
}
fun allFavorites(): RequestBuilder<Observable<JSONAPIDocument<List<Favorite>>>>
= RequestBuilder("", getAllFavoritesCall)
private val getFavoriteCall = {
id: String, h: Map<String, String>, m: Map<String, String> ->
service.getFavorite(id, h, m)
}
fun favorite(id: String): RequestBuilder<Observable<JSONAPIDocument<Favorite>>>
= RequestBuilder(id, getFavoriteCall)
private fun favoriteForMedia(userId: String, mediaId: String, mediaType: String)
: RequestBuilder<Observable<JSONAPIDocument<List<Favorite>>>> {
return RequestBuilder("", getAllFavoritesCall)
.filter("userId", userId)
.filter("itemId", mediaId)
.filter("itemType", mediaType)
.page("limit", 1)
}
fun favoriteForAnime(userId: String, animeId: String): RequestBuilder<Observable<JSONAPIDocument<List<Favorite>>>>
= favoriteForMedia(userId, animeId, "Anime")
fun favoriteForManga(userId: String, mangaId: String): RequestBuilder<Observable<JSONAPIDocument<List<Favorite>>>>
= favoriteForMedia(userId, mangaId, "Manga")
// TODO: create version of method without need for full object
fun createFavorite(favorite: Favorite, authToken: String, tokenType: String = "bearer"): Observable<JSONAPIDocument<Favorite>> {
favorite.id = "temporary_id"
var body = ResourceConverters
.mainConverter
.writeDocument(JSONAPIDocument<Favorite>(favorite))
.toString(Charsets.UTF_8)
body = SerializationUtils.removeIdFromJson(body, favorite.id!!)
return service.postFavorite(
createAuthorizationParam(tokenType, authToken),
RequestBody.create(MediaType.parse(JSON_API_CONTENT_TYPE), body)
)
}
fun createFavorite(userId: String, mediaId: String, mediaType: JsonType, authToken: String, tokenType: String = "bearer") {
//TODO: write (blocked by polymorph)
}
//TODO: test (need to make a test for [createFavorite] first so can test safely
fun deleteFavorite(id: String): Observable<Response<Void>> {
return service.deleteFavorite(id)
}
/**
* Characters
*/
private val getAllCharactersCall = {
_: String, h: Map<String, String>, m: Map<String, String> ->
service.getAllCharacters(h, m)
}
fun allCharacters(): RequestBuilder<Observable<JSONAPIDocument<List<Character>>>>
= RequestBuilder("", getAllCharactersCall)
private val getCharacterCall = {
id: String, h: Map<String, String>, m: Map<String, String> ->
service.getCharacter(id, h, m)
}
fun character(id: String): RequestBuilder<Observable<JSONAPIDocument<Character>>>
= RequestBuilder(id, getCharacterCall)
private val getAnimeCharactersCall = {
id: String, h: Map<String, String>, m: Map<String, String> ->
service.getAnimeCharacters(id, h, m)
}
/**
* No equivalent method for Manga due to current Api limits (no filter for `mediaType` on `/characters` and `manga-characters` is unfilled.
* You must use [castingsForManga] and append the following [RequestBuilder] methods:
* .filter("isCharacter", "true")
* .include("character", "person")
*/
fun charactersForAnime(animeId: String): RequestBuilder<Observable<JSONAPIDocument<List<AnimeCharacter>>>>
= RequestBuilder(animeId, getAnimeCharactersCall)
/**
* Castings
*/
private val getAllCastingsCall = {
_: String, h: Map<String, String>, m: Map<String, String> ->
service.getAllCastings(h, m)
}
fun allCastings(): RequestBuilder<Observable<JSONAPIDocument<List<Casting>>>>
= RequestBuilder("", getAllCastingsCall)
private val getCastingCall = {
id: String, h: Map<String, String>, m: Map<String, String> ->
service.getCasting(id, h, m)
}
fun casting(id: String): RequestBuilder<Observable<JSONAPIDocument<Casting>>>
= RequestBuilder(id, getCastingCall)
private fun castingsForMedia(mediaId: String, mediaType: String): RequestBuilder<Observable<JSONAPIDocument<List<Casting>>>>
= RequestBuilder("", getAllCastingsCall)
.filter("mediaType", mediaType)
.filter("mediaId", mediaId)
fun castingsForAnime(animeId: String): RequestBuilder<Observable<JSONAPIDocument<List<Casting>>>>
= castingsForMedia(animeId, "Anime")
fun castingsForManga(mangaId: String): RequestBuilder<Observable<JSONAPIDocument<List<Casting>>>>
= castingsForMedia(mangaId, "Manga")
/**
* Reactions
*/
private val getAllReactionsCall = {
_: String, h: Map<String, String>, m: Map<String, String> ->
service.getAllReactions(h, m)
}
fun allReactions(): RequestBuilder<Observable<JSONAPIDocument<List<Reaction>>>>
= RequestBuilder("", getAllReactionsCall)
private val getReactionCall = {
id: String, h: Map<String, String>, m: Map<String, String> ->
service.getReaction(id, h, m)
}
fun reaction(id: String): RequestBuilder<Observable<JSONAPIDocument<Reaction>>>
= RequestBuilder(id, getReactionCall)
private fun reactionsForMedia(mediaId: String, mediaType: String): RequestBuilder<Observable<JSONAPIDocument<List<Reaction>>>>
= RequestBuilder("", getAllReactionsCall)
.filter(mediaType + "Id", mediaId)
fun reactionsForAnime(animeId: String): RequestBuilder<Observable<JSONAPIDocument<List<Reaction>>>>
= reactionsForMedia(animeId, "anime")
fun reactionsForManga(mangaId: String): RequestBuilder<Observable<JSONAPIDocument<List<Reaction>>>>
= reactionsForMedia(mangaId, "manga")
private val getLibraryEntryReactionCall = {
id: String, h: Map<String, String>, m: Map<String, String> ->
service.getLibraryEntryReaction(id, h, m)
}
fun reactionForLibraryEntry(libraryEntryId: String): RequestBuilder<Observable<JSONAPIDocument<Reaction>>>
= RequestBuilder(libraryEntryId, getLibraryEntryReactionCall)
/**
* Users
*/
private val getAllUsersCall = {
_: String, h: Map<String, String>, m: Map<String, String> ->
service.getAllUsers(h, m)
}
fun allUsers(): RequestBuilder<Observable<JSONAPIDocument<List<User>>>>
= RequestBuilder("", getAllUsersCall)
fun allUsersAuth(authToken: String, tokenType: String = "bearer"): RequestBuilder<Observable<JSONAPIDocument<List<User>>>>
= RequestBuilder("", getAllUsersCall)
.withHeader("Authorization", createAuthorizationParam(tokenType, authToken))
private val getUserCall = {
id: String, h: Map<String, String>, m: Map<String, String> ->
service.getUser(id, h, m)
}
fun user(id: String): RequestBuilder<Observable<JSONAPIDocument<User>>>
= RequestBuilder(id, getUserCall)
}
| gpl-3.0 | a6e8e8cc2cc2c875dd2e44e5d9aa656c | 38.789474 | 148 | 0.671517 | 4.655718 | false | false | false | false |
jeffgbutler/mybatis-qbe | src/test/kotlin/examples/kotlin/mybatis3/canonical/PersonDynamicSqlSupport.kt | 1 | 2009 | /*
* Copyright 2016-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
*
* 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 examples.kotlin.mybatis3.canonical
import org.mybatis.dynamic.sql.SqlTable
import org.mybatis.dynamic.sql.util.kotlin.elements.column
import java.sql.JDBCType
import java.util.Date
object PersonDynamicSqlSupport {
val person = Person()
val id = person.id
val firstName = person.firstName
val lastName = person.lastName
val birthDate = person.birthDate
val employed = person.employed
val occupation = person.occupation
val addressId = person.addressId
class Person : SqlTable("Person") {
val id = column<Int>(name = "id", jdbcType = JDBCType.INTEGER)
val firstName = column<String>(name = "first_name", jdbcType = JDBCType.VARCHAR)
val lastName = column<LastName>(
name = "last_name",
jdbcType = JDBCType.VARCHAR,
typeHandler = "examples.kotlin.mybatis3.canonical.LastNameTypeHandler"
)
val birthDate = column<Date>(name = "birth_date", jdbcType = JDBCType.DATE)
val employed = column<Boolean>(
name = "employed",
JDBCType.VARCHAR,
typeHandler = "examples.kotlin.mybatis3.canonical.YesNoTypeHandler"
)
val occupation = column<String>(name = "occupation", jdbcType = JDBCType.VARCHAR)
val addressId = column<Int>(name = "address_id", jdbcType = JDBCType.INTEGER)
}
}
| apache-2.0 | 43adea49a3ba419e48f0926c962008fd | 39.18 | 89 | 0.681434 | 4.329741 | false | false | false | false |
PaulWoitaschek/Voice | data/src/main/kotlin/voice/data/repo/ChapterRepo.kt | 1 | 1214 | package voice.data.repo
import voice.data.Chapter
import voice.data.repo.internals.dao.ChapterDao
import voice.data.runForMaxSqlVariableNumber
import java.time.Instant
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ChapterRepo
@Inject constructor(
private val dao: ChapterDao,
) {
private val cache = mutableMapOf<Chapter.Id, Chapter?>()
suspend fun get(id: Chapter.Id): Chapter? {
// this does not use getOrPut because a `null` value should also be cached
if (!cache.containsKey(id)) {
cache[id] = dao.chapter(id)
}
return cache[id]
}
suspend fun warmup(ids: List<Chapter.Id>) {
val missing = ids.filter { it !in cache }
missing
.runForMaxSqlVariableNumber {
dao.chapters(it)
}
.forEach { cache[it.id] = it }
}
suspend fun put(chapter: Chapter) {
dao.insert(chapter)
cache[chapter.id] = chapter
}
suspend inline fun getOrPut(
id: Chapter.Id,
lastModified: Instant,
defaultValue: () -> Chapter?,
): Chapter? {
val chapter = get(id)
if (chapter != null && chapter.fileLastModified == lastModified) {
return chapter
}
return defaultValue()?.also { put(it) }
}
}
| gpl-3.0 | f258b4ca98cdd4e6587947b2e7304b3f | 22.803922 | 78 | 0.669687 | 3.758514 | false | false | false | false |
lightem90/Sismic | app/src/main/java/com/polito/sismic/Presenters/Adapters/NodeListAdapter.kt | 1 | 8418 | package com.polito.sismic.Presenters.Adapters
import android.content.Context
import android.support.v4.content.ContextCompat
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import com.polito.sismic.Domain.NeighboursNodeData
import com.polito.sismic.Domain.PeriodData
import com.polito.sismic.Domain.PillarDomainGraphPoint
import com.polito.sismic.Domain.SpectrumDTO
import com.polito.sismic.Extensions.inflate
import com.polito.sismic.Interactors.Helpers.StatiLimite
import com.polito.sismic.R
import kotlinx.android.synthetic.main.close_points_layout.view.*
import kotlinx.android.synthetic.main.domain_point_item.view.*
import kotlinx.android.synthetic.main.limit_state_data_layout.view.*
import kotlinx.android.synthetic.main.period_data_layout.view.*
class NodeListAdapter(private val mContext: Context, private val mNodeData: List<NeighboursNodeData>)
: RecyclerView.Adapter<NodeListAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NodeListAdapter.ViewHolder? {
val v = parent.inflate(R.layout.close_points_layout)
return NodeListAdapter.ViewHolder(v, mContext)
}
override fun onBindViewHolder(holder: NodeListAdapter.ViewHolder, position: Int) {
if (position == 0) holder.bindHeader()
else holder.bindNodeData(mNodeData[position - 1])
}
override fun getItemCount(): Int {
return mNodeData.size + 1
}
class ViewHolder(itemView: View, val mContext: Context) : RecyclerView.ViewHolder(itemView) {
fun bindNodeData(neighboursNodeData: NeighboursNodeData) = with(neighboursNodeData) {
itemView.node_id.text = id
itemView.node_longitude.text = longitude.toString()
itemView.node_latitude.text = latitude.toString()
itemView.node_distance.text = String.format(mContext.resources.getText(R.string.km_format).toString(), distance)
}
fun bindHeader() {
itemView.node_id.text = mContext.resources.getText(R.string.nodelist_id_header)
itemView.node_longitude.text = mContext.resources.getText(R.string.nodelist_longitude_header)
itemView.node_latitude.text = mContext.resources.getText(R.string.nodelist_latitude_header)
itemView.node_distance.text = mContext.resources.getText(R.string.nodelist_distance_header)
itemView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_grey))
}
}
}
class PeriodListAdapter(private val mContext: Context, private val mPeriodDataList: List<PeriodData>)
: RecyclerView.Adapter<PeriodListAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PeriodListAdapter.ViewHolder? {
val v = parent.inflate(R.layout.period_data_layout)
return PeriodListAdapter.ViewHolder(v, mContext)
}
override fun onBindViewHolder(holder: PeriodListAdapter.ViewHolder, position: Int) {
if (position == 0) holder.bindHeader()
else holder.bindPeriodData(mPeriodDataList[position - 1])
}
override fun getItemCount(): Int {
return mPeriodDataList.size + 1
}
class ViewHolder(itemView: View, val mContext: Context) : RecyclerView.ViewHolder(itemView) {
fun bindPeriodData(periodData: PeriodData) = with(periodData) {
itemView.year.text = years.toString()
itemView.ag.text = String.format(mContext.resources.getText(R.string.params_format).toString(), ag)
itemView.f0.text = String.format(mContext.resources.getText(R.string.params_format).toString(), f0)
itemView.tcstar.text = String.format(mContext.resources.getText(R.string.params_format).toString(), tcstar)
}
fun bindHeader() {
itemView.year.text = mContext.resources.getText(R.string.year_header)
itemView.ag.text = mContext.resources.getText(R.string.ag_header)
itemView.f0.text = mContext.resources.getText(R.string.f0_header)
itemView.tcstar.text = mContext.resources.getText(R.string.tcstar_header)
itemView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_grey))
}
}
}
class LimitStateAdapter(private val mContext: Context, private val mLimitStateAdapter: List<SpectrumDTO>)
: RecyclerView.Adapter<LimitStateAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LimitStateAdapter.ViewHolder? {
val v = parent.inflate(R.layout.limit_state_data_layout)
return LimitStateAdapter.ViewHolder(v, mContext)
}
override fun onBindViewHolder(holder: LimitStateAdapter.ViewHolder, position: Int) {
if (position == 0) holder.bindHeader()
else holder.bindPeriodData(mLimitStateAdapter[position - 1])
}
override fun getItemCount(): Int {
return mLimitStateAdapter.size + 1
}
class ViewHolder(itemView: View, val mContext: Context) : RecyclerView.ViewHolder(itemView) {
fun bindPeriodData(periodData: SpectrumDTO) = with(periodData) {
val state = StatiLimite.values().first { it.name == name }
itemView.state.text = String.format(mContext.getString(R.string.params_spectrum_state_format_old), state.name, (state.multiplier * 100).toInt(), "%")
itemView.tc.text = String.format(mContext.getString(R.string.params_spectrum_format), tc)
itemView.tb.text = String.format(mContext.getString(R.string.params_spectrum_format), tb)
itemView.td.text = String.format(mContext.getString(R.string.params_spectrum_format), td)
itemView.cc.text = String.format(mContext.getString(R.string.params_spectrum_format), ag)
itemView.ss.text = String.format(mContext.getString(R.string.params_spectrum_format), f0)
itemView.s.text = String.format(mContext.getString(R.string.params_spectrum_format), tcStar)
}
fun bindHeader() {
itemView.state.text = mContext.resources.getText(R.string.state_header)
itemView.tc.text = mContext.resources.getText(R.string.tc_header)
itemView.tb.text = mContext.resources.getText(R.string.tb_header)
itemView.td.text = mContext.resources.getText(R.string.td_header)
//same layout but i show other datas
itemView.cc.text = mContext.resources.getText(R.string.ag_header)
itemView.ss.text = mContext.resources.getText(R.string.f0_header)
itemView.s.text = mContext.resources.getText(R.string.tcstar_header)
itemView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_grey))
}
}
}
class DomainPointAdapter(private val mContext: Context, private val mDomainPointList: List<PillarDomainGraphPoint>)
: RecyclerView.Adapter<DomainPointAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DomainPointAdapter.ViewHolder? {
val v = parent.inflate(R.layout.domain_point_item)
return DomainPointAdapter.ViewHolder(v, mContext)
}
override fun onBindViewHolder(holder: DomainPointAdapter.ViewHolder, position: Int) {
if (position == 0) holder.bindHeader()
else holder.bindPillarDomainPoint(mDomainPointList[position - 1], position)
}
override fun getItemCount(): Int {
return mDomainPointList.size + 1
}
class ViewHolder(itemView: View, val mContext: Context) : RecyclerView.ViewHolder(itemView) {
fun bindPillarDomainPoint(domainPoint: PillarDomainGraphPoint, index: Int) = with(domainPoint) {
itemView.index.text = String.format(mContext.getString(R.string.domain_point_id_value), index)
itemView.n.text = String.format(mContext.getString(R.string.domain_point_value_format_high), n)
itemView.m.text = String.format(mContext.getString(R.string.domain_point_value_format_high), m)
}
fun bindHeader() {
itemView.index.text = mContext.getString(R.string.domain_point_id_label)
itemView.n.text = mContext.getString(R.string.domain_point_n_label)
itemView.m.text = mContext.getString(R.string.domain_point_m_label)
itemView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_grey))
}
}
}
| mit | ac28e3a99555713b23c79da0740dbcae | 47.65896 | 161 | 0.708244 | 4.167327 | false | false | false | false |
grassrootza/grassroot-android-v2 | app/src/main/java/za/org/grassroot2/GroupSettingsActivity.kt | 1 | 8004 | package za.org.grassroot2
import android.Manifest
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.graphics.drawable.BitmapDrawable
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.support.v4.graphics.drawable.RoundedBitmapDrawable
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory
import android.view.View
import android.widget.Toast
import com.squareup.picasso.Callback
import com.squareup.picasso.Picasso
import com.tbruyelle.rxpermissions2.RxPermissions
import io.reactivex.Observable
import kotlinx.android.synthetic.main.activity_group_settings.*
import timber.log.Timber
import za.org.grassroot2.dagger.activity.ActivityComponent
import za.org.grassroot2.model.Group
import za.org.grassroot2.presenter.activity.GroupSettingsPresenter
import za.org.grassroot2.view.activity.DashboardActivity
import za.org.grassroot2.view.activity.GrassrootActivity
import za.org.grassroot2.view.dialog.GenericSelectDialog
import za.org.grassroot2.view.dialog.SelectImageDialog
import javax.inject.Inject
class GroupSettingsActivity : GrassrootActivity(), GroupSettingsPresenter.GroupSettingsView,SelectImageDialog.SelectImageDialogEvents {
override val layoutResourceId: Int
get() = R.layout.activity_group_settings
@Inject lateinit var presenter: GroupSettingsPresenter
@Inject lateinit var rxPermission: RxPermissions
private val REQUEST_TAKE_PHOTO = 2
private val REQUEST_GALLERY = 3
private var groupUid: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
groupUid = intent.getStringExtra(EXTRA_GROUP_UID)
presenter.attach(this)
presenter.init(groupUid!!)
initToolbar()
viewMembers.setOnClickListener { presenter.loadMembers() }
hideGroup.setOnClickListener { presenter.hideGroup() }
leaveGroup.setOnClickListener { presenter.leaveGroup() }
exportGroup.setOnClickListener{ presenter.exportMembers() }
}
override fun onResume() {
super.onResume()
presenter.loadData()
}
override fun render(group: Group, lastMonthCount: Long) {
supportActionBar!!.title = group.name
description.text = if (lastMonthCount > 0)
getString(R.string.member_count_recent, group.memberCount, lastMonthCount)
else
getString(R.string.member_count_basic, group.memberCount)
if(group.profileImageUrl != null){
loadProfilePic(group.profileImageUrl)
}
if(!group.permissions.contains("GROUP_PERMISSION_UPDATE_GROUP_DETAILS")){
changePhoto.visibility = View.GONE
}else{
changePhoto.visibility = View.VISIBLE
changePhoto.setOnClickListener { v ->
val dialog:SelectImageDialog = SelectImageDialog.newInstance(R.string.select_image,false);
dialog.show(supportFragmentManager,"DIALOG_TAG")
}
}
//loadProfilePic(group.uid)
viewMembers.isEnabled = group.hasMembersFetched()
}
override fun membersAvailable(totalMembers: Int, lastMonthCount: Long) {
viewMembers.isEnabled = true
description.text = if (lastMonthCount > 0)
getString(R.string.member_count_recent, totalMembers, lastMonthCount)
else
getString(R.string.member_count_basic, totalMembers)
}
private fun loadProfilePic(url: String) {
//val url = BuildConfig.API_BASE + "group/image/view/" + groupUid
Picasso.get()
.load(url)
.resizeDimen(R.dimen.profile_photo_s_width, R.dimen.profile_photo_s_height)
.placeholder(R.drawable.group_5)
.error(R.drawable.group_5)
.centerCrop()
.into(groupPhoto, object : Callback {
override fun onSuccess() {
val imageBitmap = (groupPhoto.drawable as BitmapDrawable).bitmap
val imageDrawable: RoundedBitmapDrawable = RoundedBitmapDrawableFactory.create(resources, imageBitmap)
imageDrawable.isCircular = true
imageDrawable.cornerRadius = Math.max(imageBitmap.width, imageBitmap.height) / 2.0f
groupPhoto.setImageDrawable(imageDrawable)
}
override fun onError(e: Exception?) {
groupPhoto.setImageResource(R.drawable.user)
}
})
}
override fun exitToHome(messageToUser: Int) {
Toast.makeText(this, messageToUser, Toast.LENGTH_SHORT).show()
startActivity(Intent(this, DashboardActivity::class.java))
finish()
}
override fun ensureWriteExteralStoragePermission(): Observable<Boolean> {
return rxPermission.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
private fun initToolbar() {
setSupportActionBar(toolbar)
toolbar.setNavigationIcon(R.drawable.ic_arrow_left_white_24dp)
toolbar.setNavigationOnClickListener { v -> finish() }
}
override fun selectFileActionDialog(fileUri: Uri) {
val dialog = GenericSelectDialog.get(getString(R.string.group_export_select),
intArrayOf(R.string.open_file, R.string.share_file),
arrayListOf<View.OnClickListener>(
View.OnClickListener { tryOpenExcel(fileUri) },
View.OnClickListener { tryShareExcel(fileUri) }
))
dialog.show(supportFragmentManager, DIALOG_TAG)
}
private fun tryOpenExcel(fileUri: Uri) {
val intent = Intent(Intent.ACTION_VIEW)
intent.setDataAndType(fileUri, "application/vnd.ms-excel")
try {
startActivity(intent)
} catch (e: ActivityNotFoundException) {
Toast.makeText(this, R.string.open_file_no_app, Toast.LENGTH_SHORT).show()
}
}
private fun tryShareExcel(fileUri: Uri) {
val intent = Intent(Intent.ACTION_SEND)
intent.putExtra(Intent.EXTRA_STREAM, fileUri)
intent.setType("application/vnd.ms-excel")
try {
startActivity(intent)
} catch (e: ActivityNotFoundException) {
Toast.makeText(this, R.string.share_file_no_app, Toast.LENGTH_SHORT).show()
}
}
override fun onInject(component: ActivityComponent) {
component.inject(this)
}
override fun openCamera() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun pickImageFromGallery() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun cameraForResult(contentProviderPath: String, s: String) {
val intent:Intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.parse(contentProviderPath))
intent.putExtra("MY_UID", s)
startActivityForResult(intent,REQUEST_TAKE_PHOTO)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if(resultCode == Activity.RESULT_OK){
if(requestCode == REQUEST_TAKE_PHOTO){
presenter.cameraResult()
} else if(requestCode == REQUEST_GALLERY){
val imageUri:Uri = data!!.data
//presenter.setGroupImageUrl(imageUri.toString())
//setImage(imageUri.toString())
}
}
}
companion object {
private val EXTRA_GROUP_UID = "group_uid"
fun start(activity: Activity, groupUid: String?) {
val intent = Intent(activity, GroupSettingsActivity::class.java)
intent.putExtra(EXTRA_GROUP_UID, groupUid)
activity.startActivity(intent)
}
}
}
| bsd-3-clause | 47a88dabcafb4fb96b3bf1aa6ea6cfdc | 38.043902 | 135 | 0.666792 | 4.772809 | false | false | false | false |
neyb/swak | undertow/src/test/kotlin/swak/SwakServer_bodyReaderTest.kt | 1 | 1338 | package swak
import io.github.neyb.shoulk.shouldEqual
import org.junit.Test
import swak.body.reader.BodyReader
import swak.body.reader.provider.request.BodyReaderChooser
import swak.body.reader.provider.type.BodyReaderChooserProvider
import swak.http.request.Method.POST
import swak.http.request.UpdatableRequest
import swak.http.response.*
class SwakServer_bodyReaderTest : SwakServerTest() {
@Test fun body_can_be_read() {
val bodyLengthReader = object : BodyReader<Int>, BodyReaderChooserProvider, BodyReaderChooser<Int> {
override fun read(body: String) = body.length
override fun <B> forClass(target: Class<B>) =
@Suppress("UNCHECKED_CAST")
if (target == Int::class.javaObjectType) this as BodyReaderChooser<B>
else null
override fun forRequest(request: UpdatableRequest<String>) = this
}
var nameLength: Int? = null
swakServer {
addContentReaderProvider(bodyLengthReader)
on("/IAm", POST).withA<Int>() answer {
request.body
.doOnSuccess { nameLength = it }
.map { SimpleResponse.withoutBody() }
}
}.start()
post("/IAm", "Tony Stark")
nameLength shouldEqual 10
}
} | apache-2.0 | f694fdb2f00aac1b41e6fa3deb6b942e | 31.658537 | 108 | 0.629297 | 4.445183 | false | true | false | false |
didi/DoraemonKit | Android/dokit/src/main/java/com/didichuxing/doraemonkit/kit/connect/DoKitScanActivity.kt | 1 | 2300 | package com.didichuxing.doraemonkit.kit.connect
import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.annotation.IdRes
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.didichuxing.doraemonkit.R
import com.didichuxing.doraemonkit.widget.titlebar.HomeTitleBar
import com.didichuxing.doraemonkit.zxing.activity.CaptureActivity
/**
* didi Create on 2022/4/12 .
*
* Copyright (c) 2022/4/12 by didiglobal.com.
*
* @author <a href="[email protected]">zhangjun</a>
* @version 1.0
* @Date 2022/4/12 6:07 下午
* @Description 用一句话说明文件功能
*/
class DoKitScanActivity : CaptureActivity() {
companion object {
private const val REQUEST_CODE = 200999
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
checkCameraPermission()
}
override fun setContentView(@IdRes layoutResID: Int) {
super.setContentView(layoutResID)
initTitleBar()
}
private fun initTitleBar() {
val homeTitleBar = HomeTitleBar(this)
homeTitleBar.setBackgroundColor(resources.getColor(R.color.foreground_wtf))
homeTitleBar.setIcon(R.mipmap.dk_close_icon)
homeTitleBar.setListener { finish() }
val params = FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
resources.getDimension(R.dimen.dk_home_title_height).toInt()
)
(findViewById<View>(android.R.id.content) as FrameLayout).addView(homeTitleBar, params)
}
private fun checkCameraPermission() {
val hasCameraPermission: Int = ContextCompat.checkSelfPermission(application, Manifest.permission.CAMERA)
if (hasCameraPermission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), REQUEST_CODE)
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == REQUEST_CODE) {
}
}
}
| apache-2.0 | dde059c1a8bed63906a8698eca3543e5 | 32.970149 | 119 | 0.726274 | 4.542914 | false | false | false | false |
nickthecoder/paratask | paratask-examples/src/main/kotlin/uk/co/nickthecoder/paratask/examples/IntRangeExample.kt | 1 | 1049 | package uk.co.nickthecoder.paratask.examples
import uk.co.nickthecoder.paratask.AbstractTask
import uk.co.nickthecoder.paratask.TaskDescription
import uk.co.nickthecoder.paratask.TaskParser
import uk.co.nickthecoder.paratask.parameters.IntParameter
import uk.co.nickthecoder.paratask.parameters.LabelPosition
import uk.co.nickthecoder.paratask.parameters.asHorizontal
import uk.co.nickthecoder.paratask.parameters.compound.IntRangeParameter
class IntRangeExample : AbstractTask() {
val intP = IntParameter("int")
val range1P = IntRangeParameter("range1")
val range2P = IntRangeParameter("range2", toText = null)
.asHorizontal(LabelPosition.TOP)
override val taskD = TaskDescription("intRangeExample")
.addParameters(intP, range1P, range2P)
override fun run() {
println("Range1 = from ${range1P.from} to ${range1P.to}")
println("Range2 = from ${range2P.from} to ${range2P.to}")
}
}
fun main(args: Array<String>) {
TaskParser(IntRangeExample()).go(args, prompt = true)
}
| gpl-3.0 | 02a334f428de74ba218519dde5cc4f01 | 28.971429 | 72 | 0.741659 | 3.914179 | false | false | false | false |
Light-Team/ModPE-IDE-Source | app/src/main/kotlin/com/brackeys/ui/feature/explorer/adapters/FileAdapter.kt | 1 | 3175 | /*
* Copyright 2021 Brackeys IDE contributors.
*
* 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.brackeys.ui.feature.explorer.adapters
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.selection.Selection
import androidx.recyclerview.selection.SelectionTracker
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.brackeys.ui.filesystem.base.model.FileModel
import com.brackeys.ui.utils.adapters.OnItemClickListener
class FileAdapter(
private val selectionTracker: SelectionTracker<String>,
private val onItemClickListener: OnItemClickListener<FileModel>,
private val viewMode: Int
) : ListAdapter<FileModel, FileAdapter.FileViewHolder>(diffCallback) {
companion object {
const val VIEW_MODE_COMPACT = 0
const val VIEW_MODE_DETAILED = 1
private val diffCallback = object : DiffUtil.ItemCallback<FileModel>() {
override fun areItemsTheSame(oldItem: FileModel, newItem: FileModel): Boolean {
return oldItem.path == newItem.path
}
override fun areContentsTheSame(oldItem: FileModel, newItem: FileModel): Boolean {
return oldItem == newItem
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FileViewHolder {
return when (viewMode) {
VIEW_MODE_COMPACT -> CompactViewHolder.create(parent, onItemClickListener)
VIEW_MODE_DETAILED -> DetailedViewHolder.create(parent, onItemClickListener)
else -> CompactViewHolder.create(parent, onItemClickListener)
}
}
override fun onBindViewHolder(holder: FileViewHolder, position: Int) {
val fileModel = getItem(position)
val isSelected = selectionTracker.isSelected(fileModel.path)
holder.bind(fileModel, isSelected)
}
fun getSelectedFiles(keys: Selection<String>): List<FileModel> {
val files = mutableListOf<FileModel>()
currentList.forEach { fileModel ->
if (keys.contains(fileModel.path)) {
files.add(fileModel)
}
}
return files
}
fun indexOf(path: String): Int {
var position = 0
currentList.forEachIndexed { index, fileModel ->
if (path == fileModel.path) {
position = index
}
}
return position
}
abstract class FileViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
abstract fun bind(fileModel: FileModel, isSelected: Boolean)
}
} | apache-2.0 | b83c08add8728dfe425c12072d56270c | 35.505747 | 94 | 0.692283 | 4.937792 | false | false | false | false |
cout970/Magneticraft | ignore/test/tileentity/heat/TileRedstoneHeatPipe.kt | 2 | 1148 | package tileentity.heat
import com.cout970.magneticraft.api.internal.heat.HeatContainer
import com.cout970.magneticraft.misc.tileentity.ITileTrait
import com.cout970.magneticraft.misc.tileentity.TraitHeat
import com.cout970.magneticraft.tileentity.TileBase
import com.cout970.magneticraft.util.COPPER_HEAT_CAPACITY
import com.cout970.magneticraft.util.COPPER_MELTING_POINT
import com.cout970.magneticraft.util.DEFAULT_CONDUCTIVITY
import com.teamwizardry.librarianlib.common.util.autoregister.TileRegister
/**
* Created by cout970 on 04/07/2016.
*/
@TileRegister("redstone_heat_pipe")
class TileRedstoneHeatPipe : TileBase() {
val heat = HeatContainer(dissipation = 0.0,
specificHeat = COPPER_HEAT_CAPACITY * 3 / 8,
maxHeat = COPPER_HEAT_CAPACITY * 3 * COPPER_MELTING_POINT / 8,
conductivity = DEFAULT_CONDUCTIVITY,
worldGetter = { this.world },
posGetter = { this.getPos() })
val traitHeat: TraitHeat = TraitHeat(this, listOf(heat))
override val traits: List<ITileTrait> = listOf(traitHeat)
override fun onLoad() {
super.onLoad()
//TODO ?
}
} | gpl-2.0 | 30ec3e2fc3449f9bd19035b72008c339 | 32.794118 | 74 | 0.72561 | 3.986111 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-scm/src/main/java/net/nemerosa/ontrack/extension/scm/catalog/SCMCatalogProjectFilter.kt | 1 | 781 | package net.nemerosa.ontrack.extension.scm.catalog
import java.time.LocalDate
/**
* Filter used on the SCM catalog entries
*/
data class SCMCatalogProjectFilter(
val offset: Int = 0,
val size: Int = 20,
val scm: String? = null,
val config: String? = null,
val repository: String? = null,
val project: String? = null,
val link: SCMCatalogProjectFilterLink = SCMCatalogProjectFilterLink.ALL,
val beforeLastActivity: LocalDate? = null,
val afterLastActivity: LocalDate? = null,
val beforeCreatedAt: LocalDate? = null,
val afterCreatedAt: LocalDate? = null,
val team: String? = null,
val sortOn: SCMCatalogProjectFilterSort? = null,
val sortAscending: Boolean = true
)
| mit | 4758319762d07be9a90a917bdf64b96f | 32.956522 | 80 | 0.653009 | 4.314917 | false | false | false | false |
nextcloud/android | app/src/main/java/com/nextcloud/client/core/ManualAsyncRunner.kt | 1 | 2944 | /*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2019 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.core
import java.util.ArrayDeque
/**
* This async runner is suitable for tests, where manual simulation of
* asynchronous operations is desirable.
*/
class ManualAsyncRunner : AsyncRunner {
private val queue: ArrayDeque<Runnable> = ArrayDeque()
override fun <T> postQuickTask(
task: () -> T,
onResult: OnResultCallback<T>?,
onError: OnErrorCallback?
): Cancellable {
return postTask(
task = { _: OnProgressCallback<Any>, _: IsCancelled -> task.invoke() },
onResult = onResult,
onError = onError,
onProgress = null
)
}
override fun <T, P> postTask(
task: TaskFunction<T, P>,
onResult: OnResultCallback<T>?,
onError: OnErrorCallback?,
onProgress: OnProgressCallback<P>?
): Cancellable {
val remove: Function1<Runnable, Boolean> = queue::remove
val taskWrapper = Task(
postResult = { it.run(); true },
removeFromQueue = remove,
taskBody = task,
onSuccess = onResult,
onError = onError,
onProgress = onProgress
)
queue.push(taskWrapper)
return taskWrapper
}
val size: Int get() = queue.size
val isEmpty: Boolean get() = queue.size == 0
/**
* Run all enqueued tasks until queue is empty. This will run also tasks
* enqueued by task callbacks.
*
* @param maximum max number of tasks to run to avoid infinite loopss
* @return number of executed tasks
*/
fun runAll(maximum: Int = 100): Int {
var c = 0
while (queue.size > 0) {
val t = queue.remove()
t.run()
c++
if (c > maximum) {
throw IllegalStateException("Maximum number of tasks run. Are you in infinite loop?")
}
}
return c
}
/**
* Run one pending task
*
* @return true if task has been run
*/
fun runOne(): Boolean {
val t = queue.pollFirst()
t?.run()
return t != null
}
}
| gpl-2.0 | 89aeb56581158b923aadb6c863d9bee7 | 29.350515 | 101 | 0.610394 | 4.529231 | false | false | false | false |
yifeidesu/DayPlus-Countdown | app/src/main/java/com/robyn/dayplus2/myUtils/MyEventExt.kt | 1 | 4470 | package com.robyn.dayplus2.myUtils
import android.content.Context
import android.widget.ImageView
import com.robyn.dayplus2.R
import com.robyn.dayplus2.data.MyEvent
import com.robyn.dayplus2.data.source.enums.EventCategory
import com.robyn.dayplus2.data.source.enums.EventRepeatMode
import com.robyn.dayplus2.data.source.enums.EventType
import org.joda.time.DateTime
import org.joda.time.Days
import org.joda.time.format.DateTimeFormat
import java.io.File
import java.util.*
fun isSinceEvent(event: MyEvent): Boolean = (event.datetime - DateTime.now().millis) <= 0
// 0,1,2,3,4,5 = cake, loving, face, social, work, no categoryCode - to match the tab position in tabLayout
fun categoryCodeToFilter(eventCategoryCode: Int): EventCategory = when (eventCategoryCode) {
0 -> EventCategory.CAKE_EVENTS
1 -> EventCategory.LOVED_EVENTS
2 -> EventCategory.FACE_EVENTS
3 -> EventCategory.EXPLORE_EVENTS
4 -> EventCategory.WORK_EVENTS
else -> EventCategory.WORK_EVENTS // cannot return - if the receiver method
}
fun eventTypeToCode(eventType: EventType): Int = when (eventType) {
EventType.ALL_EVENTS -> 0
EventType.SINCE_EVENTS -> 1
EventType.UNTIL_EVENTS -> 2
EventType.STARRED_EVENTS -> 3
EventType.CATEGORY_EVENTS -> 4
}
/**
* 1,2,3,4,5 = cake, loving, face, social, work, no categoryCode - t
*
* 0 for no category. However for now try null for no category.
*
* Since the db doesn't store enum type, use int code instead. Is it a good practice?
*/
/**
* According to tabs' position code in the tabLayout, get this mapping:
* position / categoryCode code -> tab 'name'
* 0 -> cake
* 1 -> loved
* 2 -> face
* 3 -> explore
* 4 -> work
*/
//@Ignore
val categoryCodeMap: HashMap<EventCategory, Int> = hashMapOf(
EventCategory.CAKE_EVENTS to 1,
EventCategory.LOVED_EVENTS to 2,
EventCategory.FACE_EVENTS to 3,
EventCategory.EXPLORE_EVENTS to 4,
EventCategory.WORK_EVENTS to 5
)
// repeatCode to enum
//@Ignore
//val repeatCodeMap: HashMap<Int, EventRepeatMode> = hashMapOf(
// 1 to EventRepeatMode.EVERY_WEEK,
// 2 to EventRepeatMode.EVERY_WEEK,
// 3 to EventRepeatMode.EVERY_WEEK
//)
// enum to repeat type string
//@Ignore
val repeatStrMap: HashMap<EventRepeatMode, String> = hashMapOf(
EventRepeatMode.EVERY_WEEK to "Never",
EventRepeatMode.EVERY_MONTH to "Every Week",
EventRepeatMode.EVERY_YEAR to "Every Month"
)
fun MyEvent.repeatModeStr(): String {
return repeatCodeToString(this.repeatMode)
}
fun repeatCodeToString(repeatCode: Int): String {
return when (repeatCode) {
1 -> "Every Week"
2 -> "Every Month"
3 -> "Every Year"
else -> "Never"
}
}
fun MyEvent.dayCount(): Int {
val nowDate = DateTime.now()
val eventDate = DateTime(this.datetime)
val count = Days.daysBetween(
nowDate.withTimeAtStartOfDay(),
eventDate.withTimeAtStartOfDay()
).days
return count
}
fun MyEvent.dayCountAbs(): Int = Math.abs(this.dayCount())
fun MyEvent.ifSince(): Int {
return if (this.dayCount() > 0) {
R.string.until
} else {
R.string.since
}
}
fun MyEvent.ifSinceStr(): String {
return if (this.dayCount() > 0) {
"Until "
} else {
"Since "
}
}
// Num days since date
fun MyEvent.daysSinceDateStr(): String {
return "${this.dayCountAbs()} days ${ifSinceStr()} ${this.formatDateStr()}"
}
fun MyEvent.numDaysStr(): String {
// Handle word pl.
return if (this.dayCountAbs() > 1) {
"${this.dayCountAbs()} days"
} else {
"${this.dayCountAbs()} day"
}
}
fun MyEvent.photoFilename(): String = "IMG_${this.uuid}.jpg"
// For AddEditFragment date field.
fun MyEvent.formatDateStr(): String {
val fmt = DateTimeFormat.forPattern("dd MMM, yyyy")
return DateTime(this.datetime).toString(fmt)
}
fun MyEvent.formatDateStr(millis:Long): String {
val fmt = DateTimeFormat.forPattern("dd MMM, yyyy")
return DateTime(millis).toString(fmt)
}
fun MyEvent.getImageFile(context: Context): File? {
with(File(context.filesDir, this.photoFilename())) {
return if (this.exists()) {
this
} else {
// retrieve or take photo?
// val fileDir = context.filesDir
// return File(fileDir, photoFilename)
null
}
}
}
fun MyEvent.getImagePath(context: Context):String? {
return getImageFile(context)?.path
}
| apache-2.0 | 668054430275be02f49a8a18e409cf69 | 25.449704 | 107 | 0.672707 | 3.740586 | false | false | false | false |
dewarder/Android-Kotlin-Commons | akommons-bindings-common-test/src/main/java/com/dewarder/akommons/binding/common/Constants.kt | 1 | 850 | /*
* Copyright (C) 2017 Artem Hluhovskyi
*
* 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.dewarder.akommons.binding.common
const val NO_VIEW1 = 0
const val NO_VIEW2 = 1
const val NO_DIMEN1 = 0
const val NO_DIMEN2 = 1
const val NO_INTEGER1 = 0
const val NO_INTEGER2 = 1
const val NO_STRING1 = 0
const val NO_STRING2 = 1 | apache-2.0 | fac8aae33b142e32d1debe6a5d13e1d4 | 28.344828 | 75 | 0.734118 | 3.679654 | false | false | false | false |
bozaro/git-as-svn | src/main/kotlin/svnserver/repository/git/filter/GitFilterHelper.kt | 1 | 3209 | /*
* This file is part of git-as-svn. It is subject to the license terms
* in the LICENSE file found in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn,
* including this file, may be copied, modified, propagated, or distributed
* except according to the terms contained in the LICENSE file.
*/
package svnserver.repository.git.filter
import org.eclipse.jgit.lib.ObjectId
import org.mapdb.DB
import org.mapdb.HTreeMap
import org.mapdb.Serializer
import svnserver.HashHelper
import svnserver.StringHelper
import svnserver.repository.git.GitObject
import java.io.IOException
import java.security.MessageDigest
/**
* Helper for common filter functionality.
*
* @author Artem V. Navrotskiy <[email protected]>
*/
object GitFilterHelper {
private const val BUFFER_SIZE: Int = 32 * 1024
@Throws(IOException::class)
fun getSize(filter: GitFilter, cacheMd5: MutableMap<String, String>, cacheSize: MutableMap<String, Long>, objectId: GitObject<out ObjectId>): Long {
val size: Long? = cacheSize[objectId.`object`.name()]
if (size != null) {
return size
}
return createMetadata(objectId, filter, cacheMd5, cacheSize).size
}
@Throws(IOException::class)
private fun createMetadata(objectId: GitObject<out ObjectId>, filter: GitFilter, cacheMd5: MutableMap<String, String>?, cacheSize: MutableMap<String, Long>?): Metadata {
val buffer = ByteArray(BUFFER_SIZE)
filter.inputStream(objectId).use { stream ->
val digest: MessageDigest? = if (cacheMd5 != null) HashHelper.md5() else null
var totalSize: Long = 0
while (true) {
val bytes: Int = stream.read(buffer)
if (bytes <= 0) break
digest?.update(buffer, 0, bytes)
totalSize += bytes.toLong()
}
val md5: String?
if ((cacheMd5 != null) && (digest != null)) {
md5 = StringHelper.toHex(digest.digest())
cacheMd5.putIfAbsent(objectId.`object`.name(), md5)
} else {
md5 = null
}
cacheSize?.putIfAbsent(objectId.`object`.name(), totalSize)
return Metadata(totalSize, md5)
}
}
@Throws(IOException::class)
fun getMd5(filter: GitFilter, cacheMd5: MutableMap<String, String>, cacheSize: MutableMap<String, Long>?, objectId: GitObject<out ObjectId>): String {
val md5: String? = cacheMd5[objectId.`object`.name()]
if (md5 != null) {
return md5
}
return (createMetadata(objectId, filter, cacheMd5, cacheSize).md5)!!
}
fun getCacheMd5(filter: GitFilter, cacheDb: DB): HTreeMap<String, String> {
return cacheDb.hashMap("cache.filter." + filter.name + ".md5", Serializer.STRING, Serializer.STRING).createOrOpen()
}
fun getCacheSize(filter: GitFilter, cacheDb: DB): HTreeMap<String, Long> {
return cacheDb.hashMap("cache.filter." + filter.name + ".size", Serializer.STRING, Serializer.LONG).createOrOpen()
}
private class Metadata(val size: Long, val md5: String?)
}
| gpl-2.0 | 996727883ddabce6a467ecdac01087f0 | 39.620253 | 173 | 0.651916 | 4.222368 | false | false | false | false |
bozaro/git-as-svn | src/test/kotlin/svnserver/TestHelper.kt | 1 | 2099 | /*
* This file is part of git-as-svn. It is subject to the license terms
* in the LICENSE file found in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn,
* including this file, may be copied, modified, propagated, or distributed
* except according to the terms contained in the LICENSE file.
*/
package svnserver
import org.apache.commons.io.FileUtils
import org.apache.commons.io.input.CharSequenceInputStream
import org.eclipse.jgit.internal.storage.dfs.DfsRepositoryDescription
import org.eclipse.jgit.internal.storage.dfs.InMemoryRepository
import org.eclipse.jgit.lib.Repository
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.InputStream
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
/**
* Common test functions.
*
* @author Artem V. Navrotskiy <[email protected]>
*/
object TestHelper {
val logger: Logger = LoggerFactory.getLogger("test")
fun saveFile(file: Path, content: String) {
Files.write(file, content.toByteArray(StandardCharsets.UTF_8))
}
fun createTempDir(prefix: String): Path {
return Files.createTempDirectory(findGitPath().parent.resolve("build/tmp"), "$prefix-").toAbsolutePath()
}
fun findGitPath(): Path {
val root = Paths.get("").toAbsolutePath()
var path = root
while (true) {
val repo = path.resolve(".git")
if (Files.isDirectory(repo)) return repo
path = path.parent
checkNotNull(path) { "Repository not found from directory: $root" }
}
}
fun deleteDirectory(file: Path) {
FileUtils.deleteDirectory(file.toFile())
}
fun asStream(content: String): InputStream {
return CharSequenceInputStream(content, StandardCharsets.UTF_8)
}
fun emptyRepository(): Repository {
val repository: Repository = InMemoryRepository(DfsRepositoryDescription(null))
repository.create()
return repository
}
}
| gpl-2.0 | 75abdd6bff546def75c047fbe1b6105c | 32.854839 | 112 | 0.707003 | 4.140039 | false | false | false | false |
JimSeker/drawing | TextureViewDemo_kt/app/src/main/java/edu/cs4730/textureviewdemo_kt/AllinOneActivity.kt | 1 | 3530 | package edu.cs4730.textureviewdemo_kt
import android.graphics.Color
import android.graphics.Paint
import androidx.appcompat.app.AppCompatActivity
import android.view.TextureView.SurfaceTextureListener
import android.view.TextureView
import android.os.Bundle
import android.widget.FrameLayout
import android.view.Gravity
import android.graphics.SurfaceTexture
import kotlin.jvm.Volatile
import android.graphics.PorterDuff
/**
* original example from here: http://pastebin.com/J4uDgrZ8 with much thanks.
* Everything for the texture in in the MainActivity. And a generic textureView is used
*/
class AllinOneActivity : AppCompatActivity(), SurfaceTextureListener {
private lateinit var mTextureView: TextureView
private lateinit var mThread: RenderingThread
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//get a layout, which we will use later.
val content = FrameLayout(this)
//get a TextureView and set it up with all code below
mTextureView = TextureView(this)
mTextureView.surfaceTextureListener = this
//mTextureView.setOpaque(false); //normally, yes, but we need to see the block here.
//add the TextureView to our layout from above.
content.addView(mTextureView, FrameLayout.LayoutParams(500, 500, Gravity.CENTER))
setContentView(content)
}
/**
* TextureView.SurfaceTextureListener overrides below, that start up the drawing thread.
*/
override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {
mThread = RenderingThread(mTextureView)
mThread.start()
}
override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {
// Ignored
}
override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
mThread.stopRendering()
return true
}
override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {
// Ignored
}
/*
* Thread to draw a green square moving around the textureView.
*/
private class RenderingThread(private val mSurface: TextureView?) : Thread() {
@Volatile
private var mRunning = true
override fun run() {
var x = 0.0f
var y = 0.0f
var speedX = 5.0f
var speedY = 3.0f
val paint = Paint()
paint.color = -0xff0100
while (mRunning && !interrupted()) {
val canvas = mSurface!!.lockCanvas(null)
try {
//canvas.drawColor(0x00000000, PorterDuff.Mode.CLEAR);
canvas!!.drawColor(Color.BLACK, PorterDuff.Mode.CLEAR)
canvas.drawRect(x, y, x + 20.0f, y + 20.0f, paint)
} finally {
mSurface.unlockCanvasAndPost(canvas!!)
}
if (x + 20.0f + speedX >= mSurface.width || x + speedX <= 0.0f) {
speedX = -speedX
}
if (y + 20.0f + speedY >= mSurface.height || y + speedY <= 0.0f) {
speedY = -speedY
}
x += speedX
y += speedY
try {
sleep(15)
} catch (e: InterruptedException) {
// Interrupted
}
}
}
fun stopRendering() {
interrupt()
mRunning = false
}
}
} | apache-2.0 | 148ab2fba008e40390776bb70cbb99eb | 33.281553 | 96 | 0.604816 | 4.868966 | false | false | false | false |
Ztiany/Repository | Kotlin/Kotlin-Basic/src/main/kotlin/me/ztiany/reflects/KotlinReflect.kt | 2 | 6136 | package me.ztiany.reflects
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import kotlin.reflect.KClass
import kotlin.reflect.jvm.javaField
import kotlin.reflect.jvm.javaGetter
/**
*反射:反射是这样的一组语言和库功能,它允许在运行时自省你的程序的结构。
* Kotlin 让语言中的函数和属性做为一等公民、并对其自省(即在运行时获悉一个名称或者一个属性或函数的类型)
* 与简单地使用函数式或响应式风格紧密相关。
*
* Kotlin 的反射有两套 API,因为最终都是编译为字节码,所以 Java 反射 API 通用适用于 Koitlin,另一套是 Kotlin 提供的反射 API。 kotlin的反射功能是一个独立的模块,如果需要使用则需要引入这个模块,模块中核心类包括:
*
* kotlin的反射功能是一个独立的模块,如果需要使用则需要引入这个模块,模块中核心类包括:
*
* KTypes
* KClasses
* KProperties
* KCallables:是函数和属性的超接口
*
* 内容:
*
* 1,类引用
* 2,函数引用
* 3,属性引用
* 4, 构造函数引用
* 5,与Java平台的互操作
* 6,绑定对象的函数和属性引用
*
* 另外可以参考:重新审视 Kotlin 反射,我觉得可以合理使用,https://mp.weixin.qq.com/s/ScufhaG8Pu5gk_fF3rW90g
*/
//类引用
private fun classReference() {
//类引用:该引用是 KClass 类型的值。
val strClazz = String::class
println(strClazz)
//Java类引用:Kotlin 类引用与 Java 类引用不同。要获得 Java 类引用,需要在 KClass 实例上使用 .java 属性
println(String::class)
println(String::class.java)
//绑定的类引用
//通过使用对象作为接收者,可以用相同的 ::class 语法获取指定对象的类的引用
val str = "ABC"
println(str::class)
println(str::class.java)
}
//函数引用
private fun functionReference() {
fun isOdd(x: Int) = x % 2 != 0
val numbers = listOf(1, 2, 3)
println(numbers.filter(::isOdd))//::isOdd 是函数类型 (Int) -> Boolean 的一个值
//当上下文中已知函数期望的类型时,:: 可以用于重载函数
fun isOdd(s: String) = s == "brillig" || s == "slithy" || s == "tove"
println(numbers.filter(::isOdd))//// 引用到 isOdd(x: Int)
//可以通过将方法引用存储在具有显式指定类型的变量中来提供必要的上下文
val predicate: (String) -> Boolean = ::isOdd
//如果我们需要使用类的成员函数或扩展函数,它需要是限定的
//String::toCharArray 是类型 String 提供了一个扩展函数:String.() -> CharArray。
fun toCharArray(lambda: (String) -> CharArray) {
lambda("abc")
}
toCharArray(String::toCharArray)
//示例:函数组合
fun <A, B, C> compose(f: (B) -> C, g: (A) -> B): (A) -> C {
return { x -> f(g(x)) }
}
fun length(s: String) = s.length
val oddLength = compose(::isOdd, ::length)
val strings = listOf("a", "ab", "abc")
println(strings.filter(oddLength)) // 输出 "[a, abc]"
}
//属性引用
private val number = 233
private class PropertyA(val p: Int)
private val String.lastChar: Char get() = this[length - 1]
private fun propertiesReference() {
//要把属性作为 Kotlin中 的一等对象来访问,我们也可以使用 :: 运算符
//表达式 ::x 求值为 KProperty<Int> 类型的属性对象
println(::number.get())
//属性引用可以用在不需要参数的函数处
val strList = listOf("a", "bc", "def")
println(strList.map(String::length))
//访问属于类的成员的属性
val prop = PropertyA::p
println(prop.get(PropertyA(1))) // 输出 "1"
//对于扩展属性
println(String::lastChar.get("abc")) // 输出 "c"
}
//与 Java 反射的互操作性
private fun interactJava() {
//在Java平台上,标准库包含反射类的扩展,它提供了与 Java 反射对象之间映射(kotlin.reflect.jvm)
//查找一个用作 Kotlin 属性 getter 的 幕后字段或 Java方法
println(PropertyA::p.javaGetter)
//获得对应于 Java 类的 Kotlin 类
fun getKClass(o: Any): KClass<Any> = o.javaClass.kotlin
println(getKClass("abc"))
}
//构造函数引用
private fun constructorReference() {
//构造函数可以像方法和属性那样引用。他们可以用于期待这样的函数类型对象的任何地方
//:它与该构造函数接受相同参数并且返回相应类型的对象。 通过使用 :: 操作符并添加类名来引用构造函数。
class Foo
fun function(factory: () -> Foo) {
val x: Foo = factory()
}
//::Foo引用Foo的构造函数
println(function(::Foo))
Foo::class.constructors.forEach {
println(it)
}
}
//绑定的函数与属性引用
private fun bindingFunctionAndPropertyReference() {
//可以引用特定对象的实例方法
val numberRegex = "\\d+".toRegex()
println(numberRegex.matches("29")) // 输出“true”
val isNumber: (String) -> Boolean = numberRegex::matches
println(isNumber)
println(isNumber("29"))
//属性引用也可以绑定
val lengthProp = "abc"::length
println(lengthProp.get()) // 输出“3”
//比较绑定的类型和相应的未绑定类型的引用。 绑定的可调用引用有其接收者“附加”到其上,因此接收者的类型不再是参数
/*绑定非绑定*/
val str = "ABC"
val kFunction1 = str::get
kFunction1.invoke(0)
val kFunction2 = String::get
kFunction2.invoke(str, 0)
}
class LiveData<T>
class Resource<T>
class SalesPlanModel
class A {
val pendingSalesPlanList: LiveData<Resource<List<SalesPlanModel>>> = LiveData()
}
fun main(args: Array<String>) {
println(getType(A::pendingSalesPlanList.javaField!!.genericType))
}
private fun getType(type: Type): Type {
if (type !is ParameterizedType) {
return type
}
return getType(type.actualTypeArguments[0])
}
| apache-2.0 | 7d89d9c0f7841f785133f493b10a0ffc | 23.010811 | 131 | 0.65466 | 2.813173 | false | false | false | false |
martin-nordberg/KatyDOM | Katydid-VDOM-JS/src/main/kotlin/i/katydid/vdom/elements/forms/KatydidInputUrl.kt | 1 | 2791 | //
// (C) Copyright 2017-2019 Martin E. Nordberg III
// Apache 2.0 License
//
package i.katydid.vdom.elements.forms
import i.katydid.vdom.builders.KatydidPhrasingContentBuilderImpl
import i.katydid.vdom.elements.KatydidHtmlElementImpl
import o.katydid.vdom.builders.KatydidAttributesContentBuilder
import o.katydid.vdom.types.EDirection
//---------------------------------------------------------------------------------------------------------------------
/**
* Virtual node for an input type="url" element.
*/
internal class KatydidInputUrl<Msg>(
phrasingContent: KatydidPhrasingContentBuilderImpl<Msg>,
selector: String?,
key: Any?,
accesskey: Char?,
autocomplete: String?,
autofocus: Boolean?,
contenteditable: Boolean?,
dir: EDirection?,
disabled: Boolean?,
draggable: Boolean?,
form: String?,
hidden: Boolean?,
lang: String?,
list: String?,
maxlength: Int?,
minlength: Int?,
name: String?,
pattern: String?,
placeholder: String?,
readonly: Boolean?,
required: Boolean?,
size: Int?,
spellcheck: Boolean?,
style: String?,
tabindex: Int?,
title: String?,
translate: Boolean?,
value: String?,
defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit
) : KatydidHtmlElementImpl<Msg>(selector, key ?: name, accesskey, contenteditable, dir, draggable,
hidden, lang, spellcheck, style, tabindex, title, translate) {
init {
phrasingContent.contentRestrictions.confirmInteractiveContentAllowed()
require(maxlength == null || maxlength >= 0) { "Attribute maxlength must be non-negative." }
require(minlength == null || minlength >= 0) { "Attribute minlength must be non-negative." }
require(size == null || size >= 0) { "Attribute size must be non-negative." }
setAttribute("autocomplete", autocomplete)
setBooleanAttribute("autofocus", autofocus)
setBooleanAttribute("disabled", disabled)
setAttribute("form", form)
setAttribute("list", list)
setNumberAttribute("maxlength", maxlength)
setNumberAttribute("minlength", minlength)
setAttribute("name", name)
setAttribute("pattern", pattern)
setAttribute("placeholder", placeholder)
setBooleanAttribute("readonly", readonly)
setBooleanAttribute("required", required)
setNumberAttribute("size", size)
setAttribute("value", value)
setAttribute("type", "url")
phrasingContent.attributesContent(this).defineAttributes()
this.freeze()
}
////
override val nodeName = "INPUT"
}
//---------------------------------------------------------------------------------------------------------------------
| apache-2.0 | 357f7bf3d754f62dda8317da931e382a | 31.453488 | 119 | 0.609459 | 5.187732 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/model/SuggestionItem.kt | 1 | 1922 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.model
import android.database.Cursor
import de.vanita5.twittnuker.provider.TwidereDataStore.Suggestions
class SuggestionItem(cursor: Cursor, indices: Indices) {
val title: String?
val summary: String?
val _id: Long
val extra_id: String?
init {
_id = if (indices._id < 0) -1 else cursor.getLong(indices._id)
title = cursor.getString(indices.title)
summary = cursor.getString(indices.summary)
extra_id = cursor.getString(indices.extra_id)
}
class Indices(cursor: Cursor) {
val _id: Int = cursor.getColumnIndex(Suggestions._ID)
val type: Int = cursor.getColumnIndex(Suggestions.TYPE)
val title: Int = cursor.getColumnIndex(Suggestions.TITLE)
val value: Int = cursor.getColumnIndex(Suggestions.VALUE)
val summary: Int = cursor.getColumnIndex(Suggestions.SUMMARY)
val icon: Int = cursor.getColumnIndex(Suggestions.ICON)
val extra_id: Int = cursor.getColumnIndex(Suggestions.EXTRA_ID)
}
} | gpl-3.0 | 9e4f1639a8615c088171305f7c4a6d9b | 35.980769 | 72 | 0.713319 | 4.089362 | false | false | false | false |
stripe/stripe-android | identity/src/main/java/com/stripe/android/identity/ui/DocumenetScanScreen.kt | 1 | 6007 | package com.stripe.android.identity.ui
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import com.google.android.material.composethemeadapter.MdcTheme
import com.stripe.android.camera.scanui.CameraView
import com.stripe.android.identity.R
import com.stripe.android.identity.states.IdentityScanState
internal const val CONTINUE_BUTTON_TAG = "Continue"
internal const val SCAN_TITLE_TAG = "Title"
internal const val SCAN_MESSAGE_TAG = "Message"
internal const val CHECK_MARK_TAG = "CheckMark"
internal const val VIEW_FINDER_ASPECT_RATIO = 1.5f
@Composable
internal fun DocumentScanScreen(
title: String,
message: String,
newDisplayState: IdentityScanState?,
onCameraViewCreated: (CameraView) -> Unit,
onContinueClicked: () -> Unit
) {
MdcTheme {
Column(
modifier = Modifier
.fillMaxSize()
.padding(
vertical = dimensionResource(id = R.dimen.page_vertical_margin),
horizontal = dimensionResource(id = R.dimen.page_horizontal_margin)
)
) {
var loadingButtonState by remember(newDisplayState) {
mutableStateOf(
if (newDisplayState is IdentityScanState.Finished) {
LoadingButtonState.Idle
} else {
LoadingButtonState.Disabled
}
)
}
Column(
modifier = Modifier
.weight(1f)
.verticalScroll(rememberScrollState())
) {
Text(
text = title,
modifier = Modifier
.fillMaxWidth()
.semantics {
testTag = SCAN_TITLE_TAG
},
fontSize = 24.sp,
fontWeight = FontWeight.Bold
)
Text(
text = message,
modifier = Modifier
.fillMaxWidth()
.height(100.dp)
.padding(
top = dimensionResource(id = R.dimen.item_vertical_margin),
bottom = 48.dp
)
.semantics {
testTag = SCAN_MESSAGE_TAG
},
maxLines = 3,
overflow = TextOverflow.Ellipsis
)
CameraViewFinder(onCameraViewCreated, newDisplayState)
}
LoadingButton(
modifier = Modifier.testTag(CONTINUE_BUTTON_TAG),
text = stringResource(id = R.string.kontinue).uppercase(),
state = loadingButtonState
) {
loadingButtonState = LoadingButtonState.Loading
onContinueClicked()
}
}
}
}
@Composable
private fun CameraViewFinder(
onCameraViewCreated: (CameraView) -> Unit,
newScanState: IdentityScanState?
) {
Box(
modifier = Modifier
.fillMaxWidth()
.aspectRatio(VIEW_FINDER_ASPECT_RATIO)
.clip(RoundedCornerShape(dimensionResource(id = R.dimen.view_finder_corner_radius)))
) {
AndroidView(
modifier = Modifier.fillMaxSize(),
factory = {
CameraView(
it,
CameraView.ViewFinderType.ID,
R.drawable.viewfinder_border_initial
)
},
update = {
onCameraViewCreated(it)
}
)
if (newScanState is IdentityScanState.Finished) {
Box(
modifier = Modifier
.fillMaxSize()
.background(
colorResource(id = R.color.check_mark_background)
)
.testTag(CHECK_MARK_TAG)
) {
Image(
modifier = Modifier
.fillMaxSize()
.padding(60.dp),
painter = painterResource(id = R.drawable.check_mark),
contentDescription = stringResource(id = R.string.check_mark),
colorFilter = ColorFilter.tint(MaterialTheme.colors.primary),
)
}
}
}
}
| mit | f27c531d7d4af71f441c13d600b2714c | 35.852761 | 96 | 0.586482 | 5.315929 | false | false | false | false |
peterLaurence/TrekAdvisor | app/src/main/java/com/peterlaurence/trekme/viewmodel/markermanage/MakerManageViewModel.kt | 1 | 1419 | package com.peterlaurence.trekme.viewmodel.markermanage
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.peterlaurence.trekme.core.map.Map
class MakerManageViewModel : ViewModel() {
private val geographicCoords = MutableLiveData<GeographicCoords>()
private val projectedCoords = MutableLiveData<ProjectedCoords>()
fun getGeographicLiveData(): LiveData<GeographicCoords> = geographicCoords
fun getProjectedLiveData(): LiveData<ProjectedCoords> = projectedCoords
/**
* Called when the view had one of the geographic coordinates edited, and requires an update of
* the projected coordinates.
*/
fun onGeographicValuesChanged(map: Map, lat: Double, lon: Double) {
map.projection?.doProjection(lat, lon)?.also {
projectedCoords.postValue(ProjectedCoords(X = it[0], Y = it[1]))
}
}
/**
* Called when the view had one of the projected coordinates edited, and requires an updates of
* the geographic coordinates.
*/
fun onProjectedCoordsChanged(map: Map, X: Double, Y: Double) {
map.projection?.undoProjection(X, Y)?.also {
geographicCoords.postValue(GeographicCoords(lon = it[0], lat = it[1]))
}
}
}
data class GeographicCoords(val lon: Double, val lat: Double)
data class ProjectedCoords(val X: Double, val Y: Double) | gpl-3.0 | 56570414a4d403c1adab016dc39ef40a | 36.368421 | 99 | 0.718111 | 4.420561 | false | false | false | false |
vanniktech/gradle-code-quality-tools-plugin | src/main/kotlin/com/vanniktech/code/quality/tools/LintExtension.kt | 1 | 1931 | package com.vanniktech.code.quality.tools
import java.io.File
open class LintExtension {
/**
* Ability to enable or disable only lint for every subproject that is not ignored.
* @since 0.2.0
*/
var enabled: Boolean = true
/**
* Enable or disable textReport.
* @since 0.2.0
*/
var textReport: Boolean? = true
/**
* Specify the textOutput for lint. It will only be used when [textReport] is set to true.
* @since 0.2.0
*/
var textOutput: String = "stdout"
/**
* If set to false or true it overrides [CodeQualityToolsPluginExtension#failEarly].
* @since 0.2.0
*/
var abortOnError: Boolean? = null
/**
* If set to false or true it overrides [CodeQualityToolsPluginExtension#failEarly].
* @since 0.2.0
*/
var warningsAsErrors: Boolean? = null
/**
* Returns whether lint should check all warnings, including those off by default.
* @since 0.5.0
*/
var checkAllWarnings: Boolean? = null
/**
* The baseline file name (e.g. baseline.xml) which will be saved under each project.
* @since 0.5.0
*/
var baselineFileName: String? = null
/**
* Returns whether lint should use absolute paths or not.
* @since 0.9.0
*/
var absolutePaths: Boolean? = null
/**
* The lint config file (e.g. lint.xml).
* @since 0.9.0
*/
var lintConfig: File? = null
/**
* Returns whether lint should check release builds or not.
* Since this plugin hooks lint into the check task we'll assume that you're always running
* the full lint suite and hence checking release builds is not necessary.
* @since 0.10.0
*/
var checkReleaseBuilds: Boolean? = false
/**
* Returns whether lint should check test sources or not.
* @since 0.13.0
*/
var checkTestSources: Boolean? = true
/**
* Returns whether lint should check dependencies or not.
* @since 0.13.0
*/
var checkDependencies: Boolean? = null
}
| apache-2.0 | c5ef42317aa486d147545293e70055bc | 23.443038 | 93 | 0.656137 | 3.749515 | false | false | false | false |
Dr-Horv/Advent-of-Code-2017 | src/main/kotlin/solutions/day22/Day22.kt | 1 | 2871 | package solutions.day22
import solutions.Solver
import utils.Coordinate
import utils.Direction
import utils.step
fun Direction.left() = when (this) {
Direction.UP -> Direction.LEFT
Direction.LEFT -> Direction.DOWN
Direction.RIGHT -> Direction.UP
Direction.DOWN -> Direction.RIGHT
}
fun Direction.right() = when (this) {
Direction.UP -> Direction.RIGHT
Direction.LEFT -> Direction.UP
Direction.RIGHT -> Direction.DOWN
Direction.DOWN -> Direction.LEFT
}
private fun Direction.reverse(): Direction = when (this) {
Direction.UP -> Direction.DOWN
Direction.LEFT -> Direction.RIGHT
Direction.RIGHT -> Direction.LEFT
Direction.DOWN -> Direction.UP
}
enum class NodeState {
CLEAN,
WEAKENED,
INFECTED,
FLAGGED
}
class Day22 : Solver {
override fun solve(input: List<String>, partTwo: Boolean): String {
val grid = mutableMapOf<Coordinate, NodeState>().withDefault { NodeState.CLEAN }
val startY = (input.size / 2)
input.forEachIndexed { y, line ->
val startX = -(line.length / 2)
line.forEachIndexed { i, c ->
val coordinate = Coordinate(startX + i, startY - y)
when (c) {
'#' -> grid.put(coordinate, NodeState.INFECTED)
}
}
}
var carrier = Coordinate(0, 0)
var direction = Direction.UP
val nodeModifier: (s: NodeState) -> NodeState = if (partTwo) {
{ s ->
when (s) {
NodeState.CLEAN -> NodeState.WEAKENED
NodeState.WEAKENED -> NodeState.INFECTED
NodeState.INFECTED -> NodeState.FLAGGED
NodeState.FLAGGED -> NodeState.CLEAN
}
}
} else {
{ s ->
when (s) {
NodeState.CLEAN -> NodeState.INFECTED
NodeState.INFECTED -> NodeState.CLEAN
else -> throw RuntimeException("Invalid state $s")
}
}
}
val bursts = if(partTwo) {
10_000_000
} else {
10_000
}
var infectionBursts = 0
for (burst in 1..bursts) {
val state = grid.getValue(carrier)
direction = when (state) {
NodeState.CLEAN -> direction.left()
NodeState.WEAKENED -> direction
NodeState.INFECTED -> direction.right()
NodeState.FLAGGED -> direction.reverse()
}
val nextState = nodeModifier(state)
if(nextState == NodeState.INFECTED) {
infectionBursts++
}
grid.put(carrier, nextState)
carrier = carrier.step(direction)
}
return infectionBursts.toString()
}
}
| mit | ee619f3f4ae14e5db763baa07ee01093 | 26.342857 | 88 | 0.538488 | 4.645631 | false | false | false | false |
androidx/androidx | health/connect/connect-client/src/main/java/androidx/health/connect/client/records/WheelchairPushesRecord.kt | 3 | 3020 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.health.connect.client.records
import androidx.health.connect.client.aggregate.AggregateMetric
import androidx.health.connect.client.records.metadata.Metadata
import java.time.Instant
import java.time.ZoneOffset
/**
* Captures the number of wheelchair pushes done since the last reading. Each push is only reported
* once so records shouldn't have overlapping time. The start time of each record should represent
* the start of the interval in which pushes were made.
*/
public class WheelchairPushesRecord(
override val startTime: Instant,
override val startZoneOffset: ZoneOffset?,
override val endTime: Instant,
override val endZoneOffset: ZoneOffset?,
/** Count. Required field. Valid range: 1-1000000. */
public val count: Long,
override val metadata: Metadata = Metadata.EMPTY,
) : IntervalRecord {
init {
requireNonNegative(value = count, name = "count")
count.requireNotMore(other = 1000_000, name = "count")
require(startTime.isBefore(endTime)) { "startTime must be before endTime." }
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is WheelchairPushesRecord) return false
if (count != other.count) return false
if (startTime != other.startTime) return false
if (startZoneOffset != other.startZoneOffset) return false
if (endTime != other.endTime) return false
if (endZoneOffset != other.endZoneOffset) return false
if (metadata != other.metadata) return false
return true
}
override fun hashCode(): Int {
var result = 0
result = 31 * result + count.hashCode()
result = 31 * result + (startZoneOffset?.hashCode() ?: 0)
result = 31 * result + endTime.hashCode()
result = 31 * result + (endZoneOffset?.hashCode() ?: 0)
result = 31 * result + metadata.hashCode()
return result
}
companion object {
/**
* Metric identifier to retrieve the total wheelchair push count from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val COUNT_TOTAL: AggregateMetric<Long> =
AggregateMetric.longMetric(
"WheelchairPushes",
AggregateMetric.AggregationType.TOTAL,
"count"
)
}
}
| apache-2.0 | 39f21c18a92376012eed02346bc97c20 | 36.283951 | 99 | 0.674503 | 4.674923 | false | false | false | false |
markusressel/TypedPreferences | app/src/main/java/de/markusressel/typedpreferencesdemo/PreferencesFragment.kt | 1 | 5565 | /*
* Copyright (c) 2017 Markus Ressel
*
* 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 de.markusressel.typedpreferencesdemo
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.support.annotation.ArrayRes
import android.support.v4.util.SparseArrayCompat
import android.support.v7.preference.Preference
import com.github.ajalt.timberkt.Timber
import de.markusressel.typedpreferences.PreferenceItem
import de.markusressel.typedpreferencesdemo.dagger.DaggerPreferenceFragment
import javax.inject.Inject
/**
* Created by Markus on 18.07.2017.
*/
class PreferencesFragment : DaggerPreferenceFragment(), SharedPreferences.OnSharedPreferenceChangeListener {
override fun onSharedPreferenceChanged(p0: SharedPreferences?, p1: String?) {
val cachedValue = preferenceHandler.getValue(PreferenceHandler.BOOLEAN_SETTING)
val nonCachedValue = preferenceHandler.getValue(PreferenceHandler.BOOLEAN_SETTING, false)
Timber.d { "Cached: $cachedValue NonCached: $nonCachedValue" }
}
@Inject
lateinit var preferenceHandler: PreferenceHandler
@Inject
lateinit var appContext: Context
private lateinit var themeMap: SparseArrayCompat<String>
private lateinit var theme: IntListPreference
private lateinit var booleanPreference: Preference
private lateinit var complex: Preference
private lateinit var clearAll: Preference
private var booleanSettingListener: ((PreferenceItem<Boolean>, Boolean, Boolean) -> Unit)? = null
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
// set preferences file name
preferenceManager.sharedPreferencesName = preferenceHandler.sharedPreferencesName
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences)
initializePreferenceItems()
addListeners()
preferenceManager.sharedPreferences.registerOnSharedPreferenceChangeListener(this)
}
private fun addListeners() {
val hasPreference = preferenceHandler.hasPreference(PreferenceHandler.BOOLEAN_SETTING)
Timber.d { "PreferenceHandler has boolean preference: " + hasPreference }
booleanSettingListener = preferenceHandler.addOnPreferenceChangedListener(PreferenceHandler.BOOLEAN_SETTING) { preference, old, new ->
Timber.d { "Preference '${preference.getKey(appContext)}' changed from '$old' to '$new'" }
}
preferenceHandler.addOnPreferenceChangedListener(PreferenceHandler.THEME) { preference, old, new ->
theme.summary = themeMap.get(new)
// restart activity
activity?.finish()
val intent = Intent(activity, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
}
}
private fun initializePreferenceItems() {
theme = findPreference(PreferenceHandler.THEME.getKey(appContext)) as IntListPreference
theme.setDefaultValue(PreferenceHandler.THEME.defaultValue)
themeMap = getListPreferenceEntryValueMap(R.array.theme_values, R.array.theme_names)
theme.summary = themeMap.get(preferenceHandler.getValue(PreferenceHandler.THEME))
booleanPreference = findPreference(PreferenceHandler.BOOLEAN_SETTING.getKey(appContext))
complex = findPreference(PreferenceHandler.COMPLEX_SETTING.getKey(appContext))
val value = preferenceHandler.getValue(PreferenceHandler.COMPLEX_SETTING)
complex.summary = value.toString()
clearAll = findPreference(getString(R.string.key_clear_all))
clearAll.onPreferenceClickListener = Preference.OnPreferenceClickListener {
preferenceHandler.clearAll()
false
}
}
/**
* Gets a Map from two array resources
*
* @param valueRes values stored in preferences
* @param nameRes name/description of this option used in view
* @return Map from stored value -> display name
*/
private fun getListPreferenceEntryValueMap(@ArrayRes valueRes: Int, @ArrayRes nameRes: Int): SparseArrayCompat<String> {
val map = SparseArrayCompat<String>()
val values = resources.getStringArray(valueRes)
val names = resources.getStringArray(nameRes)
for (i in values.indices) {
map.put(Integer.valueOf(values[i]), names[i])
}
return map
}
override fun onPause() {
super.onPause()
// remove a single listener
booleanSettingListener?.let {
preferenceHandler.removeOnPreferenceChangedListener(it)
}
// remove all listeners of a specific preference
preferenceHandler.removeAllOnPreferenceChangedListeners(PreferenceHandler.BOOLEAN_SETTING)
// remove all listeners of the handler
preferenceHandler.removeAllOnPreferenceChangedListeners()
}
}
| apache-2.0 | 6d04e67b041d37e3a1cad6b48b030ba5 | 37.916084 | 142 | 0.728841 | 5.235183 | false | false | false | false |
oleksiyp/mockk | mockk/common/src/main/kotlin/io/mockk/impl/stub/ConstructorStub.kt | 1 | 2934 | package io.mockk.impl.stub
import io.mockk.*
import io.mockk.MockKGateway.ExclusionParameters
import io.mockk.impl.InternalPlatform
import kotlin.reflect.KClass
class ConstructorStub(
val mock: Any,
val representativeMock: Any,
val stub: Stub,
val recordPrivateCalls: Boolean
) : Stub {
private val represent = identityMapOf(mock to representativeMock)
private val revertRepresentation = identityMapOf(representativeMock to mock)
private fun <K, V> identityMapOf(vararg pairs: Pair<K, V>): Map<K, V> =
InternalPlatform.identityMap<K, V>()
.also { map -> map.putAll(pairs) }
override val name: String
get() = stub.name
override val type: KClass<*>
get() = stub.type
override fun addAnswer(matcher: InvocationMatcher, answer: Answer<*>) =
stub.addAnswer(matcher.substitute(represent), answer)
override fun answer(invocation: Invocation) = stub.answer(
invocation.substitute(represent)
).internalSubstitute(revertRepresentation)
override fun childMockK(matcher: InvocationMatcher, childType: KClass<*>) =
stub.childMockK(
matcher.substitute(represent),
childType
)
override fun recordCall(invocation: Invocation) {
val record = if (recordPrivateCalls)
true
else
!invocation.method.privateCall
if (record) {
stub.recordCall(invocation.substitute(represent))
}
}
override fun excludeRecordedCalls(params: ExclusionParameters, matcher: InvocationMatcher) {
stub.excludeRecordedCalls(
params,
matcher.substitute(represent)
)
}
override fun markCallVerified(invocation: Invocation) {
stub.markCallVerified(
invocation.substitute(represent)
)
}
override fun allRecordedCalls() = stub.allRecordedCalls()
.map {
it.substitute(revertRepresentation)
}
override fun allRecordedCalls(method: MethodDescription) =
stub.allRecordedCalls(method)
.map {
it.substitute(revertRepresentation)
}
override fun verifiedCalls() = stub.verifiedCalls()
.map {
it.substitute(revertRepresentation)
}
override fun clear(options: MockKGateway.ClearOptions) =
stub.clear(options)
override fun handleInvocation(
self: Any,
method: MethodDescription,
originalCall: () -> Any?,
args: Array<out Any?>,
fieldValueProvider: BackingFieldValueProvider
) = stub.handleInvocation(
self,
method,
originalCall,
args,
fieldValueProvider
)
override fun toStr() = stub.toStr()
override fun stdObjectAnswer(invocation: Invocation) = stub.stdObjectAnswer(invocation.substitute(represent))
override fun dispose() = stub.dispose()
} | apache-2.0 | 59410305e2013ddbdd0c0fd4b8092b26 | 28.35 | 113 | 0.648943 | 4.873754 | false | false | false | false |
initrc/android-bootstrap | app/src/main/java/util/AnimationUtils.kt | 1 | 3055 | package util
import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.view.View
import android.view.animation.AccelerateInterpolator
import android.view.animation.DecelerateInterpolator
/**
* Animation utils.
*/
object AnimationUtils {
fun show(view: View, alpha: Boolean = true, scale: Boolean = false, rotate: Boolean = false) {
if (view.visibility == View.VISIBLE) return
view.visibility = View.VISIBLE
val animators = ArrayList<Animator>().apply {
if (alpha) add(ObjectAnimator.ofFloat(view, "alpha", 0f, 1f))
if (scale) add(ObjectAnimator.ofFloat(view, "scaleX", 0f, 1f))
if (scale) add(ObjectAnimator.ofFloat(view, "scaleY", 0f, 1f))
if (rotate) add(ObjectAnimator.ofFloat(view, "rotation", 270f, 0f))
}
AnimatorSet().apply {
playTogether(animators)
start()
}
}
fun hide(view: View, alpha: Boolean = true, scale: Boolean = false, rotate: Boolean = false) {
if (view.visibility != View.VISIBLE) return
val animators = ArrayList<Animator>().apply {
if (alpha) add(ObjectAnimator.ofFloat(view, "alpha", 0f))
if (scale) add(ObjectAnimator.ofFloat(view, "scaleX", 0f))
if (scale) add(ObjectAnimator.ofFloat(view, "scaleY", 0f))
if (rotate) add(ObjectAnimator.ofFloat(view, "rotation", 270f))
}
AnimatorSet().apply {
playTogether(animators)
onAnimationEnd({ view.visibility = View.GONE })
start()
}
}
fun showFab(view: View) {
show(view, true, true, true)
}
fun hideFab(view: View) {
hide(view, true, true, true)
}
fun slideFromRight(views: List<View>) {
var animators = ArrayList<Animator>()
for (i in views.indices) {
views[i].let {
it.translationX = 400f
val animator = ObjectAnimator.ofFloat(it, "translationX", 0f).apply {
startDelay = i * 50L
interpolator = DecelerateInterpolator()
duration = 150
}
animators.add(animator)
}
}
AnimatorSet().apply {
playTogether(animators)
start()
}
}
fun slideToRight(views: List<View>, onAnimationEnd: () -> Unit) {
var animators = ArrayList<Animator>()
for (i in views.indices) {
views[i].let {
it.translationX = 0f
val animator = ObjectAnimator.ofFloat(it, "translationX", 400f).apply {
startDelay = i * 50L
interpolator = AccelerateInterpolator()
duration = 150
}
animators.add(animator)
}
}
AnimatorSet().apply {
playTogether(animators)
onAnimationEnd { onAnimationEnd() }
start()
}
}
}
| mit | 1a367238d553068879f3dcc4512164c8 | 32.944444 | 98 | 0.559083 | 4.635812 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/forge/reflection/reference/ReflectedMethodReference.kt | 1 | 7064 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 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 | 6c9a80c87f03155e0e92e9a96a3b0941 | 45.473684 | 118 | 0.570074 | 6.39276 | false | false | false | false |
Tvede-dk/CommonsenseAndroidKotlin | widgets/src/main/kotlin/com/commonsense/android/kotlin/views/databinding/adapters/BaseDataBindingRecyclerAdapter.kt | 1 | 28236 | @file:Suppress("unused", "NOTHING_TO_INLINE", "MemberVisibilityCanBePrivate")
package com.commonsense.android.kotlin.views.databinding.adapters
import android.support.annotation.IntRange
import android.content.*
import android.databinding.ViewDataBinding
import android.support.annotation.AnyThread
import android.support.annotation.UiThread
import android.support.v7.widget.RecyclerView
import android.view.*
import com.commonsense.android.kotlin.base.*
import com.commonsense.android.kotlin.base.debug.prettyStringContent
import com.commonsense.android.kotlin.base.extensions.*
import com.commonsense.android.kotlin.base.extensions.collections.*
import com.commonsense.android.kotlin.system.datastructures.*
import com.commonsense.android.kotlin.system.logging.*
import com.commonsense.android.kotlin.views.*
import com.commonsense.android.kotlin.views.extensions.*
import java.lang.ref.*
import kotlin.reflect.*
/**
* Created by kasper on 17/05/2017.
*/
/**
* Describes the required for inflating a given ViewVBinding
* VM is the viewbinding class
*/
typealias InflatingFunction<Vm> = (inflater: LayoutInflater, parent: ViewGroup?, attach: Boolean) -> BaseViewHolderItem<Vm>
/**
* Defines the required information for a data binding recycler adapter.
* @param T : ViewDataBinding the view to contain
* @property item T the data for the view
* @property viewBindingTypeValue Int the view type (a unique number for the view)
*/
open class BaseViewHolderItem<out T : ViewDataBinding>(val item: T) : RecyclerView.ViewHolder(item.root) {
/**
* The view's "type", which is the type of the class (which is unique, by jvm specification).
*/
val viewBindingTypeValue = item.javaClass.hashCode()
}
/**
*
* @param T : Any
* @param Vm : ViewDataBinding
*/
interface IRenderModelItem<T : Any, Vm : ViewDataBinding> :
TypeHashCodeLookupRepresent<InflatingFunction<Vm>> {
/**
* Gets the data associated with this binding
* @return T
*/
fun getValue(): T
/**
* Renders the given model to the given view, via the view holder
* @param view Vm the view to update with the model
* @param model T the model data associated with this view type
* @param viewHolder BaseViewHolderItem<Vm> the view holder containing the view and data
*/
fun renderFunction(view: Vm, model: T, viewHolder: BaseViewHolderItem<Vm>)
/**
* Binds this to the given view holder.
* @param holder BaseViewHolderItem<*>
*/
fun bindToViewHolder(holder: BaseViewHolderItem<*>)
/**
* Creates the view holder from the given (potentially newly inflated) view.
* @param inflatedView Vm the view binding
* @return BaseViewHolderItem<Vm> a valid view holder for the given view binding
*/
fun createViewHolder(inflatedView: Vm): BaseViewHolderItem<Vm>
/**
* Gets the inflater function to create the view for this
* @return ViewInflatingFunction<Vm> the function that can create the view;
*/
fun getInflaterFunction(): ViewInflatingFunction<Vm>
}
/**
* The Root of databinding render models (factors the most common stuff out)
* creates a renderable model that can render it self.
* @param T : Any the data associated with this render
* @param Vm : ViewDataBinding the view associated with this render
*/
abstract class BaseRenderModel<
T : Any,
Vm : ViewDataBinding>(val item: T, classType: Class<Vm>)
: IRenderModelItem<T, Vm> {
/**
* Convenience constructor, same as original but using kotlin's classes instead.
* @param item T the data to use
* @param classType KClass<Vm> the view class type
*/
constructor(item: T, classType: KClass<Vm>) : this(item, classType.java)
override fun getValue(): T = item
override fun getTypeValue() = vmTypeValue
private val vmTypeValue: Int by lazy {
classType.hashCode()
}
override fun bindToViewHolder(holder: BaseViewHolderItem<*>) {
val casted = holder.cast<BaseViewHolderItem<Vm>>()
if (casted != null) {
renderFunction(casted.item, item, casted)
//we are now "sure" that the binding class is the same as ours, thus casting "should" be "ok". (we basically introduced our own type system)
} else {
L.debug("RenderModelItem",
"unable to bind to view even though it should be correct type$vmTypeValue expected, got : ${holder.viewBindingTypeValue}")
}
}
override fun createViewHolder(inflatedView: Vm): BaseViewHolderItem<Vm> =
BaseViewHolderItem(inflatedView)
override fun getCreatorFunction(): InflatingFunction<Vm> {
return { inflater: LayoutInflater, parent: ViewGroup?, attach: Boolean ->
createViewHolder(getInflaterFunction().invoke(inflater, parent, attach))
}
}
}
/**
* A simple renderable model containing all information required for a databinding recycler adapter
* @param T : Any the data associated with this render
* @param Vm : ViewDataBinding the view associated with this render
* @constructor
*/
open class RenderModel<
T : Any,
Vm : ViewDataBinding>(private val item: T,
private val vmInflater: ViewInflatingFunction<Vm>,
private val classType: Class<Vm>,
private val vmRender: (view: Vm, model: T, viewHolder: BaseViewHolderItem<Vm>) -> Unit)
: IRenderModelItem<T, Vm> {
override fun getInflaterFunction() = vmInflater
override fun createViewHolder(inflatedView: Vm): BaseViewHolderItem<Vm> =
BaseViewHolderItem(inflatedView)
override fun getCreatorFunction(): InflatingFunction<Vm> {
return { inflater: LayoutInflater, parent: ViewGroup?, attach: Boolean ->
createViewHolder(vmInflater(inflater, parent, attach))
}
}
override fun getValue(): T = item
override fun getTypeValue(): Int = vmTypeValue
override fun renderFunction(view: Vm, model: T, viewHolder: BaseViewHolderItem<Vm>) = vmRender(view, model, viewHolder)
override fun bindToViewHolder(holder: BaseViewHolderItem<*>) {
val casted = holder.cast<BaseViewHolderItem<Vm>>()
if (casted != null) {
@Suppress("UNCHECKED_CAST")
renderFunction(casted.item, item, casted)
//we are now "sure" that the binding class is the same as ours, thus casting "should" be "ok". (we basically introduced our own type system)
} else {
L.debug("RenderModelItem", "unable to bind to view even though it should be correct type$vmTypeValue expected, got : ${holder.viewBindingTypeValue}")
}
}
/**
* more performance than an inline getter that retrieves it.
*/
private val vmTypeValue: Int by lazy {
classType.hashCode()
}
}
/**
* Base class for data binding recycler adapters.
* @param T the type of render models
*/
abstract class DataBindingRecyclerAdapter<T>(context: Context) :
RecyclerView.Adapter<BaseViewHolderItem<*>>() where T : IRenderModelItem<*, *> {
/**
* A simple implementation that discards / tells the underlying adapter that each item have no id.
* we are not stable so return NO_ID.
* @param position Int
* @return Long RecyclerView.NO_ID
*/
override fun getItemId(position: Int): Long = RecyclerView.NO_ID
/**
* The container for all the data via sections
*/
private val dataCollection: SectionLookupRep<T, InflatingFunction<*>> = SectionLookupRep()
/**
* A list of all attached recycler views
*/
private val listeningRecyclers = mutableSetOf<WeakReference<RecyclerView>>()
/**
* Our own layoutinflater
*/
private val inflater: LayoutInflater by lazy {
LayoutInflater.from(context)
}
/**
* The number of sections in this adapter
*/
val sectionCount: Int
get() = dataCollection.sectionCount
init {
super.setHasStableIds(false)
}
/**
* Delegates this responsibility to the data, since it knows it.
* @param parent ViewGroup
* @param viewType Int
* @return BaseViewHolderItem<*>
*/
override fun onCreateViewHolder(parent: ViewGroup, @IntRange(from = 0) viewType: Int): BaseViewHolderItem<*> {
val rep = dataCollection.getTypeRepresentativeFromTypeValue(viewType)
return rep?.invoke(inflater, parent, false)
?: throw RuntimeException("could not find item, " +
"even though we expected it, for viewType: $viewType;" +
"rep is = $rep;" +
"ViewGroup is = $parent")
}
/**
* Delegates this responsibility to the data, since it knows it.
* @param position Int
* @return Int
*/
override fun getItemViewType(@IntRange(from = 0) position: Int): Int {
val item = dataCollection[position]
?: throw RuntimeException("Could not get item, so the position is not there.;" +
" position = $position;" +
" count = ${dataCollection.size};" +
"$dataCollection")
return item.getTypeValue()
}
/**
* Delegates this responsibility to the data, since it knows it.
* and asks it to bind to the given view holder.
* @param holder BaseViewHolderItem<*>
* @param position Int
*/
override fun onBindViewHolder(holder: BaseViewHolderItem<*>, @android.support.annotation.IntRange(from = 0) position: Int) {
//lookup type to converter, then apply model on view using converter
val index = dataCollection.indexToPath(position) ?: return
val render = dataCollection[index]
render?.bindToViewHolder(holder)
}
/**
* Retrieves the number of items (total) in this adapter
* @return Int the number of items (total) in this adapter
*/
override fun getItemCount(): Int = dataCollection.size
/**
* Adds the given item to the end of the given section, or creates the section if not there
* @param newItem T the item to add/append
* @param inSection Int the section index (sparse) to add to
*/
open fun add(newItem: T, inSection: Int): Unit = updateData {
dataCollection.add(newItem, inSection)?.rawRow?.apply {
notifyItemInserted(this)
}
}
/**
* Adds all the given items to the end of the given section, or creates the section if not there
* @param items Collection<T> the items to add
* @param inSection Int the section index (sparse) to add to
*/
open fun addAll(items: Collection<T>, inSection: Int): Unit = updateData {
dataCollection.addAll(items, inSection)?.inRaw?.apply {
notifyItemRangeInserted(this.first, this.length)
}
}
/**
* Adds all the given items to the end of the given section, or creates the section if not there
* @param items Array<out T> the items to add
* @param inSection Int the section index (sparse) to add to
*/
open fun addAll(vararg items: T, inSection: Int): Unit = updateData {
dataCollection.addAll(items.asList(), inSection)?.inRaw?.apply {
notifyItemRangeInserted(start, length)
}
}
/**
* Inserts (instead of appending /adding) to the given section, or creates the section if not there.
* @param item T the item to insert
* @param atRow Int what row to insert at (if there are data)
* @param inSection Int the section index (sparse) to insert into
*/
open fun insert(item: T, atRow: Int, inSection: Int): Unit = updateData {
dataCollection.insert(item, atRow, inSection)?.rawRow?.apply {
notifyItemInserted(this)
}
}
/**
* Inserts all the given elements at the given start position into the given section, or creates the section if not there.
* @param items Collection<T> the items to insert at the given position
* @param startPosition Int the place to perform the insert
* @param inSection Int the section index (sparse) to insert into
*/
open fun insertAll(items: Collection<T>, startPosition: Int, inSection: Int): Unit = updateData {
dataCollection.insertAll(items, startPosition, inSection)?.inRaw?.apply {
notifyItemRangeInserted(start, length)
}
}
/**
* Inserts all the given elements at the given start position into the given section, or creates the section if not there.
* @param items Array<out T> the items to insert at the given position
* @param startPosition Int the place to perform the insert
* @param inSection Int the section index (sparse) to insert into
*/
open fun insertAll(vararg items: T, startPosition: Int, inSection: Int): Unit = updateData {
dataCollection.insertAll(items.asList(), startPosition, inSection)?.inRaw?.apply {
notifyItemRangeInserted(start, length)
}
}
/**
* Removes the item in the section iff there
* @param newItem T the object to remove
* @param inSection Int the section index (sparse) to remove the object from
* @return Int? the raw index of the removing iff any removing was performed (if not then null is returned)
*/
open fun remove(newItem: T, inSection: Int): Int? = updateData {
return@updateData dataCollection.removeItem(newItem, inSection)?.apply {
notifyItemRemoved(rawRow)
}?.rawRow
}
/**
* Removes a given row inside of a section
* Nothing happens if the row is not there.
*
* @param row Int the row in the section to remove
* @param inSection Int the section to remove from
*/
open fun removeAt(row: Int, inSection: Int): Unit = updateData {
dataCollection.removeAt(row, inSection)?.rawRow?.apply {
notifyItemRemoved(this)
}
}
/**
* Removes all the presented items from the given list of items
* @param items List<T> the items to remove from the given section
* @param inSection Int the section index (sparse) to remove all the items from (those that are there)
*/
@UiThread
open fun removeAll(items: List<T>, inSection: Int): Unit = updateData {
items.forEach {
remove(it, inSection)
}
}
/**
* Removes all the given elements from the given section iff possible
* @param range kotlin.ranges.IntRange the range to remove from the section (rows)
* @param inSection Int the section index (sparse) to remove the elements from
*/
@UiThread
open fun removeIn(range: kotlin.ranges.IntRange, inSection: Int): Unit = updateData {
dataCollection.removeInRange(range, inSection)?.inRaw?.apply {
notifyItemRangeRemoved(start + range.first, range.length)
}
}
/**
* Gets the item at the given row in the given section iff there.
* @param atRow Int the row in the section to get
* @param inSection Int the section index (sparse) to retrieve the row from
* @return T? the potential item; if not there null is returned
*/
@AnyThread
open fun getItem(atRow: Int, inSection: Int): T? = dataCollection[atRow, inSection]
/**
* Clears all content of this adapter
*/
@UiThread
open fun clear(): Unit = updateData {
dataCollection.clear()
notifyDataSetChanged()
}
/**
* Adds the given item to the given section without calling update on the underlying adapter
* @param item T the item to append / add
* @param inSection Int the section to append to
*/
@UiThread
protected fun addNoNotify(item: T, inSection: Int): Unit = updateData {
dataCollection.add(item, inSection)?.rawRow
}
/**
* Adds the given items to the given section without calling update on the underlying adapter
* @param items List<T> the items to append / add
* @param inSection Int the section to append to
*/
@UiThread
protected fun addNoNotify(items: List<T>, inSection: Int): Unit = updateData {
dataCollection.addAll(items, inSection)?.inRaw
}
/**
* Updates the given section with the given items.
* @param items List<T> the items to set the section's content to
* @param inSection Int the section index (sparse) to update
*/
@UiThread
open fun setSection(items: List<T>, inSection: Int) = updateData {
val (changes, added, removed) = dataCollection.setSection(items, inSection)
?: return@updateData
changes?.let {
notifyItemRangeChanged(it.inRaw.first, it.inRaw.length)
}
added?.let {
notifyItemRangeInserted(it.inRaw.first, it.inRaw.length)
}
removed?.let {
notifyItemRangeRemoved(it.inRaw.first, it.inRaw.length)
}
}
/**
* Sets the content of the given section to the given item
* @param item T the item to set as the only content of the given section
* @param inSection Int the section index (Sparse) to change
*/
@UiThread
fun setSection(item: T, inSection: Int) = setSection(listOf(item), inSection)
/**
* Clears the given section (removes all elements)
* calling this on an empty section / none exising section will have no effect
* @param inSection Int the section to clear / remove
*/
@UiThread
fun clearSection(inSection: Int): Unit = updateData {
dataCollection.clearSection(inSection)?.inRaw.apply {
this?.let { notifyItemRangeRemoved(it.first, it.length) }
}
}
/**
* replaces the item at the position in the given section, with the supplied item
* @param newItem T the new item to be inserted (iff possible)
* @param position Int the position in the section to replace
* @param inSection Int the section index (sparse) to change
*/
@UiThread
open fun replace(newItem: T, position: Int, inSection: Int): Unit = updateData {
dataCollection.replace(newItem, position, inSection)?.rawRow.apply {
this?.let { notifyItemChanged(it) }
}
}
/**
*Clears and sets a given section (sparse index) without notifying the underlying adapter
* @param items List<T> the items to overwrite the given section with
* @param inSection Int the seciton to clear and set
* @param isIgnored Boolean if the section should be ignored
* @return Boolean if it is ignored or not. (true if ignored)
*/
@UiThread
protected fun clearAndSetItemsNoNotify(items: List<T>, inSection: Int, isIgnored: Boolean) = updateData {
dataCollection.setSection(items, inSection)
isIgnored.ifTrue { dataCollection.ignoreSection(inSection) }
}
/**
* Sets all sections
* @param sections List<TypeSection<T>>
*/
@UiThread
protected fun setAllSections(sections: List<TypeSection<T>>) = updateData {
dataCollection.setAllSections(sections)
super.notifyDataSetChanged()
}
/**
* Stops scroll for all RecyclerViews
*/
@UiThread
private fun stopScroll() {
listeningRecyclers.forEach { recyclerView ->
recyclerView.use { stopScroll() }
}
}
/**
* Called when we get bound to a recyclerView
* @param recyclerView RecyclerView
*/
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
super.onAttachedToRecyclerView(recyclerView)
listeningRecyclers.add(recyclerView.weakReference())
}
/**
* Called when a recyclerView is not going to use this adapter anymore.
* @param recyclerView RecyclerView
*/
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
super.onDetachedFromRecyclerView(recyclerView)
listeningRecyclers.removeAll {
it.get().isNullOrEqualTo(recyclerView)
}
}
/**
* Must be called from all things that manipulate the dataCollection.
*
* @param action EmptyFunctionResult<T> the action to execute safely
* @return T the result of the action
*/
@UiThread
private inline fun <T> updateData(crossinline action: EmptyFunctionResult<T>): T {
stopScroll()
return action()
}
/**
* Gets a representor of the given type (someone who can create the view)
* @param viewHolderItem BaseViewHolderItem<*> the view holder to create it from)
* @return InflatingFunction<*>? the potential inflater function iff anyone can create the view holders view type.
* null if none can
*/
@UiThread
open fun getRepresentUsingType(viewHolderItem: BaseViewHolderItem<*>): InflatingFunction<*>? =
dataCollection.getTypeRepresentativeFromTypeValue(viewHolderItem.viewBindingTypeValue)
/**
* Tries to lookup an item from a given raw index (0 until the item count)
* @param rawIndex Int the raw index
* @return T? the item if there, null otherwise
*/
@UiThread
open fun getItemFromRawIndex(rawIndex: Int): T? {
val index = dataCollection.indexToPath(rawIndex) ?: return null
return dataCollection[index]
}
/**
* Hides the given section
* only updates anything if the section was visible beforehand
* @param sectionIndex Int the section index (sparse) to hide
*/
@UiThread
open fun hideSection(sectionIndex: Int) = updateData {
val sectionLocation = dataCollection.ignoreSection(sectionIndex)?.inRaw ?: return@updateData
notifyItemRangeRemoved(sectionLocation.first, sectionLocation.length)
}
/**
* Shows the given section iff it was invisible before.
* otherwise this have no effect
* @param sectionIndex Int the section index (sparse) to show
*/
@UiThread
open fun showSection(sectionIndex: Int) = updateData {
val sectionLocation = dataCollection.acceptSection(sectionIndex)?.inRaw ?: return@updateData
notifyItemRangeInserted(sectionLocation.first, sectionLocation.length)
}
/**
* Toggles all of the given sections visibility
* @param sectionIndexes IntArray the section indexes (sparse indexes)
*/
@UiThread
open fun toggleSectionsVisibility(vararg sectionIndexes: Int) {
sectionIndexes.forEach(this::toggleSectionVisibility)
}
/**
* Toggles the given sections visibility
* so if it was visible it becomes invisible, and vice verca
* @param sectionIndex Int the section index (sparse) to update
*/
@UiThread
open fun toggleSectionVisibility(sectionIndex: Int) {
val sectionData = dataCollection.sectionAt(sectionIndex) ?: return
if (sectionData.isIgnored) {
showSection(sectionIndex)
} else {
hideSection(sectionIndex)
}
}
/**
* Clears the underlying data without notifying the underlying adapter
*/
@AnyThread
protected fun clearNoNotify() {
dataCollection.clear()
}
/**
* Tries to find the given element in a section , and returns the path if found.
* @param item T the item to find (must be comparable to be compared, otherwise it will be per address)
* @param inSection Int the section index(sparse)
* @return IndexPath? the index where the element is, if found, null otherwise (or null also if the section is not there)
*/
@UiThread
fun getIndexFor(item: T, @android.support.annotation.IntRange(from = 0) inSection: Int): IndexPath? {
val innerIndex = dataCollection.sectionAt(inSection)?.collection?.indexOf(item)
?: return null
return IndexPath(innerIndex, inSection)
}
/**
* Retrieves the given section's size (number of elements)
* @param sectionIndex Int the section index ( sparse) to query
* @return Int? the number of item in this section (elements) , or null if the section does not exists
*/
@UiThread
fun getSectionSize(sectionIndex: Int): Int? = dataCollection.sectionAt(sectionIndex)?.size
/**
* Tells if the queried section is visible; defaults to false if the section does not exists
* @param inSection Int the section index (sparse) to query
* @return Boolean true if the section is visible, false otherwise
*/
@UiThread
fun isSectionVisible(inSection: Int): Boolean =
dataCollection.sectionAt(inSection)?.isIgnored?.not() ?: false
/**
* Changes the given section's visibility to the given visibility
* @param section Int the section index (sparse) to update
* @param isVisible Boolean if true then its visible, if false then its invisible.
*/
@UiThread
fun setSectionVisibility(section: Int, isVisible: Boolean) {
dataCollection.sectionAt(section)?.let {
if (it.isIgnored != !isVisible) {
toggleSectionVisibility(section)
}
}
}
/**
* Removes the section by index, iff it exists.
* @param sectionIndex Int the section index (sparse) to remove.
*/
@UiThread
open fun removeSection(@android.support.annotation.IntRange(from = 0) sectionIndex: Int) = clearSection(sectionIndex)
/**
* Removes a given list of sections
*
* @param sectionIndexes IntArray the sections (sparse) to remove
*/
@UiThread
fun removeSections(@android.support.annotation.IntRange(from = 0) vararg sectionIndexes: Int) {
sectionIndexes.forEach(this::removeSection)
}
/**
* Smooth scrolls to the given section start
* @param sectionIndex Int the section index (sparse)
*/
@UiThread
fun smoothScrollToSection(@android.support.annotation.IntRange(from = 0) sectionIndex: Int) {
val positionInList = dataCollection.getSectionLocation(sectionIndex)?.inRaw?.first ?: return
listeningRecyclers.forEach {
it.use { this.smoothScrollToPosition(positionInList) }
}
}
/**
* Reloads all items in this adapter
*/
@UiThread
fun reloadAll() {
notifyItemRangeChanged(0, dataCollection.size)
}
/**
* Reloads a given section's items
* @param sectionIndex Int the section index (sparse) to reload
*/
@UiThread
fun reloadSection(sectionIndex: Int) {
val location = dataCollection.getSectionLocation(sectionIndex) ?: return
notifyItemRangeChanged(location.inRaw)
}
override fun setHasStableIds(hasStableIds: Boolean) {
logClassError("Have no effect as we are effectively not stable according to the adapter implementation;" +
"We handle everything our self. Please do not call this method.")
}
//make sure we never allow transient state to be recycled.
override fun onFailedToRecycleView(holder: BaseViewHolderItem<*>): Boolean {
return false
}
override fun toString(): String {
return toPrettyString()
}
fun toPrettyString(): String {
return "Base dataBinding adapter state:" + listOf(
dataCollection.toPrettyString()
).prettyStringContent()
}
}
/**
* Hides all the given sections (by sparse index)
* calling hide on an already invisible section have no effects
* @receiver BaseDataBindingRecyclerAdapter
* @param sections IntArray the sections to hide
*/
@UiThread
fun BaseDataBindingRecyclerAdapter.hideSections(vararg sections: Int) =
sections.forEach(this::hideSection)
/**
* Shows all the given sections (by sparse index)
* calling show on an already visible section have no effects
* @receiver BaseDataBindingRecyclerAdapter
* @param sections IntArray the sections to show
*/
fun BaseDataBindingRecyclerAdapter.showSections(vararg sections: Int) =
sections.forEach(this::showSection)
open class BaseDataBindingRecyclerAdapter(context: Context) :
DataBindingRecyclerAdapter<IRenderModelItem<*, *>>(context)
class DefaultDataBindingRecyclerAdapter(context: Context) : BaseDataBindingRecyclerAdapter(context) | mit | 2b98b66b52bf1e5ef1f6f7bfac398488 | 35.623865 | 161 | 0.666348 | 4.808583 | false | false | false | false |
y2k/JoyReactor | android/src/main/kotlin/y2k/joyreactor/common/ViewHolderExtensions.kt | 1 | 1454 | package y2k.joyreactor.common
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import kotlin.reflect.KProperty
/**
* Created by y2k on 5/29/16.
*/
fun RecyclerView.ViewHolder.setOnClick(id: Int, f: (Int) -> Unit) {
itemView.find<View>(id).setOnClickListener { f(layoutPosition) }
}
fun <T : View> ViewGroup.view(): ViewGroupDelegate<T> {
return ViewGroupDelegate()
}
class ViewGroupDelegate<out T : View>() {
private var cached: T? = null
@Suppress("UNCHECKED_CAST")
operator fun getValue(group: ViewGroup, property: KProperty<*>): T {
if (cached == null) {
val context = group.context
val id = context.resources.getIdentifier(property.name, "id", context.packageName)
cached = group.findViewById(id) as T
}
return cached!!
}
}
fun <T : View> RecyclerView.ViewHolder.view(): ViewHolderDelegate<T> {
return ViewHolderDelegate()
}
class ViewHolderDelegate<out T : View>() {
private var cached: T? = null
@Suppress("UNCHECKED_CAST")
operator fun getValue(holder: RecyclerView.ViewHolder, property: KProperty<*>): T {
if (cached == null) {
val context = holder.itemView.context
val id = context.resources.getIdentifier(property.name, "id", context.packageName)
cached = holder.itemView.findViewById(id) as T
}
return cached!!
}
} | gpl-2.0 | f3ea1de7b0db94f577681f617d1ad1b6 | 26.980769 | 94 | 0.658184 | 4.027701 | false | false | false | false |
JavaEden/Orchid | languageExtensions/OrchidSyntaxHighlighter/src/main/kotlin/com/eden/orchid/languages/highlighter/tags/HighlightTag.kt | 2 | 1717 | package com.eden.orchid.languages.highlighter.tags
import com.eden.orchid.api.compilers.TemplateTag
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.options.annotations.StringDefault
import com.eden.orchid.api.resources.resource.OrchidResource
import com.eden.orchid.utilities.encodeSpaces
import org.python.util.PythonInterpreter
@Description("Add syntax highlighting using Pygments.", name = "Highlight")
class HighlightTag : TemplateTag("highlight", Type.Content, true) {
@Option
@StringDefault("java")
@Description("Your language to use for the syntax highlighting format.")
lateinit var language: String
override fun parameters() = arrayOf(::language.name)
public fun highlight(input: String): String {
try {
val interpreter = PythonInterpreter()
val pygmentsScript: OrchidResource? = context.getDefaultResourceSource(null, null).getResourceEntry(context, "scripts/pygments/pygments.py")
val pythonScript = pygmentsScript?.content ?: ""
// Set a variable with the content you want to work with
interpreter.set("code", input)
interpreter.set("codeLanguage", language)
// Simply use Pygments as you would in Python
interpreter.exec(pythonScript)
var result = interpreter.get("result", String::class.java)
// replace newlines with <br> tag, and spaces between tags with to preserve original structure
return result.encodeSpaces()
}
catch (e: Exception) {
e.printStackTrace()
}
return input
}
}
| lgpl-3.0 | ada4571378d5f2f95c2579b375013e9c | 36.326087 | 152 | 0.695981 | 4.665761 | false | false | false | false |
laurentvdl/sqlbuilder | src/main/kotlin/sqlbuilder/impl/mappers/IntegerMapper.kt | 1 | 949 | package sqlbuilder.impl.mappers
import sqlbuilder.mapping.BiMapper
import sqlbuilder.mapping.ToObjectMappingParameters
import sqlbuilder.mapping.ToSQLMappingParameters
import java.sql.Types
/**
* @author Laurent Van der Linden.
*/
class IntegerMapper : BiMapper {
override fun toObject(params: ToObjectMappingParameters): Int? {
val value = params.resultSet.getInt(params.index)
return if (params.resultSet.wasNull()) {
null
} else {
value
}
}
override fun toSQL(params: ToSQLMappingParameters) {
if (params.value != null) {
params.preparedStatement.setInt(params.index, params.value as Int)
} else {
params.preparedStatement.setNull(params.index, Types.BIGINT)
}
}
override fun handles(targetType: Class<*>): Boolean {
return Int::class.java == targetType || java.lang.Integer::class.java == targetType
}
} | apache-2.0 | 28103e04854752fb5f05b38154aff4ae | 28.6875 | 91 | 0.665964 | 4.5625 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/ast/PsiUtils.kt | 1 | 2215 | /*
* Copyright (C) 2020-2021 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.xpath.ast
import com.intellij.psi.PsiElement
import com.intellij.psi.util.elementType
import uk.co.reecedunn.intellij.plugin.core.sequences.children
import uk.co.reecedunn.intellij.plugin.core.sequences.reverse
import uk.co.reecedunn.intellij.plugin.core.sequences.siblings
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathArgumentList
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathComment
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathExpr
import xqt.platform.intellij.xpath.XPathTokenProvider
fun <T> PsiElement.filterExpressions(klass: Class<T>): Sequence<T> {
val item = children().filterIsInstance(klass)
val sequence = children().filterIsInstance<XPathExpr>().firstOrNull()
return if (sequence != null)
sequenceOf(item, sequence.children().filterIsInstance(klass)).flatten()
else
item
}
inline fun <reified T> PsiElement.filterExpressions(): Sequence<T> = filterExpressions(T::class.java)
fun Sequence<PsiElement>.filterNotWhitespace(): Sequence<PsiElement> = filterNot { e ->
e.elementType === XPathTokenProvider.S.elementType || e is XPathComment
}
val PsiElement.parenthesizedExprTextOffset: Int?
get() {
val pref = reverse(siblings()).filterNotWhitespace().firstOrNull()
return when {
pref == null -> null
pref.elementType !== XPathTokenProvider.ParenthesisOpen -> null
pref.parent !is XPathArgumentList -> pref.textOffset
pref.parent.firstChild !== pref -> pref.textOffset
else -> null
}
}
| apache-2.0 | 64c4b47bce62d3f886ef3f81114c79e3 | 40.792453 | 101 | 0.735892 | 4.227099 | false | false | false | false |
sleep/mal | kotlin/src/mal/step8_macros.kt | 4 | 6563 | package mal
import java.util.*
fun read(input: String?): MalType = read_str(input)
fun eval(_ast: MalType, _env: Env): MalType {
var ast = _ast
var env = _env
while (true) {
ast = macroexpand(ast, env)
if (ast is MalList) {
when ((ast.first() as? MalSymbol)?.value) {
"def!" -> return env.set(ast.nth(1) as MalSymbol, eval(ast.nth(2), env))
"let*" -> {
val childEnv = Env(env)
val bindings = ast.nth(1) as? ISeq ?: throw MalException("expected sequence as the first parameter to let*")
val it = bindings.seq().iterator()
while (it.hasNext()) {
val key = it.next()
if (!it.hasNext()) throw MalException("odd number of binding elements in let*")
childEnv.set(key as MalSymbol, eval(it.next(), childEnv))
}
env = childEnv
ast = ast.nth(2)
}
"fn*" -> return fn_STAR(ast, env)
"do" -> {
eval_ast(ast.slice(1, ast.count() - 1), env)
ast = ast.seq().last()
}
"if" -> {
val check = eval(ast.nth(1), env)
if (check !== NIL && check !== FALSE) {
ast = ast.nth(2)
} else if (ast.count() > 3) {
ast = ast.nth(3)
} else return NIL
}
"quote" -> return ast.nth(1)
"quasiquote" -> ast = quasiquote(ast.nth(1))
"defmacro!" -> return defmacro(ast, env)
"macroexpand" -> return macroexpand(ast.nth(1), env)
else -> {
val evaluated = eval_ast(ast, env) as ISeq
val firstEval = evaluated.first()
when (firstEval) {
is MalFnFunction -> {
ast = firstEval.ast
env = Env(firstEval.env, firstEval.params, evaluated.rest().seq())
}
is MalFunction -> return firstEval.apply(evaluated.rest())
else -> throw MalException("cannot execute non-function")
}
}
}
} else return eval_ast(ast, env)
}
}
fun eval_ast(ast: MalType, env: Env): MalType =
when (ast) {
is MalSymbol -> env.get(ast)
is MalList -> ast.elements.fold(MalList(), { a, b -> a.conj_BANG(eval(b, env)); a })
is MalVector -> ast.elements.fold(MalVector(), { a, b -> a.conj_BANG(eval(b, env)); a })
is MalHashMap -> ast.elements.entries.fold(MalHashMap(), { a, b -> a.assoc_BANG(b.key, eval(b.value, env)); a })
else -> ast
}
private fun fn_STAR(ast: MalList, env: Env): MalType {
val binds = ast.nth(1) as? ISeq ?: throw MalException("fn* requires a binding list as first parameter")
val params = binds.seq().filterIsInstance<MalSymbol>()
val body = ast.nth(2)
return MalFnFunction(body, params, env, { s: ISeq -> eval(body, Env(env, params, s.seq())) })
}
private fun is_pair(ast: MalType): Boolean = ast is ISeq && ast.seq().any()
private fun quasiquote(ast: MalType): MalType {
if (!is_pair(ast)) {
val quoted = MalList()
quoted.conj_BANG(MalSymbol("quote"))
quoted.conj_BANG(ast)
return quoted
}
val seq = ast as ISeq
var first = seq.first()
if ((first as? MalSymbol)?.value == "unquote") {
return seq.nth(1)
}
if (is_pair(first) && ((first as ISeq).first() as? MalSymbol)?.value == "splice-unquote") {
val spliced = MalList()
spliced.conj_BANG(MalSymbol("concat"))
spliced.conj_BANG((first as ISeq).nth(1))
spliced.conj_BANG(quasiquote(MalList(seq.seq().drop(1).toCollection(LinkedList<MalType>()))))
return spliced
}
val consed = MalList()
consed.conj_BANG(MalSymbol("cons"))
consed.conj_BANG(quasiquote(ast.first()))
consed.conj_BANG(quasiquote(MalList(seq.seq().drop(1).toCollection(LinkedList<MalType>()))))
return consed
}
private fun is_macro_call(ast: MalType, env: Env): Boolean {
val symbol = (ast as? MalList)?.first() as? MalSymbol ?: return false
val function = env.find(symbol) as? MalFunction ?: return false
return function.is_macro
}
private fun macroexpand(_ast: MalType, env: Env): MalType {
var ast = _ast
while (is_macro_call(ast, env)) {
val symbol = (ast as MalList).first() as MalSymbol
val function = env.find(symbol) as MalFunction
ast = function.apply(ast.rest())
}
return ast
}
private fun defmacro(ast: MalList, env: Env): MalType {
val macro = eval(ast.nth(2), env) as MalFunction
macro.is_macro = true
return env.set(ast.nth(1) as MalSymbol, macro)
}
fun print(result: MalType) = pr_str(result, print_readably = true)
fun rep(input: String, env: Env): String =
print(eval(read(input), env))
fun main(args: Array<String>) {
val repl_env = Env()
ns.forEach({ it -> repl_env.set(it.key, it.value) })
repl_env.set(MalSymbol("*ARGV*"), MalList(args.drop(1).map({ it -> MalString(it) }).toCollection(LinkedList<MalType>())))
repl_env.set(MalSymbol("eval"), MalFunction({ a: ISeq -> eval(a.first(), repl_env) }))
rep("(def! not (fn* (a) (if a false true)))", repl_env)
rep("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))", repl_env)
rep("(defmacro! cond (fn* (& xs) (if (> (count xs) 0) (list 'if (first xs) (if (> (count xs) 1) (nth xs 1) (throw \"odd number of forms to cond\")) (cons 'cond (rest (rest xs)))))))", repl_env)
rep("(defmacro! or (fn* (& xs) (if (empty? xs) nil (if (= 1 (count xs)) (first xs) `(let* (or_FIXME ~(first xs)) (if or_FIXME or_FIXME (or ~@(rest xs))))))))", repl_env)
if (args.any()) {
rep("(load-file \"${args[0]}\")", repl_env)
return
}
while (true) {
val input = readline("user> ")
try {
println(rep(input, repl_env))
} catch (e: EofException) {
break
} catch (e: MalContinue) {
} catch (e: MalException) {
println("Error: " + e.message)
} catch (t: Throwable) {
println("Uncaught " + t + ": " + t.message)
t.printStackTrace()
}
}
}
| mpl-2.0 | 6a651ccfd58587ca0e7e9f5a9b09725e | 36.079096 | 197 | 0.521865 | 3.809054 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/project/settings/XQueryProjectSettings.kt | 1 | 3141 | /*
* Copyright (C) 2016-2021 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.xquery.project.settings
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ModificationTracker
import com.intellij.util.xmlb.XmlSerializerUtil
import com.intellij.util.xmlb.annotations.Transient
import uk.co.reecedunn.intellij.plugin.intellij.lang.*
import java.util.concurrent.atomic.AtomicLongFieldUpdater
@State(name = "XQueryProjectSettings", storages = [Storage(StoragePathMacros.WORKSPACE_FILE)])
class XQueryProjectSettings : PersistentStateComponent<XQueryProjectSettings>, ModificationTracker {
// region Settings
@Suppress("PrivatePropertyName")
private var PRODUCT_VERSION = VersionedProductId("w3c/spec/v1ed")
@get:Transient
val product: Product
get() = PRODUCT_VERSION.product ?: W3C.SPECIFICATIONS
@get:Transient
val productVersion: Version
get() = PRODUCT_VERSION.productVersion ?: defaultProductVersion(product)
// endregion
// region Persisted Settings
var implementationVersion: String?
get() = PRODUCT_VERSION.id
set(version) {
PRODUCT_VERSION.id = version
incrementModificationCount()
}
@Suppress("PropertyName")
var XQueryVersion: String? = "1.0"
@Suppress("PropertyName")
var XQuery10Dialect: String? = "xquery"
@Suppress("PropertyName")
var XQuery30Dialect: String? = "xquery"
@Suppress("PropertyName")
var XQuery31Dialect: String? = "xquery"
// endregion
// region PersistentStateComponent
override fun getState(): XQueryProjectSettings = this
override fun loadState(state: XQueryProjectSettings): Unit = XmlSerializerUtil.copyBean(state, this)
// endregion
// region ModificationTracker
@Volatile
private var modificationCount: Long = 0
private fun incrementModificationCount() {
UPDATER.incrementAndGet(this)
}
override fun getModificationCount(): Long = modificationCount
// endregion
companion object {
private val UPDATER = AtomicLongFieldUpdater.newUpdater(
XQueryProjectSettings::class.java,
"modificationCount"
)
fun getInstance(project: Project): XQueryProjectSettings {
return project.getService(XQueryProjectSettings::class.java)
}
}
}
| apache-2.0 | c4ef2a241a96fe92d134c59636c5cfd5 | 31.381443 | 104 | 0.729704 | 4.817485 | false | false | false | false |
GKZX-HN/MyGithub | app/src/main/java/com/gkzxhn/mygithub/mvp/presenter/IssuePresenter.kt | 1 | 15264 | package com.gkzxhn.mygithub.mvp.presenter
import android.util.Log
import com.gkzxhn.balabala.mvp.contract.BaseView
import com.gkzxhn.mygithub.api.OAuthApi
import com.gkzxhn.mygithub.bean.info.Owner
import com.gkzxhn.mygithub.bean.info.PostIssueResponse
import com.gkzxhn.mygithub.bean.info.SearchUserResult
import com.gkzxhn.mygithub.bean.info.User
import com.gkzxhn.mygithub.extension.toast
import com.gkzxhn.mygithub.ui.fragment.ContributorsFragment
import com.gkzxhn.mygithub.ui.fragment.IssueFragment
import com.gkzxhn.mygithub.utils.rxbus.RxBus
import com.trello.rxlifecycle2.kotlin.bindToLifecycle
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject
/**
* Created by 方 on 2017/10/25.
*/
class IssuePresenter @Inject constructor(private val oAuthApi: OAuthApi,
private val view: BaseView,
private val rxBus: RxBus) {
private var owner :String? = null
private var repo : String? = null
fun getIssues(owner : String, repo: String){
this.owner = owner
this.repo = repo
view.showLoading()
oAuthApi.getIssues(owner = owner, repo = repo)
.bindToLifecycle(view as IssueFragment)
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
issues ->
if (issues.size > 0) {
view.loadData(issues)
}
view.hideLoading()
},{
e ->
Log.e(javaClass.simpleName, e.message )
view.context.toast("加载失败...")
})
}
fun getOpenIssues(owner: String, repo: String) {
this.owner = owner
this.repo = repo
view.showLoading()
oAuthApi.getIssues(owner = owner, repo = repo, state = "open")
.bindToLifecycle(view as IssueFragment)
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
issues ->
if (issues.size > 0) {
view.loadData(issues)
}
view.hideLoading()
},{
e ->
Log.e(javaClass.simpleName, e.message )
view.context.toast("加载失败...")
})
}
fun getClosedIssues(owner: String, repo: String) {
this.owner = owner
this.repo = repo
view.showLoading()
oAuthApi.getIssues(owner = owner, repo = repo, state = "closed")
.bindToLifecycle(view as IssueFragment)
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
issues ->
if (issues.size > 0) {
view.loadData(issues)
}
view.hideLoading()
},{
e ->
Log.e(javaClass.simpleName, e.message )
view.context.toast("加载失败...")
})
}
fun addSubscribe(){
rxBus.toFlowable(PostIssueResponse::class.java)
.bindToLifecycle(view as IssueFragment)
.subscribe(
{
t -> getOpenIssues(owner = owner!!, repo = repo!!)
},
{
e ->
Log.e(javaClass.simpleName, e.message)
}
)
}
fun getContributors(owner : String, repo: String){
this.owner = owner
this.repo = repo
view.showLoading()
oAuthApi.contributors(owner, repo)
.bindToLifecycle(view as ContributorsFragment)
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext {
lists: List<Owner> ->
view?.let {
it.hideLoading()
it.loadData(lists)
}
}
.doOnError {
e ->
Log.e(javaClass.simpleName, e.message)
view?.let { it.hideLoading()
if (e is NullPointerException)
//空仓库
else
it.context.toast("加载失败")
}
}
.onErrorReturn {
e ->
Log.e(javaClass.simpleName, e.message)
val list = arrayListOf<Owner>()
view.loadData(list)
list
}
.observeOn(Schedulers.io())
.subscribe {
t ->
Log.i(javaClass.simpleName, "when map observer Current thread is " + Thread.currentThread().getName())
t.forEachIndexed { index, owner ->
Log.i(javaClass.simpleName, "when map list Current thread is " + Thread.currentThread().getName())
if (view.isLoading) {
return@subscribe
}
oAuthApi.getUser(owner.login)
.bindToLifecycle(view)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
user: User ->
Log.i(javaClass.simpleName, "get user")
if (!view.isLoading) {
view?.let {
it.updateList(index, user)
}
}
},
{
e ->
view?.let {
it.hideLoading()
}
Log.e(javaClass.simpleName, e.message)
})
}
}
}
fun getForks(owner : String, repo: String){
this.owner = owner
this.repo = repo
view.showLoading()
oAuthApi.listForks(owner, repo, "newest")
.map {
repos ->
repos.map {
repo ->
repo.owner
}
}
.bindToLifecycle(view as ContributorsFragment)
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext {
owners: List<Owner> ->
view?.let {
it.hideLoading()
it.loadData(owners)
}
}
.doOnError {
e ->
Log.e(javaClass.simpleName, e.message)
view?.let { it.hideLoading()
if (e is NullPointerException)
//空仓库
else
it.context.toast("加载失败")
}
}
.onErrorReturn {
e ->
Log.e(javaClass.simpleName, e.message)
val list = arrayListOf<Owner>()
view.loadData(list)
list
}
.observeOn(Schedulers.io())
.subscribe {
t ->
Log.i(javaClass.simpleName, "when map observer Current thread is " + Thread.currentThread().getName())
t.forEachIndexed { index, owner ->
Log.i(javaClass.simpleName, "when map list Current thread is " + Thread.currentThread().getName())
if (view.isLoading) {
return@subscribe
}
oAuthApi.getUser(owner.login)
.bindToLifecycle(view)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
user: User ->
Log.i(javaClass.simpleName, "get user")
if (!view.isLoading) {
view?.let {
it.hideLoading()
it.updateList(index, user)
}
}
},
{
e ->
view?.let {
it.hideLoading()
}
Log.e(javaClass.simpleName, e.message)
})
}
}
}
fun searchUsers(string : String) {
view.showLoading()
oAuthApi.searchUsers(string)
.bindToLifecycle(view as ContributorsFragment)
.subscribeOn(Schedulers.io())
.map {
t: SearchUserResult ->
return@map t.items
}
.observeOn(AndroidSchedulers.mainThread())
.doOnNext {
owners: List<Owner> ->
view?.let {
it.hideLoading()
it.loadData(owners)
}
}
.doOnError {
e ->
Log.e(javaClass.simpleName, e.message)
view?.let { it.hideLoading()
if (e is NullPointerException)
//空仓库
else
it.context.toast("加载失败")
}
}
.onErrorReturn {
e ->
Log.e(javaClass.simpleName, e.message)
val list = arrayListOf<Owner>()
view.loadData(list)
list
}
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
t ->
getUserBio(t, view)
}
}
private fun getUserBio(t: ArrayList<Owner>, view: ContributorsFragment) {
Log.i(javaClass.simpleName, "when map observer Current thread is " + Thread.currentThread().getName())
t.forEachIndexed { index, owner ->
Log.i(javaClass.simpleName, "when map list Current thread is " + Thread.currentThread().getName())
if (view.isLoading) {
return@forEachIndexed
}
if ("User" != owner.type){
return@forEachIndexed
}
checkIfFollowIng(index, owner.login)
oAuthApi.getUser(owner.login)
.bindToLifecycle(view)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ user: User ->
Log.i(javaClass.simpleName, "get user")
if (!view.isLoading) {
view?.let {
it.hideLoading()
it.updateList(index, user)
}
}
},
{ e ->
view?.let {
it.hideLoading()
}
Log.e(javaClass.simpleName, e.message)
})
}
}
/**
* 检查是否关注该用户
*/
fun checkIfFollowIng(index: Int, username: String){
(view as ContributorsFragment).updateListFollowStatus(index, -1)
oAuthApi.checkIfFollowUser(username)
.bindToLifecycle(view)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
t ->
Log.i(javaClass.simpleName, t.message())
if (t.code() == 204) {
//已关注
view.updateListFollowStatus(index, 0)
}else{
view.updateListFollowStatus(index, 1)
}
},{
e ->
Log.i(javaClass.simpleName, e.message)
})
}
/**
* 关注用户
*/
fun followUser(index: Int, username: String) {
(view as ContributorsFragment).updateListFollowStatus(index, -1)
oAuthApi.followUser(username)
.bindToLifecycle(view)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
t ->
Log.i(javaClass.simpleName, t.message())
if (t.code() == 204) {
view.updateListFollowStatus(index, 0)
}else {
view.updateListFollowStatus(index, 1)
}
}, {
e ->
Log.e(javaClass.simpleName, e.message)
})
}
/**
* 取消关注用户
*/
fun unFollowUser(index: Int, username: String) {
(view as ContributorsFragment).updateListFollowStatus(index, -1)
oAuthApi.unFollowUser(username)
.bindToLifecycle(view)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
t ->
Log.i(javaClass.simpleName, t.message())
if (t.code() == 204) {
view.updateListFollowStatus(index, 1)
}else {
view.updateListFollowStatus(index, 1)
}
}, {
e ->
Log.e(javaClass.simpleName, e.message)
})
}
} | gpl-3.0 | 48541d0fa480b0fafbc2dd35eaca8adf | 37.557252 | 122 | 0.405821 | 6.112142 | false | false | false | false |
weisJ/darklaf | buildSrc/src/main/kotlin/GenerateIconAccessor.kt | 1 | 2446 | import java.io.File
import java.io.FileInputStream
import java.util.*
fun createIconAccessor(propertyFile: File, packageName : String, className: String): String {
class Property(val name: String?, val path: String)
class AccessorTreeNode(
val nodes: MutableMap<String, AccessorTreeNode>,
val properties: MutableList<Property>
)
val props = Properties().apply {
this.load(FileInputStream(propertyFile))
}
val root = AccessorTreeNode(mutableMapOf(), mutableListOf())
props.forEach { (k, value) ->
var key = k.toString()
val sepIndex = key.indexOf('|')
val name = if (sepIndex >= 0) {
val end = key.substring(sepIndex + 1)
key = key.substring(0, sepIndex)
end
} else null
val segments = key.split(".")
var node = root
for (segment in segments) {
node = node.nodes.getOrPut(segment) {
AccessorTreeNode(mutableMapOf(), mutableListOf())
}
}
node.properties.add(Property(name, value.toString()))
}
fun createAccessor(prop: Property): String =
"""
public static Icon ${prop.name ?: "get"}() {
return IconSet.iconLoader().getIcon("${prop.path}", true);
}
public static Icon ${prop.name ?: "get"}(final int width, final int height) {
return IconSet.iconLoader().getIcon("${prop.path}", width, height, true);
}
""".trimIndent()
fun createAccessorClass(name: String, node: AccessorTreeNode, topLevel: Boolean = false): String {
val properties = node.properties.sortedBy { it.name }.joinToString(separator = "\n\n") {
createAccessor(it)
}.replace("\n", "\n ")
val subNodes = node.nodes.entries.asSequence().sortedBy { it.key }.joinToString(separator = "\n\n") {
createAccessorClass(it.key, it.value)
}.replace("\n", "\n ")
return """
|@javax.annotation.Generated(value = {"GenerateIconAccessor"})
|public ${if (topLevel) "" else "static "}final class ${name.capitalize()} {
| $properties
| $subNodes
|}
""".trimMargin()
}
return """
|package $packageName;
|
|import javax.swing.Icon;
|
|${createAccessorClass(className, root, topLevel = true)}
""".trimMargin()
}
| mit | c2be3f382493c3c9b9d1cb90fd0d1664 | 34.449275 | 109 | 0.571137 | 4.471664 | false | false | false | false |
jkcclemens/khttp | src/test/kotlin/khttp/KHttpAsyncPutSpec.kt | 1 | 1080 | /*
* 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 khttp
import khttp.responses.Response
import org.awaitility.kotlin.await
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import java.util.concurrent.TimeUnit
import kotlin.test.assertEquals
class KHttpAsyncPutSpec : Spek({
describe("a put request") {
val url = "https://httpbin.org/put"
var error: Throwable? = null
var response: Response? = null
async.put(url, onError = { error = this }, onResponse = { response = this })
await.atMost(5, TimeUnit.SECONDS)
.until { response != null }
context("accessing the json") {
if (error != null) throw error!!
val json = response!!.jsonObject
it("should have the same url") {
assertEquals(url, json.getString("url"))
}
}
}
})
| mpl-2.0 | f39c52a154fa31ce1ab8f96a452d220d | 31.727273 | 84 | 0.636111 | 4.090909 | false | false | false | false |
Tandrial/Advent_of_Code | src/aoc2016/kot/Day25.kt | 1 | 343 | package aoc2016.kot
import VM
import java.io.File
fun main(args: Array<String>) {
val s = File("./input/2016/Day25_input.txt").readLines()
var result: Long
var regA: Long = -1L
do {
regA++
val vm = VM(s, listOf("a" to regA, "lastOut" to -1L))
result = vm.run()
} while (result == -1L)
println("Part One = $regA")
}
| mit | 41c7522f3eac5ca1f0f1aa949c41584f | 18.055556 | 58 | 0.606414 | 2.766129 | false | false | false | false |
Maccimo/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/details/GHPRBranchesPanel.kt | 5 | 8691 | // 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.plugins.github.pullrequest.ui.details
import com.intellij.collaboration.ui.CollaborationToolsUIUtil
import com.intellij.ide.IdeTooltip
import com.intellij.ide.IdeTooltipManager
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.changes.ui.CurrentBranchComponent
import com.intellij.ui.CardLayoutPanel
import com.intellij.ui.components.AnActionLink
import com.intellij.ui.components.DropDownLink
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.panels.NonOpaquePanel
import com.intellij.ui.components.panels.Wrapper
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import icons.CollaborationToolsIcons
import icons.DvcsImplIcons
import net.miginfocom.layout.CC
import net.miginfocom.layout.LC
import net.miginfocom.swing.MigLayout
import org.jetbrains.plugins.github.GithubIcons
import org.jetbrains.plugins.github.i18n.GithubBundle
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.util.function.Consumer
import javax.swing.JComponent
import javax.swing.JLabel
internal object GHPRBranchesPanel {
fun create(model: GHPRBranchesModel): JComponent {
val from = createLabel()
val to = createLabel()
val branchActionsToolbar = BranchActionsToolbar()
Controller(model, from, to, branchActionsToolbar)
return NonOpaquePanel().apply {
layout = MigLayout(LC()
.fillX()
.gridGap("0", "0")
.insets("0", "0", "0", "0"))
add(to, CC().minWidth("${JBUIScale.scale(30)}"))
add(JLabel(" ${UIUtil.leftArrow()} ").apply {
foreground = CurrentBranchComponent.TEXT_COLOR
border = JBUI.Borders.empty(0, 5)
})
add(from, CC().minWidth("${JBUIScale.scale(30)}"))
add(branchActionsToolbar)
}
}
private fun createLabel() = JBLabel(CollaborationToolsIcons.Branch).also {
CollaborationToolsUIUtil.overrideUIDependentProperty(it) {
foreground = CurrentBranchComponent.TEXT_COLOR
background = CurrentBranchComponent.getBranchPresentationBackground(UIUtil.getListBackground())
}
}.andOpaque()
private class Controller(private val model: GHPRBranchesModel,
private val from: JBLabel,
private val to: JBLabel,
private val branchActionsToolbar: BranchActionsToolbar) {
val branchesTooltipFactory = GHPRBranchesTooltipFactory()
init {
branchesTooltipFactory.installTooltip(from)
model.addAndInvokeChangeListener {
updateBranchActionsToolbar()
updateBranchLabels()
}
}
private fun updateBranchLabels() {
val localRepository = model.localRepository
val localBranch = with(localRepository.branches) { model.localBranch?.run(::findLocalBranch) }
val remoteBranch = localBranch?.findTrackedBranch(localRepository)
val currentBranchCheckedOut = localRepository.currentBranchName == localBranch?.name
to.text = model.baseBranch
from.text = model.headBranch
from.icon = when {
currentBranchCheckedOut -> DvcsImplIcons.CurrentBranchFavoriteLabel
localBranch != null -> GithubIcons.LocalBranch
else -> CollaborationToolsIcons.Branch
}
branchesTooltipFactory.apply {
isOnCurrentBranch = currentBranchCheckedOut
prBranchName = model.headBranch
localBranchName = localBranch?.name
remoteBranchName = remoteBranch?.name
}
}
private fun updateBranchActionsToolbar() {
val prRemote = model.prRemote
if (prRemote == null) {
branchActionsToolbar.showCheckoutAction()
return
}
val localBranch = model.localBranch
val updateActionExist = localBranch != null
val multipleActionsExist = updateActionExist && model.localRepository.currentBranchName != localBranch
with(branchActionsToolbar) {
when {
multipleActionsExist -> showMultiple()
updateActionExist -> showUpdateAction()
else -> showCheckoutAction()
}
}
}
}
internal class BranchActionsToolbar : CardLayoutPanel<BranchActionsToolbar.State, BranchActionsToolbar.StateUi, JComponent>() {
companion object {
const val BRANCH_ACTIONS_TOOLBAR = "Github.PullRequest.Branch.Actions.Toolbar"
}
enum class State(private val text: String) {
CHECKOUT_ACTION(VcsBundle.message("vcs.command.name.checkout")),
UPDATE_ACTION(VcsBundle.message("vcs.command.name.update")),
MULTIPLE_ACTIONS(GithubBundle.message("pull.request.branch.action.group.name"));
override fun toString(): String = text
}
fun showCheckoutAction() {
select(State.CHECKOUT_ACTION, true)
}
fun showUpdateAction() {
select(State.UPDATE_ACTION, true)
}
fun showMultiple() {
select(State.MULTIPLE_ACTIONS, true)
}
sealed class StateUi {
abstract fun createUi(): JComponent
object CheckoutActionUi : SingleActionUi("Github.PullRequest.Branch.Create", VcsBundle.message("vcs.command.name.checkout"))
object UpdateActionUi : SingleActionUi("Github.PullRequest.Branch.Update", VcsBundle.message("vcs.command.name.update"))
abstract class SingleActionUi(private val actionId: String, @NlsContexts.LinkLabel private val actionName: String) : StateUi() {
override fun createUi(): JComponent =
AnActionLink(actionId, BRANCH_ACTIONS_TOOLBAR)
.apply {
text = actionName
border = JBUI.Borders.emptyLeft(8)
}
}
object MultipleActionUi : StateUi() {
private lateinit var dropDownLink: DropDownLink<State>
private val invokeAction: JComponent.(String) -> Unit = { actionId ->
val action = ActionManager.getInstance().getAction(actionId)
ActionUtil.invokeAction(action, this, BRANCH_ACTIONS_TOOLBAR, null, null)
}
override fun createUi(): JComponent {
dropDownLink = DropDownLink(State.MULTIPLE_ACTIONS, listOf(State.CHECKOUT_ACTION, State.UPDATE_ACTION), Consumer { state ->
when (state) {
State.CHECKOUT_ACTION -> dropDownLink.invokeAction("Github.PullRequest.Branch.Create")
State.UPDATE_ACTION -> dropDownLink.invokeAction("Github.PullRequest.Branch.Update")
State.MULTIPLE_ACTIONS -> {}
}
})
.apply { border = JBUI.Borders.emptyLeft(8) }
return dropDownLink
}
}
}
override fun prepare(state: State): StateUi =
when (state) {
State.CHECKOUT_ACTION -> StateUi.CheckoutActionUi
State.UPDATE_ACTION -> StateUi.UpdateActionUi
State.MULTIPLE_ACTIONS -> StateUi.MultipleActionUi
}
override fun create(ui: StateUi): JComponent = ui.createUi()
}
private class GHPRBranchesTooltipFactory(var isOnCurrentBranch: Boolean = false,
var prBranchName: String = "",
var localBranchName: String? = null,
var remoteBranchName: String? = null) {
fun installTooltip(label: JBLabel) {
label.addMouseMotionListener(object : MouseAdapter() {
override fun mouseMoved(e: MouseEvent) {
showTooltip(e)
}
})
}
private fun showTooltip(e: MouseEvent) {
val point = e.point
if (IdeTooltipManager.getInstance().hasCurrent()) {
IdeTooltipManager.getInstance().hideCurrent(e)
}
val tooltip = IdeTooltip(e.component, point, Wrapper(createTooltip())).setPreferredPosition(Balloon.Position.below)
IdeTooltipManager.getInstance().show(tooltip, false)
}
private fun createTooltip(): GHPRBranchesTooltip =
GHPRBranchesTooltip(arrayListOf<BranchTooltipDescriptor>().apply {
if (isOnCurrentBranch) add(BranchTooltipDescriptor.head())
if (localBranchName != null) add(BranchTooltipDescriptor.localBranch(localBranchName!!))
if (remoteBranchName != null) {
add(BranchTooltipDescriptor.remoteBranch(remoteBranchName!!))
}
else {
add(BranchTooltipDescriptor.prBranch(prBranchName))
}
})
}
} | apache-2.0 | cb65bfdbc8f4fda176ac22c03c9fd7b7 | 35.830508 | 134 | 0.684156 | 5.006336 | false | false | false | false |
Maccimo/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/impl/LineStatusTrackerManager.kt | 3 | 47465 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.vcs.impl
import com.google.common.collect.HashMultiset
import com.google.common.collect.Multiset
import com.intellij.codeWithMe.ClientId
import com.intellij.diagnostic.ThreadDumper
import com.intellij.icons.AllIcons
import com.intellij.notification.Notification
import com.intellij.notification.NotificationAction
import com.intellij.notification.NotificationType
import com.intellij.notification.NotificationsManager
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.*
import com.intellij.openapi.command.CommandEvent
import com.intellij.openapi.command.CommandListener
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.editor.event.EditorFactoryEvent
import com.intellij.openapi.editor.event.EditorFactoryListener
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileDocumentManagerListener
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.util.BackgroundTaskUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.*
import com.intellij.openapi.vcs.changes.*
import com.intellij.openapi.vcs.changes.conflicts.ChangelistConflictFileStatusProvider
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.LOCAL_CHANGES
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.getToolWindowFor
import com.intellij.openapi.vcs.checkin.CheckinHandler
import com.intellij.openapi.vcs.checkin.CheckinHandlerFactory
import com.intellij.openapi.vcs.ex.*
import com.intellij.openapi.vcs.history.VcsRevisionNumber
import com.intellij.openapi.vcs.impl.LineStatusTrackerContentLoader.ContentInfo
import com.intellij.openapi.vcs.impl.LineStatusTrackerContentLoader.TrackerContent
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.openapi.vfs.newvfs.events.VFileMoveEvent
import com.intellij.openapi.vfs.newvfs.events.VFilePropertyChangeEvent
import com.intellij.testFramework.LightVirtualFile
import com.intellij.util.EventDispatcher
import com.intellij.util.concurrency.Semaphore
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.ui.UIUtil
import com.intellij.vcs.commit.isNonModalCommit
import com.intellij.vcsUtil.VcsUtil
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.CalledInAny
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.TestOnly
import java.nio.charset.Charset
import java.util.*
import java.util.concurrent.Future
import java.util.function.Supplier
class LineStatusTrackerManager(private val project: Project) : LineStatusTrackerManagerI, Disposable {
private val LOCK = Any()
private var isDisposed = false
private val trackers = HashMap<Document, TrackerData>()
private val forcedDocuments = HashMap<Document, Multiset<Any>>()
private val eventDispatcher = EventDispatcher.create(Listener::class.java)
private var partialChangeListsEnabled: Boolean = false
private val documentsInDefaultChangeList = HashSet<Document>()
private var clmFreezeCounter: Int = 0
private val filesWithDamagedInactiveRanges = HashSet<VirtualFile>()
private val fileStatesAwaitingRefresh = HashMap<VirtualFile, ChangelistsLocalLineStatusTracker.State>()
private val loader = MyBaseRevisionLoader()
companion object {
private val LOG = Logger.getInstance(LineStatusTrackerManager::class.java)
@JvmStatic
fun getInstance(project: Project): LineStatusTrackerManagerI = project.service()
@JvmStatic
fun getInstanceImpl(project: Project): LineStatusTrackerManager {
return getInstance(project) as LineStatusTrackerManager
}
}
internal class MyStartupActivity : VcsStartupActivity {
override fun runActivity(project: Project) {
getInstanceImpl(project).startListenForEditors()
}
override fun getOrder(): Int = VcsInitObject.OTHER_INITIALIZATION.order
}
private fun startListenForEditors() {
val busConnection = project.messageBus.connect()
busConnection.subscribe(LineStatusTrackerSettingListener.TOPIC, MyLineStatusTrackerSettingListener())
busConnection.subscribe(VcsFreezingProcess.Listener.TOPIC, MyFreezeListener())
busConnection.subscribe(CommandListener.TOPIC, MyCommandListener())
busConnection.subscribe(ChangeListListener.TOPIC, MyChangeListListener())
busConnection.subscribe(ChangeListAvailabilityListener.TOPIC, MyChangeListAvailabilityListener())
ApplicationManager.getApplication().messageBus.connect(this)
.subscribe(VirtualFileManager.VFS_CHANGES, MyVirtualFileListener())
LocalLineStatusTrackerProvider.EP_NAME.addChangeListener(Runnable { updateTrackingSettings() }, this)
updatePartialChangeListsAvailability()
AppUIExecutor.onUiThread().expireWith(project).execute {
if (project.isDisposed) {
return@execute
}
ApplicationManager.getApplication().addApplicationListener(MyApplicationListener(), this)
FileStatusManager.getInstance(project).addFileStatusListener(MyFileStatusListener(), this)
EditorFactory.getInstance().eventMulticaster.addDocumentListener(MyDocumentListener(), this)
MyEditorFactoryListener().install(this)
onEverythingChanged()
PartialLineStatusTrackerManagerState.restoreState(project)
}
}
override fun dispose() {
isDisposed = true
Disposer.dispose(loader)
synchronized(LOCK) {
for ((document, multiset) in forcedDocuments) {
for (requester in multiset.elementSet()) {
warn("Tracker is being held on dispose by $requester", document)
}
}
forcedDocuments.clear()
for (data in trackers.values) {
unregisterTrackerInCLM(data)
data.tracker.release()
}
trackers.clear()
}
}
override fun getLineStatusTracker(document: Document): LineStatusTracker<*>? {
synchronized(LOCK) {
return trackers[document]?.tracker
}
}
override fun getLineStatusTracker(file: VirtualFile): LineStatusTracker<*>? {
val document = FileDocumentManager.getInstance().getCachedDocument(file) ?: return null
return getLineStatusTracker(document)
}
@RequiresEdt
override fun requestTrackerFor(document: Document, requester: Any) {
ApplicationManager.getApplication().assertIsWriteThread()
synchronized(LOCK) {
if (isDisposed) {
warn("Tracker is being requested after dispose by $requester", document)
return
}
val multiset = forcedDocuments.computeIfAbsent(document) { HashMultiset.create<Any>() }
multiset.add(requester)
if (trackers[document] == null) {
val virtualFile = FileDocumentManager.getInstance().getFile(document) ?: return
switchTracker(virtualFile, document)
}
}
}
@RequiresEdt
override fun releaseTrackerFor(document: Document, requester: Any) {
ApplicationManager.getApplication().assertIsWriteThread()
synchronized(LOCK) {
val multiset = forcedDocuments[document]
if (multiset == null || !multiset.contains(requester)) {
warn("Tracker release underflow by $requester", document)
return
}
multiset.remove(requester)
if (multiset.isEmpty()) {
forcedDocuments.remove(document)
checkIfTrackerCanBeReleased(document)
}
}
}
override fun invokeAfterUpdate(task: Runnable) {
loader.addAfterUpdateRunnable(task)
}
fun getTrackers(): List<LineStatusTracker<*>> {
synchronized(LOCK) {
return trackers.values.map { it.tracker }
}
}
fun addTrackerListener(listener: Listener, disposable: Disposable) {
eventDispatcher.addListener(listener, disposable)
}
open class ListenerAdapter : Listener
interface Listener : EventListener {
fun onTrackerAdded(tracker: LineStatusTracker<*>) {
}
fun onTrackerRemoved(tracker: LineStatusTracker<*>) {
}
}
@RequiresEdt
private fun checkIfTrackerCanBeReleased(document: Document) {
synchronized(LOCK) {
val data = trackers[document] ?: return
if (forcedDocuments.containsKey(document)) return
if (data.tracker is ChangelistsLocalLineStatusTracker) {
val hasPartialChanges = data.tracker.hasPartialState()
if (hasPartialChanges) {
log("checkIfTrackerCanBeReleased - hasPartialChanges", data.tracker.virtualFile)
return
}
val isLoading = loader.hasRequestFor(document)
if (isLoading) {
log("checkIfTrackerCanBeReleased - isLoading", data.tracker.virtualFile)
if (data.tracker.hasPendingPartialState() ||
fileStatesAwaitingRefresh.containsKey(data.tracker.virtualFile)) {
log("checkIfTrackerCanBeReleased - has pending state", data.tracker.virtualFile)
return
}
}
}
releaseTracker(document)
}
}
@RequiresEdt
private fun onEverythingChanged() {
ApplicationManager.getApplication().assertIsWriteThread()
synchronized(LOCK) {
if (isDisposed) return
log("onEverythingChanged", null)
val files = HashSet<VirtualFile>()
for (data in trackers.values) {
files.add(data.tracker.virtualFile)
}
for (document in forcedDocuments.keys) {
val file = FileDocumentManager.getInstance().getFile(document)
if (file != null) files.add(file)
}
for (file in files) {
onFileChanged(file)
}
}
}
@RequiresEdt
private fun onFileChanged(virtualFile: VirtualFile) {
val document = FileDocumentManager.getInstance().getCachedDocument(virtualFile) ?: return
synchronized(LOCK) {
if (isDisposed) return
log("onFileChanged", virtualFile)
val tracker = trackers[document]?.tracker
if (tracker != null || forcedDocuments.containsKey(document)) {
switchTracker(virtualFile, document, refreshExisting = true)
}
}
}
private fun registerTrackerInCLM(data: TrackerData) {
val tracker = data.tracker
if (tracker !is ChangelistsLocalLineStatusTracker) return
val filePath = VcsUtil.getFilePath(tracker.virtualFile)
if (data.clmFilePath != null) {
LOG.error("[registerTrackerInCLM] tracker already registered")
return
}
ChangeListManagerImpl.getInstanceImpl(project).registerChangeTracker(filePath, tracker)
data.clmFilePath = filePath
}
private fun unregisterTrackerInCLM(data: TrackerData, wasUnbound: Boolean = false) {
val tracker = data.tracker
if (tracker !is ChangelistsLocalLineStatusTracker) return
val filePath = data.clmFilePath
if (filePath == null) {
LOG.error("[unregisterTrackerInCLM] tracker is not registered")
return
}
ChangeListManagerImpl.getInstanceImpl(project).unregisterChangeTracker(filePath, tracker)
data.clmFilePath = null
val actualFilePath = VcsUtil.getFilePath(tracker.virtualFile)
if (filePath != actualFilePath && !wasUnbound) {
LOG.error("[unregisterTrackerInCLM] unexpected file path: expected: $filePath, actual: $actualFilePath")
}
}
private fun reregisterTrackerInCLM(data: TrackerData) {
val tracker = data.tracker
if (tracker !is ChangelistsLocalLineStatusTracker) return
val oldFilePath = data.clmFilePath
val newFilePath = VcsUtil.getFilePath(tracker.virtualFile)
if (oldFilePath == null) {
LOG.error("[reregisterTrackerInCLM] tracker is not registered")
return
}
if (oldFilePath != newFilePath) {
ChangeListManagerImpl.getInstanceImpl(project).unregisterChangeTracker(oldFilePath, tracker)
ChangeListManagerImpl.getInstanceImpl(project).registerChangeTracker(newFilePath, tracker)
data.clmFilePath = newFilePath
}
}
private fun canCreateTrackerFor(virtualFile: VirtualFile?): Boolean {
if (isDisposed) return false
if (virtualFile == null || virtualFile is LightVirtualFile) return false
if (runReadAction { !virtualFile.isValid || virtualFile.fileType.isBinary || FileUtilRt.isTooLarge(virtualFile.length) }) return false
return true
}
override fun arePartialChangelistsEnabled(): Boolean = partialChangeListsEnabled
override fun arePartialChangelistsEnabled(virtualFile: VirtualFile): Boolean {
if (!partialChangeListsEnabled) return false
val vcs = VcsUtil.getVcsFor(project, virtualFile)
return vcs != null && vcs.arePartialChangelistsSupported()
}
private fun switchTracker(virtualFile: VirtualFile, document: Document,
refreshExisting: Boolean = false) {
val provider = getTrackerProvider(virtualFile)
val oldTracker = trackers[document]?.tracker
if (oldTracker != null && provider != null && provider.isMyTracker(oldTracker)) {
if (refreshExisting) {
refreshTracker(oldTracker, provider)
}
}
else {
releaseTracker(document)
if (provider != null) installTracker(virtualFile, document, provider)
}
}
private fun installTracker(virtualFile: VirtualFile, document: Document,
provider: LocalLineStatusTrackerProvider): LocalLineStatusTracker<*>? {
if (isDisposed) return null
if (trackers[document] != null) return null
val tracker = provider.createTracker(project, virtualFile) ?: return null
tracker.mode = getTrackingMode()
val data = TrackerData(tracker)
val replacedData = trackers.put(document, data)
LOG.assertTrue(replacedData == null)
registerTrackerInCLM(data)
refreshTracker(tracker, provider)
eventDispatcher.multicaster.onTrackerAdded(tracker)
if (clmFreezeCounter > 0) {
tracker.freeze()
}
log("Tracker installed", virtualFile)
return tracker
}
private fun getTrackerProvider(virtualFile: VirtualFile): LocalLineStatusTrackerProvider? {
if (!canCreateTrackerFor(virtualFile)) {
return null
}
LocalLineStatusTrackerProvider.EP_NAME.findFirstSafe { it.isTrackedFile(project, virtualFile) }?.let {
return it
}
return listOf(ChangelistsLocalStatusTrackerProvider, DefaultLocalStatusTrackerProvider).find { it.isTrackedFile(project, virtualFile) }
}
@RequiresEdt
private fun releaseTracker(document: Document, wasUnbound: Boolean = false) {
val data = trackers.remove(document) ?: return
eventDispatcher.multicaster.onTrackerRemoved(data.tracker)
unregisterTrackerInCLM(data, wasUnbound)
data.tracker.release()
log("Tracker released", data.tracker.virtualFile)
}
private fun updatePartialChangeListsAvailability() {
partialChangeListsEnabled = VcsApplicationSettings.getInstance().ENABLE_PARTIAL_CHANGELISTS &&
ChangeListManager.getInstance(project).areChangeListsEnabled()
}
private fun updateTrackingSettings() {
synchronized(LOCK) {
if (isDisposed) return
val mode = getTrackingMode()
for (data in trackers.values) {
data.tracker.mode = mode
}
}
onEverythingChanged()
}
private fun getTrackingMode(): LocalLineStatusTracker.Mode {
val settings = VcsApplicationSettings.getInstance()
return LocalLineStatusTracker.Mode(settings.SHOW_LST_GUTTER_MARKERS,
settings.SHOW_LST_ERROR_STRIPE_MARKERS,
settings.SHOW_WHITESPACES_IN_LST)
}
@RequiresEdt
private fun refreshTracker(tracker: LocalLineStatusTracker<*>,
provider: LocalLineStatusTrackerProvider) {
if (isDisposed) return
if (provider !is LineStatusTrackerContentLoader) return
loader.scheduleRefresh(RefreshRequest(tracker.document, provider))
log("Refresh queued", tracker.virtualFile)
}
private inner class MyBaseRevisionLoader : SingleThreadLoader<RefreshRequest, RefreshData>() {
fun hasRequestFor(document: Document): Boolean {
return hasRequest { it.document == document }
}
override fun loadRequest(request: RefreshRequest): Result<RefreshData> {
if (isDisposed) return Result.Canceled()
val document = request.document
val virtualFile = FileDocumentManager.getInstance().getFile(document)
val loader = request.loader
log("Loading started", virtualFile)
if (virtualFile == null || !virtualFile.isValid) {
log("Loading error: virtual file is not valid", virtualFile)
return Result.Error()
}
if (!canCreateTrackerFor(virtualFile) || !loader.isTrackedFile(project, virtualFile)) {
log("Loading error: virtual file is not a tracked file", virtualFile)
return Result.Error()
}
val newContentInfo = loader.getContentInfo(project, virtualFile)
if (newContentInfo == null) {
log("Loading error: base revision not found", virtualFile)
return Result.Error()
}
synchronized(LOCK) {
val data = trackers[document]
if (data == null) {
log("Loading cancelled: tracker not found", virtualFile)
return Result.Canceled()
}
if (!loader.shouldBeUpdated(data.contentInfo, newContentInfo)) {
log("Loading cancelled: no need to update", virtualFile)
return Result.Canceled()
}
}
val content = loader.loadContent(project, newContentInfo)
if (content == null) {
log("Loading error: provider failure", virtualFile)
return Result.Error()
}
log("Loading successful", virtualFile)
return Result.Success(RefreshData(content, newContentInfo))
}
@RequiresEdt
override fun handleResult(request: RefreshRequest, result: Result<RefreshData>) {
val document = request.document
when (result) {
is Result.Canceled -> handleCanceled(document)
is Result.Error -> handleError(request, document)
is Result.Success -> handleSuccess(request, document, result.data)
}
checkIfTrackerCanBeReleased(document)
}
private fun handleCanceled(document: Document) {
restorePendingTrackerState(document)
}
private fun handleError(request: RefreshRequest, document: Document) {
synchronized(LOCK) {
val loader = request.loader
val data = trackers[document] ?: return
val tracker = data.tracker
if (loader.isMyTracker(tracker)) {
loader.handleLoadingError(tracker)
}
data.contentInfo = null
}
}
private fun handleSuccess(request: RefreshRequest, document: Document, refreshData: RefreshData) {
val virtualFile = FileDocumentManager.getInstance().getFile(document)!!
val loader = request.loader
val tracker: LocalLineStatusTracker<*>
synchronized(LOCK) {
val data = trackers[document]
if (data == null) {
log("Loading finished: tracker already released", virtualFile)
return
}
if (!loader.shouldBeUpdated(data.contentInfo, refreshData.contentInfo)) {
log("Loading finished: no need to update", virtualFile)
return
}
data.contentInfo = refreshData.contentInfo
tracker = data.tracker
}
if (loader.isMyTracker(tracker)) {
loader.setLoadedContent(tracker, refreshData.content)
log("Loading finished: success", virtualFile)
}
else {
log("Loading finished: wrong tracker. tracker: $tracker, loader: $loader", virtualFile)
}
restorePendingTrackerState(document)
}
private fun restorePendingTrackerState(document: Document) {
val tracker = getLineStatusTracker(document)
if (tracker is ChangelistsLocalLineStatusTracker) {
val virtualFile = tracker.virtualFile
val state = synchronized(LOCK) {
fileStatesAwaitingRefresh.remove(virtualFile) ?: return
}
val success = tracker.restoreState(state)
log("Pending state restored. success - $success", virtualFile)
}
}
}
/**
* We can speedup initial content loading if it was already loaded by someone.
* We do not set 'contentInfo' here to ensure, that following refresh will fix potential inconsistency.
*/
@RequiresEdt
@ApiStatus.Internal
fun offerTrackerContent(document: Document, text: CharSequence) {
try {
val tracker: LocalLineStatusTracker<*>
synchronized(LOCK) {
val data = trackers[document]
if (data == null || data.contentInfo != null) return
tracker = data.tracker
}
if (tracker is LocalLineStatusTrackerImpl<*>) {
ClientId.withClientId(ClientId.localId) {
tracker.setBaseRevision(text)
log("Offered content", tracker.virtualFile)
}
}
}
catch (e: Throwable) {
LOG.error(e)
}
}
private inner class MyFileStatusListener : FileStatusListener {
override fun fileStatusesChanged() {
onEverythingChanged()
}
override fun fileStatusChanged(virtualFile: VirtualFile) {
onFileChanged(virtualFile)
}
}
private inner class MyEditorFactoryListener : EditorFactoryListener {
fun install(disposable: Disposable) {
val editorFactory = EditorFactory.getInstance()
for (editor in editorFactory.allEditors) {
if (isTrackedEditor(editor)) {
requestTrackerFor(editor.document, editor)
}
}
editorFactory.addEditorFactoryListener(this, disposable)
}
override fun editorCreated(event: EditorFactoryEvent) {
val editor = event.editor
if (isTrackedEditor(editor)) {
requestTrackerFor(editor.document, editor)
}
}
override fun editorReleased(event: EditorFactoryEvent) {
val editor = event.editor
if (isTrackedEditor(editor)) {
releaseTrackerFor(editor.document, editor)
}
}
private fun isTrackedEditor(editor: Editor): Boolean {
// can't filter out "!isInLocalFileSystem" files, custom VcsBaseContentProvider can handle them
// check for isDisposed - light project in tests
return !project.isDisposed &&
(editor.project == null || editor.project == project) &&
FileDocumentManager.getInstance().getFile(editor.document) != null
}
}
private inner class MyVirtualFileListener : BulkFileListener {
override fun before(events: List<VFileEvent>) {
for (event in events) {
when (event) {
is VFileDeleteEvent -> handleFileDeletion(event.file)
}
}
}
override fun after(events: List<VFileEvent>) {
for (event in events) {
when (event) {
is VFilePropertyChangeEvent -> when {
VirtualFile.PROP_ENCODING == event.propertyName -> onFileChanged(event.file)
event.isRename -> handleFileMovement(event.file)
}
is VFileMoveEvent -> handleFileMovement(event.file)
}
}
}
private fun handleFileMovement(file: VirtualFile) {
if (!partialChangeListsEnabled) return
synchronized(LOCK) {
forEachTrackerUnder(file) { data ->
reregisterTrackerInCLM(data)
}
}
}
private fun handleFileDeletion(file: VirtualFile) {
if (!partialChangeListsEnabled) return
synchronized(LOCK) {
forEachTrackerUnder(file) { data ->
releaseTracker(data.tracker.document)
}
}
}
private fun forEachTrackerUnder(file: VirtualFile, action: (TrackerData) -> Unit) {
if (file.isDirectory) {
val affected = trackers.values.filter { VfsUtil.isAncestor(file, it.tracker.virtualFile, false) }
for (data in affected) {
action(data)
}
}
else {
val document = FileDocumentManager.getInstance().getCachedDocument(file) ?: return
val data = trackers[document] ?: return
action(data)
}
}
}
internal class MyFileDocumentManagerListener : FileDocumentManagerListener {
override fun afterDocumentUnbound(file: VirtualFile, document: Document) {
val projectManager = ProjectManager.getInstanceIfCreated() ?: return
for (project in projectManager.openProjects) {
val lstm = project.getServiceIfCreated(LineStatusTrackerManagerI::class.java) as? LineStatusTrackerManager ?: continue
lstm.releaseTracker(document, wasUnbound = true)
}
}
}
private inner class MyDocumentListener : DocumentListener {
override fun documentChanged(event: DocumentEvent) {
if (!ApplicationManager.getApplication().isDispatchThread) return // disable for documents forUseInNonAWTThread
if (!partialChangeListsEnabled || project.isDisposed) return
val document = event.document
if (documentsInDefaultChangeList.contains(document)) return
val virtualFile = FileDocumentManager.getInstance().getFile(document) ?: return
if (getLineStatusTracker(document) != null) return
val provider = getTrackerProvider(virtualFile)
if (provider != ChangelistsLocalStatusTrackerProvider) return
val changeList = ChangeListManager.getInstance(project).getChangeList(virtualFile)
val inAnotherChangelist = changeList != null && !ActiveChangeListTracker.getInstance(project).isActiveChangeList(changeList)
if (inAnotherChangelist) {
log("Tracker install from DocumentListener: ", virtualFile)
val tracker = synchronized(LOCK) {
installTracker(virtualFile, document, provider)
}
if (tracker is ChangelistsLocalLineStatusTracker) {
tracker.replayChangesFromDocumentEvents(listOf(event))
}
}
else {
documentsInDefaultChangeList.add(document)
}
}
}
private inner class MyApplicationListener : ApplicationListener {
override fun afterWriteActionFinished(action: Any) {
documentsInDefaultChangeList.clear()
synchronized(LOCK) {
val documents = trackers.values.map { it.tracker.document }
for (document in documents) {
checkIfTrackerCanBeReleased(document)
}
}
}
}
private inner class MyLineStatusTrackerSettingListener : LineStatusTrackerSettingListener {
override fun settingsUpdated() {
updatePartialChangeListsAvailability()
updateTrackingSettings()
}
}
private inner class MyChangeListListener : ChangeListAdapter() {
override fun defaultListChanged(oldDefaultList: ChangeList?, newDefaultList: ChangeList?) {
runInEdt(ModalityState.any()) {
if (project.isDisposed) return@runInEdt
expireInactiveRangesDamagedNotifications()
EditorFactory.getInstance().allEditors
.forEach { if (it is EditorEx) it.gutterComponentEx.repaint() }
}
}
}
private inner class MyChangeListAvailabilityListener : ChangeListAvailabilityListener {
override fun onBefore() {
if (ChangeListManager.getInstance(project).areChangeListsEnabled()) {
val fileStates = getInstanceImpl(project).collectPartiallyChangedFilesStates()
if (fileStates.isNotEmpty()) {
PartialLineStatusTrackerManagerState.saveCurrentState(project, fileStates)
}
}
}
override fun onAfter() {
updatePartialChangeListsAvailability()
onEverythingChanged()
if (ChangeListManager.getInstance(project).areChangeListsEnabled()) {
PartialLineStatusTrackerManagerState.restoreState(project)
}
}
}
private inner class MyCommandListener : CommandListener {
override fun commandFinished(event: CommandEvent) {
if (!partialChangeListsEnabled) return
if (CommandProcessor.getInstance().currentCommand == null &&
!filesWithDamagedInactiveRanges.isEmpty()) {
showInactiveRangesDamagedNotification()
}
}
}
class CheckinFactory : CheckinHandlerFactory() {
override fun createHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler {
val project = panel.project
return object : CheckinHandler() {
override fun checkinSuccessful() {
resetExcludedFromCommit()
}
override fun checkinFailed(exception: MutableList<VcsException>?) {
resetExcludedFromCommit()
}
private fun resetExcludedFromCommit() {
runInEdt {
// TODO Move this to SingleChangeListCommitWorkflow
if (!project.isDisposed && !panel.isNonModalCommit) getInstanceImpl(project).resetExcludedFromCommitMarkers()
}
}
}
}
}
private inner class MyFreezeListener : VcsFreezingProcess.Listener {
override fun onFreeze() {
runReadAction {
synchronized(LOCK) {
if (clmFreezeCounter == 0) {
for (data in trackers.values) {
try {
data.tracker.freeze()
}
catch (e: Throwable) {
LOG.error(e)
}
}
}
clmFreezeCounter++
}
}
}
override fun onUnfreeze() {
runInEdt(ModalityState.any()) {
synchronized(LOCK) {
clmFreezeCounter--
if (clmFreezeCounter == 0) {
for (data in trackers.values) {
try {
data.tracker.unfreeze()
}
catch (e: Throwable) {
LOG.error(e)
}
}
}
}
}
}
}
private class TrackerData(val tracker: LocalLineStatusTracker<*>,
var contentInfo: ContentInfo? = null,
var clmFilePath: FilePath? = null)
private class RefreshRequest(val document: Document, val loader: LineStatusTrackerContentLoader) {
override fun equals(other: Any?): Boolean = other is RefreshRequest && document == other.document
override fun hashCode(): Int = document.hashCode()
override fun toString(): String = "RefreshRequest: " + (FileDocumentManager.getInstance().getFile(document)?.path ?: "unknown") // NON-NLS
}
private class RefreshData(val content: TrackerContent,
val contentInfo: ContentInfo)
private fun log(@NonNls message: String, file: VirtualFile?) {
if (LOG.isDebugEnabled) {
if (file != null) {
LOG.debug(message + "; file: " + file.path)
}
else {
LOG.debug(message)
}
}
}
private fun warn(@NonNls message: String, document: Document?) {
val file = document?.let { FileDocumentManager.getInstance().getFile(it) }
warn(message, file)
}
private fun warn(@NonNls message: String, file: VirtualFile?) {
if (file != null) {
LOG.warn(message + "; file: " + file.path)
}
else {
LOG.warn(message)
}
}
@RequiresEdt
fun resetExcludedFromCommitMarkers() {
ApplicationManager.getApplication().assertIsWriteThread()
synchronized(LOCK) {
val documents = mutableListOf<Document>()
for (data in trackers.values) {
val tracker = data.tracker
if (tracker is ChangelistsLocalLineStatusTracker) {
tracker.resetExcludedFromCommitMarkers()
documents.add(tracker.document)
}
}
for (document in documents) {
checkIfTrackerCanBeReleased(document)
}
}
}
internal fun collectPartiallyChangedFilesStates(): List<ChangelistsLocalLineStatusTracker.FullState> {
ApplicationManager.getApplication().assertReadAccessAllowed()
val result = mutableListOf<ChangelistsLocalLineStatusTracker.FullState>()
synchronized(LOCK) {
for (data in trackers.values) {
val tracker = data.tracker
if (tracker is ChangelistsLocalLineStatusTracker) {
val hasPartialChanges = tracker.affectedChangeListsIds.size > 1
if (hasPartialChanges) {
result.add(tracker.storeTrackerState())
}
}
}
}
return result
}
@RequiresEdt
internal fun restoreTrackersForPartiallyChangedFiles(trackerStates: List<ChangelistsLocalLineStatusTracker.State>) {
runWriteAction {
synchronized(LOCK) {
if (isDisposed) return@runWriteAction
for (state in trackerStates) {
val virtualFile = state.virtualFile
val document = FileDocumentManager.getInstance().getDocument(virtualFile) ?: continue
val provider = getTrackerProvider(virtualFile)
if (provider != ChangelistsLocalStatusTrackerProvider) continue
switchTracker(virtualFile, document)
val tracker = trackers[document]?.tracker
if (tracker !is ChangelistsLocalLineStatusTracker) continue
val isLoading = loader.hasRequestFor(document)
if (isLoading) {
fileStatesAwaitingRefresh.put(state.virtualFile, state)
log("State restoration scheduled", virtualFile)
}
else {
val success = tracker.restoreState(state)
log("State restored. success - $success", virtualFile)
}
}
loader.addAfterUpdateRunnable(Runnable {
synchronized(LOCK) {
log("State restoration finished", null)
fileStatesAwaitingRefresh.clear()
}
})
}
}
onEverythingChanged()
}
@RequiresEdt
internal fun notifyInactiveRangesDamaged(virtualFile: VirtualFile) {
ApplicationManager.getApplication().assertIsWriteThread()
if (filesWithDamagedInactiveRanges.contains(virtualFile) || virtualFile == FileEditorManagerEx.getInstanceEx(project).currentFile) {
return
}
filesWithDamagedInactiveRanges.add(virtualFile)
}
private fun showInactiveRangesDamagedNotification() {
val currentNotifications = NotificationsManager.getNotificationsManager()
.getNotificationsOfType(InactiveRangesDamagedNotification::class.java, project)
val lastNotification = currentNotifications.lastOrNull { !it.isExpired }
if (lastNotification != null) filesWithDamagedInactiveRanges.addAll(lastNotification.virtualFiles)
currentNotifications.forEach { it.expire() }
val files = filesWithDamagedInactiveRanges.toSet()
filesWithDamagedInactiveRanges.clear()
InactiveRangesDamagedNotification(project, files).notify(project)
}
@RequiresEdt
private fun expireInactiveRangesDamagedNotifications() {
filesWithDamagedInactiveRanges.clear()
val currentNotifications = NotificationsManager.getNotificationsManager()
.getNotificationsOfType(InactiveRangesDamagedNotification::class.java, project)
currentNotifications.forEach { it.expire() }
}
private class InactiveRangesDamagedNotification(project: Project, val virtualFiles: Set<VirtualFile>)
: Notification(VcsNotifier.STANDARD_NOTIFICATION.displayId,
VcsBundle.message("lst.inactive.ranges.damaged.notification"),
NotificationType.INFORMATION) {
init {
icon = AllIcons.Toolwindows.ToolWindowChanges
setDisplayId(VcsNotificationIdsHolder.INACTIVE_RANGES_DAMAGED)
addAction(NotificationAction.createSimple(
Supplier { VcsBundle.message("action.NotificationAction.InactiveRangesDamagedNotification.text.view.changes") },
Runnable {
val defaultList = ChangeListManager.getInstance(project).defaultChangeList
val changes = defaultList.changes.filter { virtualFiles.contains(it.virtualFile) }
val window = getToolWindowFor(project, LOCAL_CHANGES)
window?.activate { ChangesViewManager.getInstance(project).selectChanges(changes) }
expire()
}))
}
}
@TestOnly
fun waitUntilBaseContentsLoaded() {
assert(ApplicationManager.getApplication().isUnitTestMode)
if (ApplicationManager.getApplication().isDispatchThread) {
UIUtil.dispatchAllInvocationEvents()
}
val semaphore = Semaphore()
semaphore.down()
loader.addAfterUpdateRunnable(Runnable {
semaphore.up()
})
val start = System.currentTimeMillis()
while (true) {
if (ApplicationManager.getApplication().isDispatchThread) {
UIUtil.dispatchAllInvocationEvents()
}
if (semaphore.waitFor(10)) {
return
}
if (System.currentTimeMillis() - start > 10000) {
loader.dumpInternalState()
System.err.println(ThreadDumper.dumpThreadsToString())
throw IllegalStateException("Couldn't await base contents") // NON-NLS
}
}
}
@TestOnly
fun releaseAllTrackers() {
synchronized(LOCK) {
forcedDocuments.clear()
for (data in trackers.values) {
unregisterTrackerInCLM(data)
data.tracker.release()
}
trackers.clear()
}
}
}
/**
* Single threaded queue with the following properties:
* - Ignores duplicated requests (the first queued is used).
* - Allows to check whether request is scheduled or is waiting for completion.
* - Notifies callbacks when queue is exhausted.
*/
private abstract class SingleThreadLoader<Request, T> : Disposable {
companion object {
private val LOG = Logger.getInstance(SingleThreadLoader::class.java)
}
private val LOCK: Any = Any()
private val taskQueue = ArrayDeque<Request>()
private val waitingForRefresh = HashSet<Request>()
private val callbacksWaitingUpdateCompletion = ArrayList<Runnable>()
private var isScheduled: Boolean = false
private var isDisposed: Boolean = false
private var lastFuture: Future<*>? = null
@RequiresBackgroundThread
protected abstract fun loadRequest(request: Request): Result<T>
@RequiresEdt
protected abstract fun handleResult(request: Request, result: Result<T>)
@RequiresEdt
fun scheduleRefresh(request: Request) {
if (isDisposed) return
synchronized(LOCK) {
if (taskQueue.contains(request)) return
taskQueue.add(request)
schedule()
}
}
@RequiresEdt
override fun dispose() {
val callbacks = mutableListOf<Runnable>()
synchronized(LOCK) {
isDisposed = true
taskQueue.clear()
waitingForRefresh.clear()
lastFuture?.cancel(true)
callbacks += callbacksWaitingUpdateCompletion
callbacksWaitingUpdateCompletion.clear()
}
executeCallbacks(callbacksWaitingUpdateCompletion)
}
@RequiresEdt
protected fun hasRequest(condition: (Request) -> Boolean): Boolean {
synchronized(LOCK) {
return taskQueue.any(condition) ||
waitingForRefresh.any(condition)
}
}
@CalledInAny
fun addAfterUpdateRunnable(task: Runnable) {
val updateScheduled = putRunnableIfUpdateScheduled(task)
if (updateScheduled) return
runInEdt(ModalityState.any()) {
if (!putRunnableIfUpdateScheduled(task)) {
task.run()
}
}
}
private fun putRunnableIfUpdateScheduled(task: Runnable): Boolean {
synchronized(LOCK) {
if (taskQueue.isEmpty() && waitingForRefresh.isEmpty()) return false
callbacksWaitingUpdateCompletion.add(task)
return true
}
}
private fun schedule() {
if (isDisposed) return
synchronized(LOCK) {
if (isScheduled) return
if (taskQueue.isEmpty()) return
isScheduled = true
lastFuture = ApplicationManager.getApplication().executeOnPooledThread {
ClientId.withClientId(ClientId.localId) {
BackgroundTaskUtil.runUnderDisposeAwareIndicator(this, Runnable {
handleRequests()
})
}
}
}
}
private fun handleRequests() {
while (true) {
val request = synchronized(LOCK) {
val request = taskQueue.poll()
if (isDisposed || request == null) {
isScheduled = false
return
}
waitingForRefresh.add(request)
return@synchronized request
}
handleSingleRequest(request)
}
}
private fun handleSingleRequest(request: Request) {
val result: Result<T> = try {
loadRequest(request)
}
catch (e: ProcessCanceledException) {
Result.Canceled()
}
catch (e: Throwable) {
LOG.error(e)
Result.Error()
}
runInEdt(ModalityState.any()) {
try {
synchronized(LOCK) {
waitingForRefresh.remove(request)
}
handleResult(request, result)
}
finally {
notifyTrackerRefreshed()
}
}
}
@RequiresEdt
private fun notifyTrackerRefreshed() {
if (isDisposed) return
val callbacks = mutableListOf<Runnable>()
synchronized(LOCK) {
if (taskQueue.isEmpty() && waitingForRefresh.isEmpty()) {
callbacks += callbacksWaitingUpdateCompletion
callbacksWaitingUpdateCompletion.clear()
}
}
executeCallbacks(callbacks)
}
@RequiresEdt
private fun executeCallbacks(callbacks: List<Runnable>) {
for (callback in callbacks) {
try {
callback.run()
}
catch (ignore: ProcessCanceledException) {
}
catch (e: Throwable) {
LOG.error(e)
}
}
}
@TestOnly
fun dumpInternalState() {
synchronized(LOCK) {
LOG.debug("isScheduled - $isScheduled")
LOG.debug("pending callbacks: ${callbacksWaitingUpdateCompletion.size}")
taskQueue.forEach {
LOG.debug("pending task: ${it}")
}
waitingForRefresh.forEach {
LOG.debug("waiting refresh: ${it}")
}
}
}
}
private sealed class Result<T> {
class Success<T>(val data: T) : Result<T>()
class Canceled<T> : Result<T>()
class Error<T> : Result<T>()
}
private object ChangelistsLocalStatusTrackerProvider : BaseRevisionStatusTrackerContentLoader() {
override fun isTrackedFile(project: Project, file: VirtualFile): Boolean {
if (!LineStatusTrackerManager.getInstance(project).arePartialChangelistsEnabled(file)) return false
if (!super.isTrackedFile(project, file)) return false
val status = FileStatusManager.getInstance(project).getStatus(file)
if (status != FileStatus.MODIFIED &&
status != ChangelistConflictFileStatusProvider.MODIFIED_OUTSIDE &&
status != FileStatus.NOT_CHANGED) return false
val change = ChangeListManager.getInstance(project).getChange(file)
return change == null ||
change.javaClass == Change::class.java &&
(change.type == Change.Type.MODIFICATION || change.type == Change.Type.MOVED) &&
change.afterRevision is CurrentContentRevision
}
override fun isMyTracker(tracker: LocalLineStatusTracker<*>): Boolean = tracker is ChangelistsLocalLineStatusTracker
override fun createTracker(project: Project, file: VirtualFile): LocalLineStatusTracker<*>? {
val document = FileDocumentManager.getInstance().getDocument(file) ?: return null
return ChangelistsLocalLineStatusTracker.createTracker(project, document, file)
}
}
private object DefaultLocalStatusTrackerProvider : BaseRevisionStatusTrackerContentLoader() {
override fun isMyTracker(tracker: LocalLineStatusTracker<*>): Boolean = tracker is SimpleLocalLineStatusTracker
override fun createTracker(project: Project, file: VirtualFile): LocalLineStatusTracker<*>? {
val document = FileDocumentManager.getInstance().getDocument(file) ?: return null
return SimpleLocalLineStatusTracker.createTracker(project, document, file)
}
}
private abstract class BaseRevisionStatusTrackerContentLoader : LineStatusTrackerContentLoader {
override fun isTrackedFile(project: Project, file: VirtualFile): Boolean {
if (!VcsFileStatusProvider.getInstance(project).isSupported(file)) return false
val status = FileStatusManager.getInstance(project).getStatus(file)
if (status == FileStatus.ADDED ||
status == FileStatus.DELETED ||
status == FileStatus.UNKNOWN ||
status == FileStatus.IGNORED) {
return false
}
return true
}
override fun getContentInfo(project: Project, file: VirtualFile): ContentInfo? {
val baseContent = VcsFileStatusProvider.getInstance(project).getBaseRevision(file) ?: return null
return BaseRevisionContentInfo(baseContent, file.charset)
}
override fun shouldBeUpdated(oldInfo: ContentInfo?, newInfo: ContentInfo): Boolean {
newInfo as BaseRevisionContentInfo
return oldInfo == null ||
oldInfo !is BaseRevisionContentInfo ||
oldInfo.baseContent.revisionNumber != newInfo.baseContent.revisionNumber ||
oldInfo.baseContent.revisionNumber == VcsRevisionNumber.NULL ||
oldInfo.charset != newInfo.charset
}
override fun loadContent(project: Project, info: ContentInfo): TrackerContent? {
info as BaseRevisionContentInfo
val lastUpToDateContent = info.baseContent.loadContent() ?: return null
val correctedText = StringUtil.convertLineSeparators(lastUpToDateContent)
return BaseRevisionContent(correctedText)
}
override fun setLoadedContent(tracker: LocalLineStatusTracker<*>, content: TrackerContent) {
tracker as LocalLineStatusTrackerImpl<*>
content as BaseRevisionContent
tracker.setBaseRevision(content.text)
}
override fun handleLoadingError(tracker: LocalLineStatusTracker<*>) {
tracker as LocalLineStatusTrackerImpl<*>
tracker.dropBaseRevision()
}
private class BaseRevisionContentInfo(val baseContent: VcsBaseContentProvider.BaseContent, val charset: Charset) : ContentInfo
private class BaseRevisionContent(val text: CharSequence) : TrackerContent
}
interface LocalLineStatusTrackerProvider {
fun isTrackedFile(project: Project, file: VirtualFile): Boolean
fun isMyTracker(tracker: LocalLineStatusTracker<*>): Boolean
fun createTracker(project: Project, file: VirtualFile): LocalLineStatusTracker<*>?
companion object {
internal val EP_NAME =
ExtensionPointName<LocalLineStatusTrackerProvider>("com.intellij.openapi.vcs.impl.LocalLineStatusTrackerProvider")
}
}
interface LineStatusTrackerContentLoader : LocalLineStatusTrackerProvider {
fun getContentInfo(project: Project, file: VirtualFile): ContentInfo?
fun shouldBeUpdated(oldInfo: ContentInfo?, newInfo: ContentInfo): Boolean
fun loadContent(project: Project, info: ContentInfo): TrackerContent?
fun setLoadedContent(tracker: LocalLineStatusTracker<*>, content: TrackerContent)
fun handleLoadingError(tracker: LocalLineStatusTracker<*>)
interface ContentInfo
interface TrackerContent
}
| apache-2.0 | b5eaa34e32c996618e51c4216738c021 | 32.473202 | 142 | 0.702454 | 5.468948 | false | false | false | false |
Maccimo/intellij-community | platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/ToolboxLiteGen.kt | 1 | 2833 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.intellij.build.impl
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.SystemProperties
import com.intellij.util.execution.ParametersListUtil
import org.codehaus.groovy.runtime.ProcessGroovyMethods
import org.jetbrains.intellij.build.BuildMessages
import org.jetbrains.intellij.build.dependencies.BuildDependenciesCommunityRoot
import org.jetbrains.intellij.build.dependencies.BuildDependenciesDownloader
import org.jetbrains.intellij.build.dependencies.BuildDependenciesExtractOptions
import org.jetbrains.intellij.build.dependencies.BuildDependenciesManualRunOnly
import java.io.OutputStream
import java.net.URI
import java.nio.file.Files
import java.nio.file.Path
object ToolboxLiteGen {
private fun downloadToolboxLiteGen(communityRoot: BuildDependenciesCommunityRoot?, liteGenVersion: String): Path {
val liteGenUri = URI("https://repo.labs.intellij.net/toolbox/lite-gen/lite-gen-$liteGenVersion.zip")
val zip = BuildDependenciesDownloader.downloadFileToCacheLocation(communityRoot, liteGenUri)
return BuildDependenciesDownloader.extractFileToCacheLocation(communityRoot, zip, BuildDependenciesExtractOptions.STRIP_ROOT)
}
fun runToolboxLiteGen(communityRoot: BuildDependenciesCommunityRoot?,
messages: BuildMessages,
liteGenVersion: String,
vararg args: String) {
check(SystemInfo.isUnix) { "Currently, lite gen runs only on Unix" }
val liteGenPath = downloadToolboxLiteGen(communityRoot, liteGenVersion)
messages.info("Toolbox LiteGen is at $liteGenPath")
val binPath = liteGenPath.resolve("bin/lite")
check(Files.isExecutable(binPath)) { "File at \'$binPath\' is missing or not executable" }
val command: MutableList<String?> = ArrayList()
command.add(binPath.toString())
command.addAll(args)
messages.info("Running " + ParametersListUtil.join(command))
val processBuilder = ProcessBuilder(command)
processBuilder.directory(liteGenPath.toFile())
processBuilder.environment()["JAVA_HOME"] = SystemProperties.getJavaHome()
val process = processBuilder.start()
// todo get rid of ProcessGroovyMethods
ProcessGroovyMethods.consumeProcessOutputStream(process, System.out as OutputStream)
ProcessGroovyMethods.consumeProcessErrorStream(process, System.err as OutputStream)
val rc = process.waitFor()
check(rc == 0) { "\'${command.joinToString(separator = " ")}\' exited with exit code $rc" }
}
@JvmStatic
fun main(args: Array<String>) {
val path = downloadToolboxLiteGen(BuildDependenciesManualRunOnly.getCommunityRootFromWorkingDirectory(), "1.2.1553")
println("litegen is at $path")
}
} | apache-2.0 | 0386978bb62c6fbc23e911d788e05c91 | 51.481481 | 129 | 0.774797 | 4.801695 | false | false | false | false |
k9mail/k-9 | app/ui/legacy/src/main/java/com/fsck/k9/activity/setup/AccountSetupAccountType.kt | 2 | 5044 | package com.fsck.k9.activity.setup
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import com.fsck.k9.Account
import com.fsck.k9.Preferences
import com.fsck.k9.helper.EmailHelper.getDomainFromEmailAddress
import com.fsck.k9.mail.ConnectionSecurity
import com.fsck.k9.mail.ServerSettings
import com.fsck.k9.mailstore.SpecialLocalFoldersCreator
import com.fsck.k9.preferences.Protocols
import com.fsck.k9.setup.ServerNameSuggester
import com.fsck.k9.ui.R
import com.fsck.k9.ui.base.K9Activity
import org.koin.android.ext.android.inject
/**
* Prompts the user to select an account type. The account type, along with the
* passed in email address, password and makeDefault are then passed on to the
* AccountSetupIncoming activity.
*/
class AccountSetupAccountType : K9Activity() {
private val preferences: Preferences by inject()
private val serverNameSuggester: ServerNameSuggester by inject()
private val localFoldersCreator: SpecialLocalFoldersCreator by inject()
private lateinit var account: Account
private var makeDefault = false
private lateinit var initialAccountSettings: InitialAccountSettings
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setLayout(R.layout.account_setup_account_type)
setTitle(R.string.account_setup_account_type_title)
decodeArguments()
findViewById<View>(R.id.pop).setOnClickListener { setupPop3Account() }
findViewById<View>(R.id.imap).setOnClickListener { setupImapAccount() }
}
private fun decodeArguments() {
val accountUuid = intent.getStringExtra(EXTRA_ACCOUNT) ?: error("No account UUID provided")
account = preferences.getAccount(accountUuid) ?: error("No account with given UUID found")
makeDefault = intent.getBooleanExtra(EXTRA_MAKE_DEFAULT, false)
initialAccountSettings = intent.getParcelableExtra(EXTRA_INITIAL_ACCOUNT_SETTINGS)
?: error("Initial account settings are missing")
}
private fun setupPop3Account() {
setupAccount(Protocols.POP3)
}
private fun setupImapAccount() {
setupAccount(Protocols.IMAP)
}
private fun setupAccount(serverType: String) {
setupStoreAndSmtpTransport(serverType)
createSpecialLocalFolders()
returnAccountTypeSelectionResult()
}
private fun setupStoreAndSmtpTransport(serverType: String) {
val domainPart = getDomainFromEmailAddress(account.email) ?: error("Couldn't get domain from email address")
initializeIncomingServerSettings(serverType, domainPart)
initializeOutgoingServerSettings(domainPart)
}
private fun initializeIncomingServerSettings(serverType: String, domainPart: String) {
val suggestedStoreServerName = serverNameSuggester.suggestServerName(serverType, domainPart)
val storeServer = ServerSettings(
serverType,
suggestedStoreServerName,
-1,
ConnectionSecurity.SSL_TLS_REQUIRED,
initialAccountSettings.authenticationType,
initialAccountSettings.email,
initialAccountSettings.password,
initialAccountSettings.clientCertificateAlias
)
account.incomingServerSettings = storeServer
}
private fun initializeOutgoingServerSettings(domainPart: String) {
val suggestedTransportServerName = serverNameSuggester.suggestServerName(Protocols.SMTP, domainPart)
val transportServer = ServerSettings(
Protocols.SMTP,
suggestedTransportServerName,
-1,
ConnectionSecurity.STARTTLS_REQUIRED,
initialAccountSettings.authenticationType,
initialAccountSettings.email,
initialAccountSettings.password,
initialAccountSettings.clientCertificateAlias
)
account.outgoingServerSettings = transportServer
}
private fun createSpecialLocalFolders() {
localFoldersCreator.createSpecialLocalFolders(account)
}
private fun returnAccountTypeSelectionResult() {
AccountSetupIncoming.actionIncomingSettings(this, account, makeDefault)
}
companion object {
private const val EXTRA_ACCOUNT = "account"
private const val EXTRA_MAKE_DEFAULT = "makeDefault"
private const val EXTRA_INITIAL_ACCOUNT_SETTINGS = "initialAccountSettings"
@JvmStatic
fun actionSelectAccountType(
context: Context,
account: Account,
makeDefault: Boolean,
initialAccountSettings: InitialAccountSettings
) {
val intent = Intent(context, AccountSetupAccountType::class.java).apply {
putExtra(EXTRA_ACCOUNT, account.uuid)
putExtra(EXTRA_MAKE_DEFAULT, makeDefault)
putExtra(EXTRA_INITIAL_ACCOUNT_SETTINGS, initialAccountSettings)
}
context.startActivity(intent)
}
}
}
| apache-2.0 | a8cdef9760e11f6edf3a55fecea5ecc5 | 37.503817 | 116 | 0.7159 | 5.205366 | false | false | false | false |
unic/sledge | src/main/kotlin/io/sledge/deployer/crx/VaultPropertiesXmlDataExtractor.kt | 1 | 2231 | package io.sledge.deployer.crx
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.MapperFeature
import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule
import com.fasterxml.jackson.dataformat.xml.XmlMapper
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlText
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import java.io.File
import java.io.IOException
import java.util.zip.ZipFile
class VaultPropertiesXmlDataExtractor {
companion object {
const val VLT_PROPERTIES_PATH = "META-INF/vault/properties.xml"
}
val kotlinXmlMapper = XmlMapper(JacksonXmlModule().apply {
setDefaultUseWrapper(false)
}).registerKotlinModule()
.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES, false)
@Throws(IOException::class)
fun getEntryValue(zip: String, entryKeyName: String): String {
val zipFile = ZipFile(File(zip))
val zipEntry = zipFile.getEntry(VLT_PROPERTIES_PATH)
val zipFileInputStream = zipFile.getInputStream(zipEntry)
try {
val propertiesXml = kotlinXmlMapper.readValue(zipFileInputStream, Properties::class.java)
return propertiesXml.entries.find { entry -> entry.key.equals(entryKeyName) }?.value ?: ""
} finally {
zipFile.close()
}
}
@JacksonXmlRootElement(localName = "properties")
data class Properties(
@JacksonXmlElementWrapper(useWrapping = false)
@set:JacksonXmlProperty(localName = "entry")
var entries: List<Entry> = ArrayList()
)
data class Entry(
@set:JacksonXmlProperty(localName = "key", isAttribute = true)
var key: String?) {
@set:JacksonXmlText
lateinit var value: String
}
}
| apache-2.0 | 03c4cef5b1663aa04a61fb7af7afb654 | 38.140351 | 102 | 0.72658 | 4.6 | false | true | false | false |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/component/renderer/HorizontalSliderRenderer.kt | 1 | 1895 | package org.hexworks.zircon.internal.component.renderer
import org.hexworks.zircon.api.component.Slider
import org.hexworks.zircon.api.component.data.ComponentState
import org.hexworks.zircon.api.component.renderer.ComponentRenderContext
import org.hexworks.zircon.api.component.renderer.ComponentRenderer
import org.hexworks.zircon.api.data.Position
import org.hexworks.zircon.api.data.Tile
import org.hexworks.zircon.api.graphics.Symbols
import org.hexworks.zircon.api.graphics.TileGraphics
@Suppress("DuplicatedCode")
class HorizontalSliderRenderer : ComponentRenderer<Slider> {
override fun render(tileGraphics: TileGraphics, context: ComponentRenderContext<Slider>) {
tileGraphics.applyStyle(context.currentStyle)
val defaultStyleSet = context.componentStyle.fetchStyleFor(ComponentState.DEFAULT)
val invertedDefaultStyleSet = defaultStyleSet
.withBackgroundColor(defaultStyleSet.foregroundColor)
.withForegroundColor(defaultStyleSet.backgroundColor)
val disabledStyleSet = context.componentStyle.fetchStyleFor(ComponentState.DISABLED)
val cursorPosition = context.component.currentStep
val barWidth = context.component.numberOfSteps
(0..barWidth).forEach { idx ->
when {
idx == cursorPosition -> tileGraphics.draw(
Tile.createCharacterTile(
Symbols.DOUBLE_LINE_VERTICAL,
context.currentStyle
), Position.create(idx, 0)
)
idx < cursorPosition -> tileGraphics.draw(
Tile.createCharacterTile(' ', invertedDefaultStyleSet),
Position.create(idx, 0)
)
else -> tileGraphics.draw(Tile.createCharacterTile(' ', disabledStyleSet), Position.create(idx, 0))
}
}
}
}
| apache-2.0 | 21ff98e817f9baf5524e5afe63ba3bd5 | 42.068182 | 115 | 0.688127 | 5.135501 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/posts/editor/media/AddLocalMediaToPostUseCase.kt | 1 | 6032 | package org.wordpress.android.ui.posts.editor.media
import android.content.Context
import android.net.Uri
import dagger.Reusable
import org.wordpress.android.fluxc.model.MediaModel
import org.wordpress.android.fluxc.model.MediaModel.MediaUploadState.QUEUED
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.ui.posts.editor.media.CopyMediaToAppStorageUseCase.CopyMediaResult
import org.wordpress.android.ui.posts.editor.media.GetMediaModelUseCase.CreateMediaModelsResult
import org.wordpress.android.ui.posts.editor.media.OptimizeMediaUseCase.OptimizeMediaResult
import org.wordpress.android.util.MediaUtilsWrapper
import javax.inject.Inject
/**
* Processes a list of local media items in the background (optimizing, resizing, rotating, etc.), adds them to
* the editor one at a time and initiates their upload.
*/
@Reusable
class AddLocalMediaToPostUseCase @Inject constructor(
private val copyMediaToAppStorageUseCase: CopyMediaToAppStorageUseCase,
private val optimizeMediaUseCase: OptimizeMediaUseCase,
private val getMediaModelUseCase: GetMediaModelUseCase,
private val updateMediaModelUseCase: UpdateMediaModelUseCase,
private val appendMediaToEditorUseCase: AppendMediaToEditorUseCase,
private val uploadMediaUseCase: UploadMediaUseCase,
private val mediaUtilsWrapper: MediaUtilsWrapper,
private val context: Context
) {
/**
* Adds media items with existing localMediaId to the editor and optionally initiates an upload.
* Does NOT optimize the items.
*/
suspend fun addLocalMediaToEditorAsync(
localMediaIds: List<Int>,
editorMediaListener: EditorMediaListener,
doUploadAfterAdding: Boolean = true
) {
// Add media to editor and optionally initiate upload
addToEditorAndOptionallyUpload(
getMediaModelUseCase.loadMediaByLocalId(localMediaIds),
editorMediaListener,
doUploadAfterAdding
)
}
/**
* Copies files to app storage, optimizes them, adds them to the editor and optionally initiates an upload.
*/
suspend fun addNewMediaToEditorAsync(
uriList: List<Uri>,
site: SiteModel,
freshlyTaken: Boolean,
editorMediaListener: EditorMediaListener,
doUploadAfterAdding: Boolean = true,
trackEvent: Boolean = true
): Boolean {
val allowedUris = uriList.filter {
// filter out long video files on free sites
if (mediaUtilsWrapper.isProhibitedVideoDuration(context, site, it)) {
// put out a notice to the user that the particular video file was rejected
editorMediaListener.showVideoDurationLimitWarning(it.path.toString())
return@filter false
}
return@filter true
}
return processMediaUris(
allowedUris,
site,
freshlyTaken,
editorMediaListener,
doUploadAfterAdding,
trackEvent)
}
private suspend fun processMediaUris(
uriList: List<Uri>,
site: SiteModel,
freshlyTaken: Boolean,
editorMediaListener: EditorMediaListener,
doUploadAfterAdding: Boolean = true,
trackEvent: Boolean = true
): Boolean {
// Copy files to apps storage to make sure they are permanently accessible.
val copyFilesResult: CopyMediaResult = copyMediaToAppStorageUseCase.copyFilesToAppStorageIfNecessary(uriList)
// Optimize and rotate the media
val optimizeMediaResult: OptimizeMediaResult = optimizeMediaUseCase
.optimizeMediaIfSupportedAsync(
site,
freshlyTaken,
copyFilesResult.permanentlyAccessibleUris,
trackEvent
)
// Transform Uris to MediaModels
val createMediaModelsResult: CreateMediaModelsResult = getMediaModelUseCase.createMediaModelFromUri(
site.id,
optimizeMediaResult.optimizedMediaUris
)
// here we pass a map of "old" (before optimisation) Uris to the new MediaModels which contain
// both the mediaModel ids and the optimized media URLs.
// this way, the listener will be able to process from other models pointing to the old URLs
// and make any needed updates
editorMediaListener.onMediaModelsCreatedFromOptimizedUris(
uriList.zip(createMediaModelsResult.mediaModels).toMap()
)
// Add media to editor and optionally initiate upload
addToEditorAndOptionallyUpload(createMediaModelsResult.mediaModels, editorMediaListener, doUploadAfterAdding)
return !optimizeMediaResult.loadingSomeMediaFailed &&
!createMediaModelsResult.loadingSomeMediaFailed &&
!copyFilesResult.copyingSomeMediaFailed
}
private fun addToEditorAndOptionallyUpload(
mediaModels: List<MediaModel>,
editorMediaListener: EditorMediaListener,
doUploadAfterAdding: Boolean
) {
// 1. first, set the Post's data in the mediaModels and set them QUEUED if we want to upload
if (doUploadAfterAdding) {
updateMediaModel(mediaModels, editorMediaListener)
}
// 2. actually append media to the Editor
appendMediaToEditorUseCase.addMediaToEditor(editorMediaListener, mediaModels)
// 3. finally, upload
if (doUploadAfterAdding) {
uploadMediaUseCase.saveQueuedPostAndStartUpload(editorMediaListener, mediaModels)
}
}
private fun updateMediaModel(
mediaModels: List<MediaModel>,
editorMediaListener: EditorMediaListener
) {
mediaModels.forEach {
updateMediaModelUseCase.updateMediaModel(
it,
editorMediaListener.getImmutablePost(),
QUEUED
)
}
}
}
| gpl-2.0 | 32ad38ef82f3166be9da1c2647058698 | 39.213333 | 117 | 0.683521 | 5.674506 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/reader/views/ReaderExpandableTagsView.kt | 1 | 5684 | package org.wordpress.android.ui.reader.views
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewTreeObserver.OnPreDrawListener
import com.google.android.material.chip.Chip
import com.google.android.material.chip.ChipGroup
import org.wordpress.android.R
import org.wordpress.android.WordPress
import org.wordpress.android.analytics.AnalyticsTracker.Stat
import org.wordpress.android.ui.reader.discover.interests.TagUiState
import org.wordpress.android.ui.reader.tracker.ReaderTracker
import org.wordpress.android.ui.utils.UiHelpers
import javax.inject.Inject
class ReaderExpandableTagsView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : ChipGroup(context, attrs, defStyleAttr) {
@Inject lateinit var uiHelpers: UiHelpers
@Inject lateinit var readerTracker: ReaderTracker
private var tagsUiState: List<TagUiState>? = null
private val tagChips
get() = (0 until childCount - 1).map { getChildAt(it) as Chip }
private val overflowIndicatorChip
get() = getChildAt(childCount - 1) as Chip
private val lastVisibleTagChipIndex
get() = tagChips.filter { it.visibility == View.VISIBLE }.lastIndex
private val lastVisibleTagChip
get() = getChildAt(lastVisibleTagChipIndex)
private val hiddenTagChipsCount
get() = tagChips.size - (lastVisibleTagChipIndex + 1)
private val isOverflowIndicatorChipOutsideBounds
get() = !isChipWithinBounds(overflowIndicatorChip)
init {
(context.applicationContext as WordPress).component().inject(this)
layoutDirection = View.LAYOUT_DIRECTION_LOCALE
}
fun updateUi(tagsUiState: List<TagUiState>) {
if (this.tagsUiState != null && this.tagsUiState == tagsUiState) {
return
}
this.tagsUiState = tagsUiState
removeAllViews()
addOverflowIndicatorChip()
addTagChips(tagsUiState)
expandLayout(false)
}
private fun addOverflowIndicatorChip() {
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val chip = inflater.inflate(R.layout.reader_expandable_tags_view_overflow_chip, this, false) as Chip
chip.setOnCheckedChangeListener { _, isChecked ->
readerTracker.track(Stat.READER_CHIPS_MORE_TOGGLED)
expandLayout(isChecked)
}
addView(chip)
}
private fun addTagChips(tagsUiState: List<TagUiState>) {
tagsUiState.forEachIndexed { index, tagUiState ->
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val chip = inflater.inflate(R.layout.reader_expandable_tags_view_chip, this, false) as Chip
chip.tag = tagUiState.slug
chip.text = tagUiState.title
chip.maxWidth = tagUiState.maxWidth
tagUiState.onClick?.let { onClick ->
chip.setOnClickListener {
onClick.invoke(tagUiState.slug)
}
}
addView(chip, index)
}
}
private fun expandLayout(isChecked: Boolean) {
isSingleLine = !isChecked
showAllTagChips()
preLayout {
hideTagChipsOutsideBounds()
updateLastVisibleTagChip()
updateOverflowIndicatorChip()
}
requestLayout()
}
private fun showAllTagChips() {
tagChips.forEach { uiHelpers.updateVisibility(it, true) }
}
private fun hideTagChipsOutsideBounds() {
tagChips.forEach { uiHelpers.updateVisibility(it, isChipWithinBounds(it)) }
}
private fun isChipWithinBounds(chip: Chip) = if (isSingleLine) {
if (layoutDirection == View.LAYOUT_DIRECTION_LTR) {
chip.right <= right - (paddingEnd + chipSpacingHorizontal)
} else {
chip.left >= left + (paddingStart + chipSpacingHorizontal)
}
} else {
chip.bottom <= bottom
}
private fun updateLastVisibleTagChip() {
lastVisibleTagChip?.let {
if (lastVisibleTagChipIndex > 0) {
uiHelpers.updateVisibility(it, !isOverflowIndicatorChipOutsideBounds)
}
}
}
private fun updateOverflowIndicatorChip() {
val showOverflowIndicatorChip = hiddenTagChipsCount > 0 || !isSingleLine
uiHelpers.updateVisibility(overflowIndicatorChip, showOverflowIndicatorChip)
overflowIndicatorChip.contentDescription = String.format(
resources.getString(R.string.show_n_hidden_items_desc),
hiddenTagChipsCount
)
overflowIndicatorChip.text = if (isSingleLine) {
String.format(
resources.getString(R.string.reader_expandable_tags_view_overflow_indicator_expand_title),
hiddenTagChipsCount
)
} else {
resources.getString(R.string.reader_expandable_tags_view_overflow_indicator_collapse_title)
}
val chipBackgroundColorRes = if (isSingleLine) {
R.color.on_surface_chip
} else {
R.color.transparent
}
overflowIndicatorChip.setChipBackgroundColorResource(chipBackgroundColorRes)
}
private fun View.preLayout(what: () -> Unit) {
viewTreeObserver.addOnPreDrawListener(object : OnPreDrawListener {
override fun onPreDraw(): Boolean {
viewTreeObserver.removeOnPreDrawListener(this)
what.invoke()
return true
}
})
}
}
| gpl-2.0 | 44429a8779a09935833ef48cfdf7d369 | 34.748428 | 110 | 0.664321 | 5.021201 | false | false | false | false |
kevinmost/extensions-kotlin | core/src/test/java/com/kevinmost/koolbelt/extension/ListUtilTest.kt | 2 | 1175 | package com.kevinmost.koolbelt.extension
import org.junit.Assert
import org.junit.Assert.assertEquals
import org.junit.Assert.fail
import org.junit.Test
class ListUtilTest {
@Test fun `test setOrAppend() with append`() {
val res = mutableListOf(3, 4, 5).setOrAppend(3, 4)
assertEquals(4, res.size)
assertEquals(4, res[3])
}
@Test fun `test setOrAppend() with set`() {
val res = mutableListOf(3, 4, 5).setOrAppend(0, 2)
assertEquals(2, res[0])
}
@Test fun `test setOrAppend() with really high index throws exception`() {
try {
mutableListOf(3, 4, 5).setOrAppend(400, 6)
fail()
} catch(e: IndexOutOfBoundsException) {
}
}
@Test fun `test operator overload for sublist`() {
val numbers = (1..100).toList()
val sub = numbers[50..52]
Assert.assertEquals(2, sub.size)
Assert.assertEquals(51, sub[0])
Assert.assertEquals(52, sub[1])
val sub2 = numbers[0..0]
Assert.assertTrue(sub2.isEmpty())
val sub3 = numbers[10 downTo 0 step 5]
Assert.assertEquals(3, sub3.size)
Assert.assertEquals(11, sub3[0])
Assert.assertEquals(6, sub3[1])
Assert.assertEquals(1, sub3[2])
}
}
| apache-2.0 | 135266edfb10c19c2ebc9e701114d9b7 | 25.111111 | 76 | 0.660426 | 3.366762 | false | true | false | false |
ingokegel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceUntilWithRangeToIntention.kt | 1 | 1531 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
internal fun KtExpression.getArguments() = when (this) {
is KtBinaryExpression -> this.left to this.right
is KtDotQualifiedExpression -> this.receiverExpression to this.callExpression?.valueArguments?.singleOrNull()?.getArgumentExpression()
else -> null
}
class ReplaceUntilWithRangeToIntention : SelfTargetingIntention<KtExpression>(
KtExpression::class.java,
KotlinBundle.lazyMessage("replace.with.0.operator", "..")
) {
override fun isApplicableTo(element: KtExpression, caretOffset: Int): Boolean {
if (element !is KtBinaryExpression && element !is KtDotQualifiedExpression) return false
val fqName = element.getCallableDescriptor()?.fqNameUnsafe?.asString() ?: return false
return fqName == "kotlin.ranges.until"
}
override fun applyTo(element: KtExpression, editor: Editor?) {
val args = element.getArguments() ?: return
element.replace(KtPsiFactory(element).createExpressionByPattern("$0..$1 - 1", args.first ?: return, args.second ?: return))
}
} | apache-2.0 | 804e9ebe12082ac53ffed8d275a1212a | 48.419355 | 158 | 0.760287 | 4.784375 | false | false | false | false |
ingokegel/intellij-community | platform/workspaceModel/codegen/src/com/intellij/workspaceModel/codegen/writer/classes/SoftLinksCode.kt | 1 | 10913 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.codegen.classes
import com.intellij.workspaceModel.codegen.deft.meta.ObjClass
import com.intellij.workspaceModel.codegen.deft.meta.ObjProperty
import com.intellij.workspaceModel.codegen.deft.meta.ValueType
import com.intellij.workspaceModel.codegen.isRefType
import com.intellij.workspaceModel.codegen.utils.LinesBuilder
import com.intellij.workspaceModel.codegen.utils.fqn
import com.intellij.workspaceModel.codegen.utils.lines
import com.intellij.workspaceModel.codegen.utils.toQualifiedName
import com.intellij.workspaceModel.codegen.writer.allFields
import com.intellij.workspaceModel.storage.PersistentEntityId
import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex
internal fun ObjClass<*>.softLinksCode(context: LinesBuilder, hasSoftLinks: Boolean) {
context.conditionalLine({ hasSoftLinks }, "override fun getLinks(): Set<${PersistentEntityId::class.fqn}<*>>") {
line("val result = HashSet<${PersistentEntityId::class.fqn}<*>>()")
operate(this) { line("result.add($it)") }
line("return result")
}
context.conditionalLine(
{ hasSoftLinks },
"override fun index(index: ${WorkspaceMutableIndex::class.fqn}<${PersistentEntityId::class.fqn}<*>>)"
) {
operate(this) { line("index.index(this, $it)") }
}
context.conditionalLine(
{ hasSoftLinks },
"override fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: ${WorkspaceMutableIndex::class.fqn}<${PersistentEntityId::class.fqn}<*>>)"
) {
line("// TODO verify logic")
line("val mutablePreviousSet = HashSet(prev)")
operate(this) {
line("val removedItem_${it.clean()} = mutablePreviousSet.remove($it)")
section("if (!removedItem_${it.clean()})") {
line("index.index(this, $it)")
}
}
section("for (removed in mutablePreviousSet)") {
line("index.remove(this, removed)")
}
}
context.conditionalLine(
{ hasSoftLinks },
"override fun updateLink(oldLink: ${PersistentEntityId::class.fqn}<*>, newLink: ${PersistentEntityId::class.fqn}<*>): Boolean"
) {
line("var changed = false")
operateUpdateLink(this)
line("return changed")
}
}
internal fun ObjClass<*>.hasSoftLinks(): Boolean {
return fields.noPersistentId().noRefs().any { field ->
field.hasSoftLinks()
}
}
internal fun ObjProperty<*, *>.hasSoftLinks(): Boolean {
if (name == "persistentId") return false
return valueType.hasSoftLinks()
}
internal fun ValueType<*>.hasSoftLinks(): Boolean = when (this) {
is ValueType.Blob -> isPersistentId
is ValueType.Collection<*, *> -> elementType.hasSoftLinks()
is ValueType.Optional<*> -> type.hasSoftLinks()
is ValueType.SealedClass<*> -> isPersistentId || subclasses.any { it.hasSoftLinks() }
is ValueType.DataClass<*> -> isPersistentId || properties.any { it.type.hasSoftLinks() }
else -> false
}
val ValueType.JvmClass<*>.isPersistentId: Boolean
get() = PersistentEntityId::class.java.simpleName in javaSuperClasses || //todo check qualified name only
PersistentEntityId::class.java.name in javaSuperClasses
private fun ObjClass<*>.operate(
context: LinesBuilder,
operation: LinesBuilder.(String) -> Unit
) {
allFields.noPersistentId().noRefs().forEach { field ->
field.valueType.operate(field.name, context, operation)
}
}
private fun ValueType<*>.operate(
varName: String,
context: LinesBuilder,
operation: LinesBuilder.(String) -> Unit,
generateNewName: Boolean = true,
) {
when (this) {
is ValueType.JvmClass -> {
when {
isPersistentId -> context.operation(varName)
this is ValueType.SealedClass<*> -> processSealedClass(this, varName, context, operation, generateNewName)
this is ValueType.DataClass<*> -> processDataClassProperties(varName, context, properties, operation)
}
}
is ValueType.Collection<*, *> -> {
val elementType = elementType
context.section("for (item in ${varName})") {
elementType.operate("item", this@section, operation, false)
}
}
is ValueType.Optional<*> -> {
if (type is ValueType.JvmClass && type.isPersistentId) {
context.line("val optionalLink_${varName.clean()} = $varName")
context.`if`("optionalLink_${varName.clean()} != null") label@{
type.operate("optionalLink_${varName.clean()}", this@label, operation)
}
}
}
else -> Unit
}
}
private fun processDataClassProperties(varName: String,
context: LinesBuilder,
dataClassProperties: List<ValueType.DataClassProperty>,
operation: LinesBuilder.(String) -> Unit) {
for (property in dataClassProperties) {
property.type.operate("$varName.${property.name}", context, operation)
}
}
private fun processSealedClass(thisClass: ValueType.SealedClass<*>,
varName: String,
context: LinesBuilder,
operation: LinesBuilder.(String) -> Unit,
generateNewName: Boolean = true) {
val newVarName = if (generateNewName) "_${varName.clean()}" else varName
if (generateNewName) context.line("val $newVarName = $varName")
context.section("when ($newVarName)") {
listBuilder(thisClass.subclasses) { item ->
val linesBuilder = LinesBuilder(StringBuilder(), context.indentLevel+1, context.indentSize).wrapper()
if (item is ValueType.SealedClass) {
processSealedClass(item, newVarName, linesBuilder, operation, generateNewName)
}
else if (item is ValueType.DataClass) {
processDataClassProperties(newVarName, linesBuilder, item.properties, operation)
}
section("is ${item.javaClassName.toQualifiedName()} -> ") {
result.append(linesBuilder.result)
}
}
}
}
private fun ObjClass<*>.operateUpdateLink(context: LinesBuilder) {
allFields.noPersistentId().noRefs().forEach { field ->
val retType = field.valueType.processType(context, field.name)
if (retType != null) {
context.`if`("$retType != null") {
if (field.valueType is ValueType.Set<*> && !field.valueType.isRefType()) {
line("${field.name} = $retType as MutableSet")
} else if (field.valueType is ValueType.List<*> && !field.valueType.isRefType()) {
line("${field.name} = $retType as MutableList")
} else {
line("${field.name} = $retType")
}
}
}
}
}
private fun ValueType<*>.processType(
context: LinesBuilder,
varName: String,
): String? {
return when (this) {
is ValueType.JvmClass -> {
when {
isPersistentId -> {
val name = "${varName.clean()}_data"
context.lineNoNl("val $name = ")
context.ifElse("$varName == oldLink", {
line("changed = true")
line("newLink as ${javaClassName.toQualifiedName()}")
}) { line("null") }
name
}
this is ValueType.SealedClass<*> -> {
processSealedClass(this, varName, context)
}
this is ValueType.DataClass<*> -> {
val updates = properties.mapNotNull label@{
val retVar = it.type.processType(
context,
"$varName.${it.name}"
)
if (retVar != null) it.name to retVar else null
}
if (updates.isEmpty()) {
null
}
else {
val name = "${varName.clean()}_data"
context.line("var $name = $varName")
updates.forEach { (fieldName, update) ->
context.`if`("$update != null") {
line("$name = $name.copy($fieldName = $update)")
}
}
name
}
}
else -> null
}
}
is ValueType.Collection<*, *> -> {
var name: String? = "${varName.clean()}_data"
val builder = lines(context.indentLevel) {
section("val $name = $varName.map") label@{
val returnVar = elementType.processType(
this@label,
"it"
)
if (returnVar != null) {
ifElse("$returnVar != null", {
line(returnVar)
}) { line("it") }
}
else {
name = null
}
}
}
if (name != null) {
context.result.append(builder)
}
name
}
is ValueType.Optional<*> -> {
var name: String? = "${varName.clean()}_data_optional"
val builder = lines(context.indentLevel) {
lineNoNl("var $name = ")
ifElse("$varName != null", labelIf@{
val returnVar = type.processType(
this@labelIf,
"$varName!!"
)
if (returnVar != null) {
line(returnVar)
}
else {
name = null
}
}) { line("null") }
}
if (name != null) {
context.result.append(builder)
}
name
}
else -> return null
}
}
private fun processSealedClass(thisClass: ValueType.SealedClass<*>,
varName: String,
context: LinesBuilder): String {
val newVarName = "_${varName.clean()}"
val resVarName = "res_${varName.clean()}"
context.line("val $newVarName = $varName")
context.lineNoNl("val $resVarName = ")
context.section("when ($newVarName)") {
listBuilder(thisClass.subclasses) { item ->
section("is ${item.javaClassName.toQualifiedName()} -> ") label@{
var sectionVarName = newVarName
val properties: List<ValueType.DataClassProperty>
if (item is ValueType.SealedClass) {
sectionVarName = processSealedClass(item, sectionVarName, this)
properties = emptyList()
}
else if (item is ValueType.DataClass) {
properties = item.properties
}
else {
properties = emptyList()
}
val updates = properties.mapNotNull {
val retVar = it.type.processType(
this@label,
"$sectionVarName.${it.name}"
)
if (retVar != null) it.name to retVar else null
}
if (updates.isEmpty()) {
line(sectionVarName)
}
else {
val name = "${sectionVarName.clean()}_data"
line("var $name = $sectionVarName")
updates.forEach { (fieldName, update) ->
`if`("$update != null") {
line("$name = $name.copy($fieldName = $update)")
}
}
line(name)
}
}
}
}
return resVarName
}
private fun String.clean(): String {
return this.replace(".", "_").replace('!', '_')
} | apache-2.0 | de16d66e7e85c2f1d47c1dd14227fc95 | 33.429022 | 150 | 0.59901 | 4.622194 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/friends/feed/post/PostViewState.kt | 1 | 2017 | package io.ipoli.android.friends.feed.post
import io.ipoli.android.common.AppState
import io.ipoli.android.common.BaseViewStateReducer
import io.ipoli.android.common.DataLoadedAction
import io.ipoli.android.common.redux.Action
import io.ipoli.android.common.redux.BaseViewState
import io.ipoli.android.friends.feed.data.Post
import io.ipoli.android.friends.feed.post.PostViewState.StateType.DATA_CHANGED
import io.ipoli.android.friends.feed.post.PostViewState.StateType.LOADING
sealed class PostAction : Action {
data class Load(val postId: String) : PostAction()
data class SaveComment(val postId: String, val text: String) : PostAction()
data class Remove(val postId: String) : PostAction()
data class React(val postId: String, val reaction: Post.ReactionType) : PostAction()
}
object PostReducer : BaseViewStateReducer<PostViewState>() {
override val stateKey = key<PostViewState>()
override fun reduce(state: AppState, subState: PostViewState, action: Action) =
when (action) {
is DataLoadedAction.PostChanged -> {
val currentPlayerId = state.dataState.player!!.id
subState.copy(
type = DATA_CHANGED,
post = action.post,
comments = action.post.comments
.sortedBy { it.createdAt.toEpochMilli() },
canDelete = action.post.playerId == currentPlayerId,
currentPlayerId = currentPlayerId
)
}
else -> subState
}
override fun defaultState() = PostViewState(
type = LOADING,
post = null,
comments = emptyList(),
canDelete = false,
currentPlayerId = null
)
}
data class PostViewState(
val type: StateType,
val post: Post?,
val comments: List<Post.Comment>,
val canDelete: Boolean,
val currentPlayerId : String?
) : BaseViewState() {
enum class StateType {
LOADING, DATA_CHANGED
}
} | gpl-3.0 | d0528b3ac7bca52a73a7c940baac238c | 32.633333 | 88 | 0.654437 | 4.658199 | false | false | false | false |
MiJack/ImageDrive | app/src/main/java/cn/mijack/imagedrive/ui/MainActivity.kt | 1 | 7943 | package cn.mijack.imagedrive.ui
import android.app.Activity
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.NavigationView
import android.support.v4.app.Fragment
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AlertDialog
import android.support.v7.widget.Toolbar
import android.view.Gravity
import android.view.Menu
import android.view.MenuItem
import android.view.View
import cn.mijack.imagedrive.R
import cn.mijack.imagedrive.base.BaseActivity
import cn.mijack.imagedrive.componment.NavigationHeaderView
import cn.mijack.imagedrive.fragment.BackUpFragment
import cn.mijack.imagedrive.fragment.ImageDriverFragment
import cn.mijack.imagedrive.fragment.ImageListFragment
import com.google.firebase.auth.FirebaseAuth
/**
* @author Mr.Yuan
* *
* @date 2017/4/16
*/
class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedListener {
private var toolbar: Toolbar? = null
private var drawerLayout: DrawerLayout? = null
private lateinit var actionBarDrawerToggle: ActionBarDrawerToggle
private var headerView: NavigationHeaderView? = null
private lateinit var navigationView: NavigationView
private var firebaseAuth: FirebaseAuth? = null
private var imageListFragment: ImageListFragment? = null
private var imageDriverFragment: ImageDriverFragment? = null
private var currentFragment: Fragment? = null
private var backUpFragment: BackUpFragment? = null
private var dialog: AlertDialog? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
toolbar = findViewById<Toolbar>(R.id.toolbar)
firebaseAuth = FirebaseAuth.getInstance()
drawerLayout = findViewById<DrawerLayout>(R.id.drawerLayout)
navigationView = findViewById<NavigationView>(R.id.navigationView)
headerView = NavigationHeaderView(this, navigationView)
headerView!!.loadLoginInfo()
setSupportActionBar(toolbar)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
actionBarDrawerToggle = ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.content_drawer_open, R.string.content_drawer_close)
drawerLayout!!.addDrawerListener(actionBarDrawerToggle!!)
actionBarDrawerToggle!!.syncState()
switchFragment(IMAGE_LIST_FRAGMENT)
navigationView!!.setNavigationItemSelectedListener({ this.onNavigationItemSelected(it) })
}
private fun switchFragment(fragmentCode: Int) {
val transaction = supportFragmentManager.beginTransaction()
if (currentFragment != null) {
transaction.hide(currentFragment)
}
when (fragmentCode) {
IMAGE_LIST_FRAGMENT -> {
title = getString(R.string.local)
if (imageListFragment == null) {
imageListFragment = ImageListFragment()
transaction.add(R.id.frameLayout, imageListFragment)
} else {
transaction.show(imageListFragment)
}
currentFragment = imageListFragment
}
IMAGE_DRIVER_FRAGMENT -> {
title = getString(R.string.driver)
if (imageDriverFragment == null) {
imageDriverFragment = ImageDriverFragment()
transaction.add(R.id.frameLayout, imageDriverFragment)
} else {
transaction.show(imageDriverFragment)
}
currentFragment = imageDriverFragment
}
BACKUP_FRAGMENT -> {
if (backUpFragment == null) {
backUpFragment = BackUpFragment()
transaction.add(R.id.frameLayout, backUpFragment)
} else {
transaction.show(backUpFragment)
}
currentFragment = backUpFragment
}
}
transaction.commit()
invalidateOptionsMenu()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
menu.setGroupVisible(R.id.actionShow, currentFragment is ImageListFragment)
return true
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
REQUEST_CODE_LOGIN -> {
if (resultCode == Activity.RESULT_CANCELED) {
return
}
if (resultCode == LoginActivity.RESULT_LOGIN) {
headerView!!.loadLoginInfo()
return
}
if (resultCode == LoginActivity.RESULT_NEW_ACCOUNT) {
headerView!!.loadLoginInfo()
}
}
REQUEST_CODE_PROFILE -> headerView!!.loadLoginInfo()
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.actionShowFolder -> imageListFragment!!.showFolder()
R.id.actionShowImages -> imageListFragment!!.showImages()
}
return super.onOptionsItemSelected(item)
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.actionProfile -> {
drawerLayout!!.closeDrawer(Gravity.LEFT)
headerView!!.startProfileActivity()
return true
}
R.id.actionDriver -> {
drawerLayout!!.closeDrawer(Gravity.LEFT)
switchFragment(IMAGE_DRIVER_FRAGMENT)
return true
}
R.id.actionLocal -> {
drawerLayout!!.closeDrawer(Gravity.LEFT)
switchFragment(IMAGE_LIST_FRAGMENT)
return true
}
R.id.actionBackUp -> {
drawerLayout!!.closeDrawer(Gravity.LEFT)
switchFragment(BACKUP_FRAGMENT)
return true
}
R.id.actionAbout -> {
drawerLayout!!.closeDrawer(Gravity.LEFT)
startActivity(Intent(this, AboutActivity::class.java))
return true
}
R.id.actionSettings -> {
drawerLayout!!.closeDrawer(Gravity.LEFT)
startActivity(Intent(this, SettingsActivity::class.java))
return true
}
R.id.actionLogout -> {
drawerLayout!!.closeDrawer(Gravity.LEFT)
if (dialog == null) {
val listener = { dialog: DialogInterface, which: Int ->
if (which == DialogInterface.BUTTON_POSITIVE) {
firebaseAuth!!.signOut()
headerView!!.loadLoginInfo()
}
}
dialog = AlertDialog.Builder(this)
.setTitle(R.string.sign_out)
.setIcon(R.drawable.ic_logout)
.setCancelable(false)
.setPositiveButton(R.string.ok, listener)
.setNegativeButton(R.string.cancel, listener)
.setMessage(R.string.sign_out_message)
.create()
}
dialog!!.show()
return true
}
}
return false
}
companion object {
val REQUEST_CODE_LOGIN = 1
val REQUEST_CODE_PROFILE = 2
private val IMAGE_LIST_FRAGMENT = 1
private val IMAGE_DRIVER_FRAGMENT = 2
private val BACKUP_FRAGMENT = 3
}
}
| apache-2.0 | 1a4922aecd85245a3585ec4ef7b8f0c2 | 38.715 | 143 | 0.597885 | 5.554545 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/avatar/picker/AvatarPickerFragment.kt | 1 | 9716 | package org.thoughtcrime.securesms.avatar.picker
import android.Manifest
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.PopupMenu
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.Fragment
import androidx.fragment.app.setFragmentResult
import androidx.fragment.app.setFragmentResultListener
import androidx.fragment.app.viewModels
import androidx.navigation.Navigation
import androidx.recyclerview.widget.RecyclerView
import org.signal.core.util.ThreadUtil
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.avatar.Avatar
import org.thoughtcrime.securesms.avatar.AvatarBundler
import org.thoughtcrime.securesms.avatar.photo.PhotoEditorFragment
import org.thoughtcrime.securesms.avatar.text.TextAvatarCreationFragment
import org.thoughtcrime.securesms.avatar.vector.VectorAvatarCreationFragment
import org.thoughtcrime.securesms.components.ButtonStripItemView
import org.thoughtcrime.securesms.components.recyclerview.GridDividerDecoration
import org.thoughtcrime.securesms.groups.ParcelableGroupId
import org.thoughtcrime.securesms.mediasend.AvatarSelectionActivity
import org.thoughtcrime.securesms.mediasend.Media
import org.thoughtcrime.securesms.permissions.Permissions
import org.thoughtcrime.securesms.util.ViewUtil
import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter
import org.thoughtcrime.securesms.util.navigation.safeNavigate
import org.thoughtcrime.securesms.util.visible
/**
* Primary Avatar picker fragment, displays current user avatar and a list of recently used avatars and defaults.
*/
class AvatarPickerFragment : Fragment(R.layout.avatar_picker_fragment) {
companion object {
const val REQUEST_KEY_SELECT_AVATAR = "org.thoughtcrime.securesms.avatar.picker.SELECT_AVATAR"
const val SELECT_AVATAR_MEDIA = "org.thoughtcrime.securesms.avatar.picker.SELECT_AVATAR_MEDIA"
const val SELECT_AVATAR_CLEAR = "org.thoughtcrime.securesms.avatar.picker.SELECT_AVATAR_CLEAR"
private const val REQUEST_CODE_SELECT_IMAGE = 1
}
private val viewModel: AvatarPickerViewModel by viewModels(factoryProducer = this::createFactory)
private lateinit var recycler: RecyclerView
private fun createFactory(): AvatarPickerViewModel.Factory {
val args = AvatarPickerFragmentArgs.fromBundle(requireArguments())
val groupId = ParcelableGroupId.get(args.groupId)
return AvatarPickerViewModel.Factory(AvatarPickerRepository(requireContext()), groupId, args.isNewGroup, args.groupAvatarMedia)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val toolbar: Toolbar = view.findViewById(R.id.avatar_picker_toolbar)
val cameraButton: ButtonStripItemView = view.findViewById(R.id.avatar_picker_camera)
val photoButton: ButtonStripItemView = view.findViewById(R.id.avatar_picker_photo)
val textButton: ButtonStripItemView = view.findViewById(R.id.avatar_picker_text)
val saveButton: View = view.findViewById(R.id.avatar_picker_save)
val clearButton: View = view.findViewById(R.id.avatar_picker_clear)
recycler = view.findViewById(R.id.avatar_picker_recycler)
recycler.addItemDecoration(GridDividerDecoration(4, ViewUtil.dpToPx(16)))
val adapter = MappingAdapter()
AvatarPickerItem.register(adapter, this::onAvatarClick, this::onAvatarLongClick)
recycler.adapter = adapter
val avatarViewHolder = AvatarPickerItem.ViewHolder(view)
viewModel.state.observe(viewLifecycleOwner) { state ->
if (state.currentAvatar != null) {
avatarViewHolder.bind(AvatarPickerItem.Model(state.currentAvatar, false))
}
clearButton.visible = state.canClear
val wasEnabled = saveButton.isEnabled
saveButton.isEnabled = state.canSave
if (wasEnabled != state.canSave) {
val alpha = if (state.canSave) 1f else 0.5f
saveButton.animate().cancel()
saveButton.animate().alpha(alpha)
}
val items = state.selectableAvatars.map { AvatarPickerItem.Model(it, it == state.currentAvatar) }
val selectedPosition = items.indexOfFirst { it.isSelected }
adapter.submitList(items) {
if (selectedPosition > -1)
recycler.smoothScrollToPosition(selectedPosition)
}
}
toolbar.setNavigationOnClickListener { Navigation.findNavController(it).popBackStack() }
cameraButton.setOnIconClickedListener { openCameraCapture() }
photoButton.setOnIconClickedListener { openGallery() }
textButton.setOnIconClickedListener { openTextEditor(null) }
saveButton.setOnClickListener { v ->
viewModel.save(
{
setFragmentResult(
REQUEST_KEY_SELECT_AVATAR,
Bundle().apply {
putParcelable(SELECT_AVATAR_MEDIA, it)
}
)
ThreadUtil.runOnMain { Navigation.findNavController(v).popBackStack() }
},
{
setFragmentResult(
REQUEST_KEY_SELECT_AVATAR,
Bundle().apply {
putBoolean(SELECT_AVATAR_CLEAR, true)
}
)
ThreadUtil.runOnMain { Navigation.findNavController(v).popBackStack() }
}
)
}
clearButton.setOnClickListener { viewModel.clear() }
setFragmentResultListener(TextAvatarCreationFragment.REQUEST_KEY_TEXT) { _, bundle ->
val text = AvatarBundler.extractText(bundle)
viewModel.onAvatarEditCompleted(text)
}
setFragmentResultListener(VectorAvatarCreationFragment.REQUEST_KEY_VECTOR) { _, bundle ->
val vector = AvatarBundler.extractVector(bundle)
viewModel.onAvatarEditCompleted(vector)
}
setFragmentResultListener(PhotoEditorFragment.REQUEST_KEY_EDIT) { _, bundle ->
val photo = AvatarBundler.extractPhoto(bundle)
viewModel.onAvatarEditCompleted(photo)
}
}
override fun onResume() {
super.onResume()
ViewUtil.hideKeyboard(requireContext(), requireView())
}
@Suppress("DEPRECATION")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_CODE_SELECT_IMAGE && resultCode == Activity.RESULT_OK && data != null) {
val media: Media = requireNotNull(data.getParcelableExtra(AvatarSelectionActivity.EXTRA_MEDIA))
viewModel.onAvatarPhotoSelectionCompleted(media)
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
private fun onAvatarClick(avatar: Avatar, isSelected: Boolean) {
if (isSelected) {
openEditor(avatar)
} else {
viewModel.onAvatarSelectedFromGrid(avatar)
}
}
private fun onAvatarLongClick(anchorView: View, avatar: Avatar): Boolean {
val menuRes = when (avatar) {
is Avatar.Photo -> R.menu.avatar_picker_context
is Avatar.Text -> R.menu.avatar_picker_context
is Avatar.Vector -> return true
is Avatar.Resource -> return true
}
val popup = PopupMenu(context, anchorView, Gravity.TOP)
popup.menuInflater.inflate(menuRes, popup.menu)
popup.setOnMenuItemClickListener { menuItem ->
when (menuItem.itemId) {
R.id.action_delete -> viewModel.delete(avatar)
}
true
}
popup.show()
return true
}
fun openEditor(avatar: Avatar) {
when (avatar) {
is Avatar.Photo -> openPhotoEditor(avatar)
is Avatar.Resource -> throw UnsupportedOperationException()
is Avatar.Text -> openTextEditor(avatar)
is Avatar.Vector -> openVectorEditor(avatar)
}
}
private fun openPhotoEditor(photo: Avatar.Photo) {
Navigation.findNavController(requireView())
.safeNavigate(AvatarPickerFragmentDirections.actionAvatarPickerFragmentToAvatarPhotoEditorFragment(AvatarBundler.bundlePhoto(photo)))
}
private fun openVectorEditor(vector: Avatar.Vector) {
Navigation.findNavController(requireView())
.safeNavigate(AvatarPickerFragmentDirections.actionAvatarPickerFragmentToVectorAvatarCreationFragment(AvatarBundler.bundleVector(vector)))
}
private fun openTextEditor(text: Avatar.Text?) {
val bundle = if (text != null) AvatarBundler.bundleText(text) else null
Navigation.findNavController(requireView())
.safeNavigate(AvatarPickerFragmentDirections.actionAvatarPickerFragmentToTextAvatarCreationFragment(bundle))
}
@Suppress("DEPRECATION")
private fun openCameraCapture() {
Permissions.with(this)
.request(Manifest.permission.CAMERA)
.ifNecessary()
.onAllGranted {
val intent = AvatarSelectionActivity.getIntentForCameraCapture(requireContext())
startActivityForResult(intent, REQUEST_CODE_SELECT_IMAGE)
}
.onAnyDenied {
Toast.makeText(requireContext(), R.string.AvatarSelectionBottomSheetDialogFragment__taking_a_photo_requires_the_camera_permission, Toast.LENGTH_SHORT)
.show()
}
.execute()
}
@Suppress("DEPRECATION")
private fun openGallery() {
Permissions.with(this)
.request(Manifest.permission.READ_EXTERNAL_STORAGE)
.ifNecessary()
.onAllGranted {
val intent = AvatarSelectionActivity.getIntentForGallery(requireContext())
startActivityForResult(intent, REQUEST_CODE_SELECT_IMAGE)
}
.onAnyDenied {
Toast.makeText(requireContext(), R.string.AvatarSelectionBottomSheetDialogFragment__viewing_your_gallery_requires_the_storage_permission, Toast.LENGTH_SHORT)
.show()
}
.execute()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
Permissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults)
}
}
| gpl-3.0 | 135df610529f24574725e00ad03982f9 | 37.709163 | 165 | 0.742384 | 4.872618 | false | false | false | false |
jk1/intellij-community | uast/uast-java/src/org/jetbrains/uast/java/JavaAbstractUElement.kt | 4 | 5281 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.java
import com.intellij.psi.*
import org.jetbrains.uast.*
import org.jetbrains.uast.java.expressions.JavaUExpressionList
import org.jetbrains.uast.java.internal.JavaUElementWithComments
import org.jetbrains.uast.java.kinds.JavaSpecialExpressionKinds
abstract class JavaAbstractUElement(givenParent: UElement?) : JavaUElementWithComments, JvmDeclarationUElement {
@Suppress("unused") // Used in Kotlin 1.2, to be removed in 2018.1
@Deprecated("use JavaAbstractUElement(givenParent)", ReplaceWith("JavaAbstractUElement(givenParent)"))
constructor() : this(null)
override fun equals(other: Any?): Boolean {
if (other !is UElement || other.javaClass != this.javaClass) return false
return if (this.psi != null) this.psi == other.psi else this === other
}
override fun hashCode(): Int = psi?.hashCode() ?: System.identityHashCode(this)
override fun asSourceString(): String {
return this.psi?.text ?: super<JavaUElementWithComments>.asSourceString()
}
override fun toString(): String = asRenderString()
override val uastParent: UElement? by lz { givenParent ?: convertParent() }
protected open fun convertParent(): UElement? =
getPsiParentForLazyConversion()
?.let { JavaConverter.unwrapElements(it).toUElement() }
?.let { unwrapSwitch(it) }
?.also {
if (it === this) throw IllegalStateException("lazy parent loop for $this")
if (it.psi != null && it.psi === this.psi)
throw IllegalStateException("lazy parent loop: psi ${this.psi}(${this.psi?.javaClass}) for $this of ${this.javaClass}")
}
protected open fun getPsiParentForLazyConversion(): PsiElement? = this.psi?.parent
//explicitly overridden in abstract class to be binary compatible with Kotlin
override val comments: List<UComment>
get() = super<JavaUElementWithComments>.comments
override val sourcePsi: PsiElement?
get() = super<JavaUElementWithComments>.sourcePsi
override val javaPsi: PsiElement?
get() = super<JavaUElementWithComments>.javaPsi
}
private fun JavaAbstractUElement.unwrapSwitch(uParent: UElement): UElement {
when (uParent) {
is JavaUCodeBlockExpression -> {
val codeBlockParent = uParent.uastParent
if (codeBlockParent is JavaUExpressionList && codeBlockParent.kind == JavaSpecialExpressionKinds.SWITCH) {
if (branchHasElement(psi, codeBlockParent.psi) { it is PsiSwitchLabelStatement }) {
return codeBlockParent
}
val uSwitchExpression = codeBlockParent.uastParent as? JavaUSwitchExpression ?: return uParent
val psiElement = psi ?: return uParent
return findUSwitchClauseBody(uSwitchExpression, psiElement) ?: return codeBlockParent
}
if (codeBlockParent is JavaUSwitchExpression) {
return unwrapSwitch(codeBlockParent)
}
return uParent
}
is USwitchExpression -> {
val parentPsi = uParent.psi as PsiSwitchStatement
return if (this === uParent.body || branchHasElement(psi, parentPsi) { it === parentPsi.expression })
uParent
else
uParent.body
}
else -> return uParent
}
}
private inline fun branchHasElement(child: PsiElement?, parent: PsiElement?, predicate: (PsiElement) -> Boolean): Boolean {
var current: PsiElement? = child;
while (current != null && current != parent) {
if (predicate(current)) return true
current = current.parent
}
return false
}
abstract class JavaAbstractUExpression(givenParent: UElement?) : JavaAbstractUElement(givenParent), UExpression {
@Suppress("unused") // Used in Kotlin 1.2, to be removed in 2018.1
@Deprecated("use JavaAbstractUExpression(givenParent)", ReplaceWith("JavaAbstractUExpression(givenParent)"))
constructor() : this(null)
override fun evaluate(): Any? {
val project = psi?.project ?: return null
return JavaPsiFacade.getInstance(project).constantEvaluationHelper.computeConstantExpression(psi)
}
override val annotations: List<UAnnotation>
get() = emptyList()
override fun getExpressionType(): PsiType? {
val expression = psi as? PsiExpression ?: return null
return expression.type
}
override fun getPsiParentForLazyConversion(): PsiElement? = super.getPsiParentForLazyConversion()?.let {
when (it) {
is PsiResourceExpression -> it.parent
is PsiReferenceExpression -> (it.parent as? PsiMethodCallExpression) ?: it
else -> it
}
}
override fun convertParent(): UElement? = super.convertParent().let { uParent ->
when (uParent) {
is UAnonymousClass -> uParent.uastParent
else -> uParent
}
}.let(this::unwrapCompositeQualifiedReference)
}
| apache-2.0 | fbf40ad79dd0f6073109e5a42bbe44fc | 36.721429 | 129 | 0.71975 | 4.862799 | false | false | false | false |
evanchooly/kobalt | modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/maven/aether/ConsoleTransferListener.kt | 1 | 4226 | package com.beust.kobalt.maven.aether
import com.beust.kobalt.misc.KobaltLogger
import com.beust.kobalt.misc.log
import org.eclipse.aether.transfer.AbstractTransferListener
import org.eclipse.aether.transfer.MetadataNotFoundException
import org.eclipse.aether.transfer.TransferEvent
import org.eclipse.aether.transfer.TransferResource
import java.io.PrintStream
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.util.*
import java.util.concurrent.ConcurrentHashMap
class ConsoleTransferListener @JvmOverloads constructor(out: PrintStream? = null) : AbstractTransferListener() {
private val out: PrintStream
private val downloads = ConcurrentHashMap<TransferResource, Long>()
private var lastLength: Int = 0
init {
this.out = out ?: System.out
}
override fun transferInitiated(event: TransferEvent?) {
val message = if (event!!.requestType == TransferEvent.RequestType.PUT) "Uploading" else "Downloading"
log(2, message + ": " + event.resource.repositoryUrl + event.resource.resourceName)
}
override fun transferProgressed(event: TransferEvent?) {
val resource = event!!.resource
downloads.put(resource, java.lang.Long.valueOf(event.transferredBytes))
val buffer = StringBuilder(64)
for (entry in downloads.entries) {
val total = entry.key.contentLength
val complete = entry.value.toLong()
buffer.append(getStatus(complete, total)).append(" ")
}
val pad = lastLength - buffer.length
lastLength = buffer.length
pad(buffer, pad)
buffer.append('\r')
out.print(buffer)
}
private fun getStatus(complete: Long, total: Long): String {
if (total >= 1024) {
return toKB(complete).toString() + "/" + toKB(total) + " KB "
} else if (total >= 0) {
return complete.toString() + "/" + total + " B "
} else if (complete >= 1024) {
return toKB(complete).toString() + " KB "
} else {
return complete.toString() + " B "
}
}
private fun pad(buffer: StringBuilder, spaces: Int) {
var spaces = spaces
val block = " "
while (spaces > 0) {
val n = Math.min(spaces, block.length)
buffer.append(block, 0, n)
spaces -= n
}
}
override fun transferSucceeded(event: TransferEvent) {
transferCompleted(event)
val resource = event.resource
val contentLength = event.transferredBytes
if (contentLength >= 0) {
val type = if (event.requestType == TransferEvent.RequestType.PUT) "Uploaded" else "Downloaded"
val len = if (contentLength >= 1024) toKB(contentLength).toString() + " KB"
else contentLength.toString() + " B"
var throughput = ""
val duration = System.currentTimeMillis() - resource.transferStartTime
if (duration > 0) {
val bytes = contentLength - resource.resumeOffset
val format = DecimalFormat("0.0", DecimalFormatSymbols(Locale.ENGLISH))
val kbPerSec = bytes / 1024.0 / (duration / 1000.0)
throughput = " at " + format.format(kbPerSec) + " KB/sec"
}
log(2, type + ": " + resource.repositoryUrl + resource.resourceName + " (" + len
+ throughput + ")")
}
}
override fun transferFailed(event: TransferEvent) {
transferCompleted(event)
if (event.exception !is MetadataNotFoundException) {
if (KobaltLogger.LOG_LEVEL > 1) {
event.exception.printStackTrace(out)
}
}
}
private fun transferCompleted(event: TransferEvent) {
downloads.remove(event.resource)
val buffer = StringBuilder(64)
pad(buffer, lastLength)
buffer.append('\r')
out.print(buffer)
}
override fun transferCorrupted(event: TransferEvent?) {
event!!.exception.printStackTrace(out)
}
protected fun toKB(bytes: Long): Long {
return (bytes + 1023) / 1024
}
}
| apache-2.0 | 62d93924f2552825e80e17c7c58460bc | 32.015625 | 112 | 0.61169 | 4.578548 | false | false | false | false |
abertschi/ad-free | app/src/main/java/ch/abertschi/adfree/crashhandler/SendCrashReportActivity.kt | 1 | 4174 | package ch.abertschi.adfree.crashhandler
import android.content.Context
import android.graphics.Typeface
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.text.Html
import android.view.View
import android.widget.TextView
import ch.abertschi.adfree.R
import android.widget.Toast
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.warn
import java.io.File
import java.lang.Exception
import android.content.Intent
import org.jetbrains.anko.info
// TODO: refator this into presenter and view
class SendCrashReportActivity : AppCompatActivity(), View.OnClickListener, AnkoLogger {
companion object {
val ACTION_NAME = "ch.abertschi.adfree.SEND_LOG_CRASH"
val EXTRA_LOGFILE = "ch.abertschi.adfree.extra.logfile"
val EXTRA_SUMMARY = "ch.abertschi.adfree.extra.summary"
val MAIL_ADDR = "[email protected]"
val SUBJECT = "[ad-free-crash-report]"
}
private var logfile: String? = null
private var summary: String? = null
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
try {
parseIntent(this.intent)
doOnCreate()
} catch (e: Exception) {
warn(e)
Toast.makeText(this, "Error: $e", Toast.LENGTH_LONG).show()
}
}
fun parseIntent(i: Intent?) {
logfile = i?.extras?.getString(EXTRA_LOGFILE)
summary = i?.extras?.getString(EXTRA_SUMMARY) ?: ""
}
fun sendReport() {
try {
val file = File(applicationContext.filesDir, logfile)
val log = file.readText()
info { "sending report with $file $log" }
launchSendIntent(summary!!)
} catch (e: Exception) {
warn { e }
}
}
private fun launchSendIntent(msg: String) {
val sendIntent = Intent(Intent.ACTION_SEND)
sendIntent.putExtra(Intent.EXTRA_EMAIL, arrayOf(MAIL_ADDR))
sendIntent.putExtra(Intent.EXTRA_TEXT, msg)
sendIntent.putExtra(Intent.EXTRA_SUBJECT, SUBJECT)
sendIntent.type = "text/plain"
this.applicationContext
.startActivity(Intent.createChooser(sendIntent, "Choose an Email client"))
}
private fun doOnCreate() {
setupUI()
}
// TODO: Send logcat output and summary
private fun setupUI() {
setContentView(R.layout.crash_view)
setFinishOnTouchOutside(false)
val v = findViewById(R.id.crash_container) as View
v.setOnClickListener(this)
var typeFace: Typeface = Typeface.createFromAsset(baseContext.assets, "fonts/Raleway-ExtraLight.ttf")
val title = findViewById(R.id.crash_Title) as TextView
title.typeface = typeFace
title.setOnClickListener(this)
val text =
"success is not final, failure is not fatal: it is the " +
"<font color=#FFFFFF>courage</font> to <font color=#FFFFFF>continue</font> that counts. -- " +
"Winston Churchill"
title?.text = Html.fromHtml(text)
val subtitle = findViewById(R.id.debugSubtitle) as TextView
subtitle.typeface = typeFace
subtitle.setOnClickListener(this)
val subtitletext =
"<font color=#FFFFFF>ad-free</font> crashed. be courageous and continue. " +
"send the <font color=#FFFFFF>crash report </font>. tab here, choose your mail application and send the report.</font>"
subtitle.text = Html.fromHtml(subtitletext)
}
override fun onClick(v: View) {
info { "clicking view for crashreport" }
logfile?.let {
try {
sendReport()
} catch (e: Exception) {
warn { "cant send crash report" }
warn { e }
e.printStackTrace()
Toast.makeText(this, "No crash report available.",
Toast.LENGTH_LONG).show()
}
} ?: run {
Toast.makeText(this, "No crash report available.",
Toast.LENGTH_LONG).show()
}
}
} | apache-2.0 | c50ca3788e1da82e58fbbcf3134246ab | 31.115385 | 143 | 0.617393 | 4.389064 | false | false | false | false |
binaryroot/AndroidArchitecture | app/src/main/java/com/androidarchitecture/data/auth/AuthRestJsonInterceptor.kt | 1 | 947 | package com.androidarchitecture.data.auth
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException
import javax.inject.Inject
class AuthRestJsonInterceptor @Inject
constructor(private val mAuthorizationService: AuthorizationService) : Interceptor {
companion object {
private val CONTENT_TYPE_JSON = "application/json; charset=utf-8"
}
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val original = chain.request()
// Customize the request
val builder = original.newBuilder()
.header("CONTENT_TYPE", CONTENT_TYPE_JSON)
val token = mAuthorizationService.mTokenStore.userToken
if (token != null) {
builder.header("AUTHORIZATION", token.accessToken)
}
val request = builder.build()
// Customize or return the response
return chain.proceed(request)
}
}
| mit | f1921c8c9a85879323f9b5df856780bc | 27.69697 | 84 | 0.687434 | 4.758794 | false | false | false | false |
marklemay/IntelliJATS | src/main/kotlin/com/atslangplugin/ATSSyntaxHighlighter.kt | 1 | 16418 | package com.atslangplugin
//TODO: static import these
import com.atslangplugin.psi.ATSTokenTypes
import com.intellij.lexer.FlexAdapter
import com.intellij.lexer.Lexer
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors.*
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase
import com.intellij.psi.tree.IElementType
import java.util.*
class ATSSyntaxHighlighter : SyntaxHighlighterBase() {
companion object {
// this interface seems like it could be more concise, see MakefileSyntaxHighlighter.kt
val ATS_BLOCK_COMMENT = createTextAttributesKey("BLOCK_COMMENT", BLOCK_COMMENT)
val ATS_BRACES = createTextAttributesKey("BRACES", BRACES)
val ATS_BRACKETS = createTextAttributesKey("BRACKETS", BRACKETS)
val ATS_COMMA = createTextAttributesKey("COMMA", COMMA)
val ATS_DIRECTIVES = createTextAttributesKey("DIRECTIVES", PREDEFINED_SYMBOL)
val ATS_DOC_COMMENT = createTextAttributesKey("DOC_COMMENT", DOC_COMMENT)
val ATS_EXTERNAL_CODE = createTextAttributesKey("EXTERNAL_CODE", TEMPLATE_LANGUAGE_COLOR)
val ATS_FUNCTION_CALL = createTextAttributesKey("FUNCTION_CALL", FUNCTION_CALL)
val ATS_IDENTIFIER = createTextAttributesKey("IDENTIFIER", IDENTIFIER)
val ATS_LINE_COMMENT = createTextAttributesKey("LINE_COMMENT", LINE_COMMENT)
val ATS_KEYWORD = createTextAttributesKey("KEYWORD", KEYWORD)
val ATS_LOCAL_VARIABLE = createTextAttributesKey("LOCAL_VARIABLE", LOCAL_VARIABLE)
val ATS_NUMBER = createTextAttributesKey("NUMBER", NUMBER)
val ATS_OPERATION_SIGN = createTextAttributesKey("OPERATION_SIGN", OPERATION_SIGN)
val ATS_PARENTHESES = createTextAttributesKey("PARENTHESES", PARENTHESES)
val ATS_REST_COMMENT = createTextAttributesKey("REST_COMMENT", BLOCK_COMMENT)
val ATS_SEMICOLON = createTextAttributesKey("SEMICOLON", SEMICOLON)
val ATS_STRING = createTextAttributesKey("STRING", STRING)
val ATS_TYPE_DECLARATIONS = createTextAttributesKey("TYPE_DECLARATIONS", KEYWORD)
val ATS_VAL_DECLARATIONS = createTextAttributesKey("VAL_DECLARATIONS", INSTANCE_FIELD)
val ATS_INVALID_STRING_ESCAPE = createTextAttributesKey("INVALID_STRING_ESCAPE", INVALID_STRING_ESCAPE)
val ATS_VALID_STRING_ESCAPE = createTextAttributesKey("VALID_STRING_ESCAPE", VALID_STRING_ESCAPE)
private val EMPTY_KEYS = emptyArray<TextAttributesKey>()
private val ATS_BLOCK_COMMENT_KEYS = arrayOf(ATS_BLOCK_COMMENT)
private val ATS_BRACES_KEYS = arrayOf(ATS_BRACES)
private val ATS_BRACKETS_KEYS = arrayOf(ATS_BRACKETS)
private val ATS_COMMA_KEYS = arrayOf(ATS_COMMA)
private val ATS_DOC_COMMENT_KEYS = arrayOf(ATS_DOC_COMMENT)
private val ATS_DIRECTIVES_KEYS = arrayOf(ATS_DIRECTIVES)
private val ATS_EXTERNAL_CODE_KEYS = arrayOf(ATS_EXTERNAL_CODE)
private val ATS_FUNCTION_CALL_KEYS = arrayOf(ATS_FUNCTION_CALL)
private val ATS_IDENTIFIER_KEYS = arrayOf(ATS_IDENTIFIER)
private val ATS_LINE_COMMENT_KEYS = arrayOf(ATS_LINE_COMMENT)
private val ATS_KEYWORD_KEYS = arrayOf(ATS_KEYWORD)
private val ATS_LOCAL_VARIABLE_KEYS = arrayOf(ATS_LOCAL_VARIABLE)
private val ATS_NUMBER_KEYS = arrayOf(ATS_NUMBER)
private val ATS_OPERATION_SIGN_KEYS = arrayOf(ATS_OPERATION_SIGN)
private val ATS_PARENTHESES_KEYS = arrayOf(ATS_PARENTHESES)
private val ATS_REST_COMMENT_KEYS = arrayOf(ATS_REST_COMMENT)
private val ATS_SEMICOLON_KEYS = arrayOf(ATS_SEMICOLON)
private val ATS_STRING_KEYS = arrayOf(ATS_STRING)
private val ATS_TYPE_DECLARATIONS_KEYS = arrayOf(ATS_TYPE_DECLARATIONS)
private val ATS_VAL_DECLARATIONS_KEYS = arrayOf(ATS_VAL_DECLARATIONS)
private val tokenColorMap: Map<IElementType, Array<TextAttributesKey>>
//TODO: bake this into the function so it is more concise and readable
init {
val tmpMap = HashMap<IElementType, Array<TextAttributesKey>>()
tmpMap.put(ATSTokenTypes.ABSTYPE, ATS_TYPE_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.ADDRAT, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.AND, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.AS, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.ASSUME, ATS_TYPE_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.AT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.ATLBRACE, ATS_BRACES_KEYS)
tmpMap.put(ATSTokenTypes.ATLPAREN, ATS_BRACES_KEYS)
tmpMap.put(ATSTokenTypes.BACKSLASH, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.BANG, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.BAR, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.BEGIN, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.BQUOTE, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.CASE, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.CHAR, ATS_STRING_KEYS)
tmpMap.put(ATSTokenTypes.CLASSDEC, ATS_TYPE_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.COLON, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.COLONLT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.COMMA, ATS_COMMA_KEYS)
tmpMap.put(ATSTokenTypes.COMMALPAREN, ATS_PARENTHESES_KEYS)
tmpMap.put(ATSTokenTypes.COMMENT_BLOCK, ATS_BLOCK_COMMENT_KEYS)
tmpMap.put(ATSTokenTypes.COMMENT_DOC, ATS_DOC_COMMENT_KEYS)
tmpMap.put(ATSTokenTypes.COMMENT_LINE, ATS_LINE_COMMENT_KEYS)
tmpMap.put(ATSTokenTypes.COMMENT_REST, ATS_REST_COMMENT_KEYS)
// Do not want to color CRLF
tmpMap.put(ATSTokenTypes.DATASORT, ATS_TYPE_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.DLRARRPSZ, ATS_TYPE_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.DLRBREAK, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLRCONTINUE, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLRDELAY, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLREFFMASK, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLREFFMASK_ARG, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.DLREXTERN, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLREXTFCALL, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLREXTVAL, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLREXTYPE, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLREXTYPE_STRUCT, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLRLST, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLRMYFILENAME, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLRMYFILENAME, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLRMYLOCATION, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLRRAISE, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLRREC, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLRSHOWTYPE, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLRTUP, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLRTEMPENVER, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DLRVCOPYENV, ATS_FUNCTION_CALL_KEYS)
tmpMap.put(ATSTokenTypes.DO, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.DOLLAR, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.DOT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.DOTDOT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.DOTDOTDOT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.DOTINT, ATS_OPERATION_SIGN_KEYS) // what is it?
tmpMap.put(ATSTokenTypes.DOTLT, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.DOTLTGTDOT, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.SRPDYNLOAD, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.ELSE, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.END, ATS_KEYWORD_KEYS)
// don't color EOF
tmpMap.put(ATSTokenTypes.EQ, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.EQGT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.EQGTGT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.EQLT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.EQLTGT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.EQSLASHEQGT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.EQSLASHEQGTGT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.EXCEPTION, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.EXTCODE_CLOSE, ATS_BRACES_KEYS)
tmpMap.put(ATSTokenTypes.EXTERN, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.EXTVAR, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.FIX, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.FIXITY, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.FLOAT, ATS_NUMBER_KEYS)
tmpMap.put(ATSTokenTypes.FOLDAT, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.FORSTAR, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.FREEAT, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.FUN, ATS_VAL_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.GT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.GTDOT, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.GTLT, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.HASH, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.HASHLBRACKETOLON, ATS_BRACKETS_KEYS)
tmpMap.put(ATSTokenTypes.IDENTIFIER, ATS_IDENTIFIER_KEYS)
tmpMap.put(ATSTokenTypes.IF, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.IMPLEMENT, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.IMPORT, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.IN, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.INT, ATS_NUMBER_KEYS)
tmpMap.put(ATSTokenTypes.LAM, ATS_TYPE_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.LBRACE, ATS_BRACES_KEYS)
tmpMap.put(ATSTokenTypes.LBRACKET, ATS_BRACKETS_KEYS)
tmpMap.put(ATSTokenTypes.LET, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.LOCAL, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.LPAREN, ATS_PARENTHESES_KEYS)
tmpMap.put(ATSTokenTypes.LT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.MACDEF, ATS_VAL_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.MINUSGT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.MINUSLT, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.MINUSLTGT, ATS_KEYWORD_KEYS)
// NONE isn't used here
tmpMap.put(ATSTokenTypes.NONFIX, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.OF, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.OP, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.OVERLOAD, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.PERCENT, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.PERCENTLPAREN, ATS_PARENTHESES_KEYS)
tmpMap.put(ATSTokenTypes.QMARK, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.QUOTELBRACE, ATS_BRACES_KEYS)
tmpMap.put(ATSTokenTypes.QUOTELBRACKET, ATS_BRACKETS_KEYS)
tmpMap.put(ATSTokenTypes.QUOTELPAREN, ATS_PARENTHESES_KEYS)
tmpMap.put(ATSTokenTypes.RBRACE, ATS_BRACES_KEYS)
tmpMap.put(ATSTokenTypes.RBRACKET, ATS_BRACES_KEYS)
tmpMap.put(ATSTokenTypes.REC, ATS_TYPE_DECLARATIONS_KEYS) // recursive
tmpMap.put(ATSTokenTypes.REFAT, ATS_FUNCTION_CALL_KEYS) // CHECK_ME
tmpMap.put(ATSTokenTypes.REF_IDENTIFIER, ATS_IDENTIFIER_KEYS)
tmpMap.put(ATSTokenTypes.REQUIRE, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.RPAREN, ATS_PARENTHESES_KEYS)
tmpMap.put(ATSTokenTypes.SCASE, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.SEMICOLON, ATS_SEMICOLON_KEYS)
tmpMap.put(ATSTokenTypes.SIF, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.SORTDEF, ATS_TYPE_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.SRPASSERT, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.SRPDEFINE, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.SRPELIF, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.SRPELIFDEF, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.SRPELIFNDEF, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.SRPELSE, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.SRPENDIF, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.SRPERROR, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.SRPIF, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.SRPIFDEF, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.SRPIFNDEF, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.SRPINCLUDE, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.SRPPRINT, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.SRPTHEN, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.SRPUNDEF, ATS_DIRECTIVES_KEYS)
tmpMap.put(ATSTokenTypes.STACST, ATS_VAL_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.STADEF, ATS_TYPE_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.SRPSTALOAD, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.STATIC, ATS_TYPE_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.STRING, ATS_STRING_KEYS)
tmpMap.put(ATSTokenTypes.SYMELIM, ATS_VAL_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.SYMINTR, ATS_VAL_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.THEN, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.TILDE, ATS_OPERATION_SIGN_KEYS)
tmpMap.put(ATSTokenTypes.TKINDEF, ATS_VAL_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.TRY, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.TYPE, ATS_TYPE_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.TYPEDEF, ATS_TYPE_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.VAL, ATS_VAL_DECLARATIONS_KEYS)
tmpMap.put(ATSTokenTypes.VAL_IDENTIFIER, ATS_IDENTIFIER_KEYS)
tmpMap.put(ATSTokenTypes.VIEWAT, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.WHEN, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.WHERE, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.WHILE, ATS_KEYWORD_KEYS)
// do not color WHITESPACE
tmpMap.put(ATSTokenTypes.WHILESTAR, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.WITH, ATS_KEYWORD_KEYS)
tmpMap.put(ATSTokenTypes.WITHTYPE, ATS_KEYWORD_KEYS)
tokenColorMap = tmpMap
}
}
override fun getTokenHighlights(tokenType: IElementType) = when (tokenType) {
// MakefileTypes.DOC_COMMENT -> DOCCOMMENT_KEYS
// MakefileTypes.COMMENT -> COMMENT_KEYS
// MakefileTypes.TARGET -> TARGET_KEYS
// MakefileTypes.COLON, MakefileTypes.DOUBLECOLON, MakefileTypes.ASSIGN, MakefileTypes.SEMICOLON, MakefileTypes.PIPE -> SEPARATOR_KEYS
// MakefileTypes.KEYWORD_INCLUDE, MakefileTypes.KEYWORD_IFEQ, MakefileTypes.KEYWORD_IFNEQ, MakefileTypes.KEYWORD_IFDEF, MakefileTypes.KEYWORD_IFNDEF, MakefileTypes.KEYWORD_ELSE, MakefileTypes.KEYWORD_ENDIF, MakefileTypes.KEYWORD_DEFINE, MakefileTypes.KEYWORD_ENDEF, MakefileTypes.KEYWORD_UNDEFINE, MakefileTypes.KEYWORD_OVERRIDE, MakefileTypes.KEYWORD_EXPORT, MakefileTypes.KEYWORD_PRIVATE, MakefileTypes.KEYWORD_VPATH -> KEYWORD_KEYS
// MakefileTypes.PREREQUISITE -> PREREQUISITE_KEYS
// MakefileTypes.VARIABLE -> VARIABLE_KEYS
// MakefileTypes.VARIABLE_VALUE -> VARIABLE_VALUE_KEYS
// MakefileTypes.SPLIT -> LINE_SPLIT_KEYS
// MakefileTypes.TAB -> TAB_KEYS
// TokenType.BAD_CHARACTER -> BAD_CHAR_KEYS
ATSTokenTypes.EXTCODE -> ATS_EXTERNAL_CODE_KEYS
ATSTokenTypes.DATATYPE -> ATS_TYPE_DECLARATIONS_KEYS
else -> tokenColorMap.getOrDefault(tokenType,EMPTY_KEYS) //TODO: remove the map in favor of the cleaner syntax
}
override fun getHighlightingLexer(): Lexer {
return FlexAdapter(ATSLexer(null))
}
}
| gpl-3.0 | 116d4ac3ad359a3d3dd3d8ec4820f1c7 | 61.904215 | 441 | 0.698563 | 4.25778 | false | false | false | false |
ClearVolume/scenery | src/main/kotlin/graphics/scenery/backends/vulkan/VulkanTexture.kt | 1 | 51210 | package graphics.scenery.backends.vulkan
import graphics.scenery.textures.Texture
import graphics.scenery.textures.Texture.BorderColor
import graphics.scenery.textures.UpdatableTexture.TextureExtents
import graphics.scenery.textures.Texture.RepeatMode
import graphics.scenery.textures.UpdatableTexture
import graphics.scenery.textures.UpdatableTexture.TextureUpdate
import graphics.scenery.utils.Image
import graphics.scenery.utils.LazyLogger
import net.imglib2.type.numeric.NumericType
import net.imglib2.type.numeric.integer.*
import net.imglib2.type.numeric.real.DoubleType
import net.imglib2.type.numeric.real.FloatType
import org.lwjgl.system.MemoryStack.stackPush
import org.lwjgl.system.MemoryUtil.*
import org.lwjgl.vulkan.*
import org.lwjgl.vulkan.VK10.*
import org.lwjgl.vulkan.VkImageCreateInfo
import java.awt.color.ColorSpace
import java.awt.image.*
import java.io.FileInputStream
import java.io.InputStream
import java.nio.ByteBuffer
import java.nio.file.Files
import java.nio.file.Paths
import kotlin.math.max
import kotlin.math.roundToLong
import kotlin.streams.toList
/**
* Vulkan Texture class. Creates a texture on the [device], with [width]x[height]x[depth],
* of [format], with a given number of [mipLevels]. Filtering can be set via
* [minFilterLinear] and [maxFilterLinear]. Needs to be supplied with a [queue] to execute
* generic operations on, and a [transferQueue] for transfer operations. Both are allowed to
* be the same.
*
* @author Ulrik Günther <[email protected]>
*/
open class VulkanTexture(val device: VulkanDevice,
val commandPools: VulkanRenderer.CommandPools, val queue: VkQueue, val transferQueue: VkQueue,
val width: Int, val height: Int, val depth: Int = 1,
val format: Int = VK_FORMAT_R8G8B8_SRGB, var mipLevels: Int = 1,
val minFilterLinear: Boolean = true, val maxFilterLinear: Boolean = true,
val usage: HashSet<Texture.UsageType> = hashSetOf(Texture.UsageType.Texture)) : AutoCloseable {
//protected val logger by LazyLogger()
private var initialised: Boolean = false
/** The Vulkan image associated with this texture. */
var image: VulkanImage
protected set
private var stagingImage: VulkanImage
private var gt: Texture? = null
var renderBarrier: VkImageMemoryBarrier? = null
protected set
/**
* Wrapper class for holding on to raw Vulkan [image]s backed by [memory].
*/
inner class VulkanImage(var image: Long = -1L, var memory: Long = -1L, val maxSize: Long = -1L) {
/** Raw Vulkan sampler. */
var sampler: Long = -1L
internal set
/** Raw Vulkan view. */
var view: Long = -1L
internal set
/**
* Copies the content of the image from [buffer]. This gets executed
* within a given [commandBuffer].
*/
fun copyFrom(commandBuffer: VkCommandBuffer, buffer: VulkanBuffer, update: TextureUpdate? = null, bufferOffset: Long = 0) {
with(commandBuffer) {
val bufferImageCopy = VkBufferImageCopy.calloc(1)
bufferImageCopy.imageSubresource()
.aspectMask(VK_IMAGE_ASPECT_COLOR_BIT)
.mipLevel(0)
.baseArrayLayer(0)
.layerCount(1)
bufferImageCopy.bufferOffset(bufferOffset)
if(update != null) {
bufferImageCopy.imageExtent().set(update.extents.w, update.extents.h, update.extents.d)
bufferImageCopy.imageOffset().set(update.extents.x, update.extents.y, update.extents.z)
} else {
bufferImageCopy.imageExtent().set(width, height, depth)
bufferImageCopy.imageOffset().set(0, 0, 0)
}
vkCmdCopyBufferToImage(this,
buffer.vulkanBuffer,
[email protected], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
bufferImageCopy)
bufferImageCopy.free()
}
update?.let {
it.consumed = true
}
}
/**
* Copies the content of the image to [buffer] from a series of [updates]. This gets executed
* within a given [commandBuffer].
*/
fun copyFrom(commandBuffer: VkCommandBuffer, buffer: VulkanBuffer, updates: List<TextureUpdate>, bufferOffset: Long = 0) {
logger.debug("Got {} texture updates for {}", updates.size, this)
with(commandBuffer) {
val bufferImageCopy = VkBufferImageCopy.calloc(1)
var offset = bufferOffset
updates.forEach { update ->
val updateSize = update.contents.remaining()
bufferImageCopy.imageSubresource()
.aspectMask(VK_IMAGE_ASPECT_COLOR_BIT)
.mipLevel(0)
.baseArrayLayer(0)
.layerCount(1)
bufferImageCopy.bufferOffset(offset)
bufferImageCopy.imageExtent().set(update.extents.w, update.extents.h, update.extents.d)
bufferImageCopy.imageOffset().set(update.extents.x, update.extents.y, update.extents.z)
vkCmdCopyBufferToImage(this,
buffer.vulkanBuffer,
[email protected], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
bufferImageCopy)
offset += updateSize
update.consumed = true
}
bufferImageCopy.free()
}
}
/**
* Copies the content of the image from a given [VulkanImage], [image].
* This gets executed within a given [commandBuffer].
*/
fun copyFrom(commandBuffer: VkCommandBuffer, image: VulkanImage, extents: TextureExtents? = null) {
with(commandBuffer) {
val subresource = VkImageSubresourceLayers.calloc()
.aspectMask(VK_IMAGE_ASPECT_COLOR_BIT)
.baseArrayLayer(0)
.mipLevel(0)
.layerCount(1)
val region = VkImageCopy.calloc(1)
.srcSubresource(subresource)
.dstSubresource(subresource)
if(extents != null) {
region.srcOffset().set(extents.x, extents.y, extents.z)
region.dstOffset().set(extents.x, extents.y, extents.z)
region.extent().set(extents.w, extents.h, extents.d)
} else {
region.srcOffset().set(0, 0, 0)
region.dstOffset().set(0, 0, 0)
region.extent().set(width, height, depth)
}
vkCmdCopyImage(this,
image.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
[email protected], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
region)
subresource.free()
region.free()
}
}
override fun toString(): String {
return "VulkanImage (${this.image.toHexString()}, ${width}x${height}x${depth}, format=$format, maxSize=${this.maxSize})"
}
}
init {
stagingImage = if(depth == 1) {
createImage(width, height, depth,
format, VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
VK_IMAGE_TILING_LINEAR,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT or VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
mipLevels = 1
)
} else {
createImage(16, 16, 1,
format, VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
VK_IMAGE_TILING_LINEAR,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT or VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
mipLevels = 1)
}
var usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT or VK_IMAGE_USAGE_SAMPLED_BIT or VK_IMAGE_USAGE_TRANSFER_SRC_BIT
if(device.formatFeatureSupported(format, VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT, optimalTiling = true)) {
usage = usage or VK_IMAGE_USAGE_STORAGE_BIT
}
image = createImage(width, height, depth,
format, usage,
VK_IMAGE_TILING_OPTIMAL, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
mipLevels)
if (image.sampler == -1L) {
image.sampler = createSampler()
}
if (image.view == -1L) {
image.view = createImageView(image, format)
}
gt?.let { cache.put(it, this) }
}
/**
* Alternative constructor to create a [VulkanTexture] from a [Texture].
*/
constructor(device: VulkanDevice,
commandPools: VulkanRenderer.CommandPools, queue: VkQueue, transferQueue: VkQueue,
texture: Texture, mipLevels: Int = 1) : this(device,
commandPools,
queue,
transferQueue,
texture.dimensions.x().toInt(),
texture.dimensions.y().toInt(),
texture.dimensions.z().toInt(),
texture.toVulkanFormat(),
mipLevels, texture.minFilter == Texture.FilteringMode.Linear, texture.maxFilter == Texture.FilteringMode.Linear, usage = texture.usageType) {
gt = texture
gt?.let { cache.put(it, this) }
}
/**
* Creates a Vulkan image of [format] with a given [width], [height], and [depth].
* [usage] and [memoryFlags] need to be given, as well as the [tiling] parameter and number of [mipLevels].
* A custom memory allocator may be used and given as [customAllocator].
*/
fun createImage(width: Int, height: Int, depth: Int, format: Int,
usage: Int, tiling: Int, memoryFlags: Int, mipLevels: Int,
initialLayout: Int? = null,
customAllocator: ((VkMemoryRequirements, Long) -> Long)? = null, imageCreateInfo: VkImageCreateInfo? = null): VulkanImage {
val imageInfo = if(imageCreateInfo != null) {
imageCreateInfo
} else {
val i = VkImageCreateInfo.calloc()
.sType(VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO)
.imageType(if (depth == 1) {
VK_IMAGE_TYPE_2D
} else {
VK_IMAGE_TYPE_3D
})
.mipLevels(mipLevels)
.arrayLayers(1)
.format(format)
.tiling(tiling)
.initialLayout(if(depth == 1) {VK_IMAGE_LAYOUT_PREINITIALIZED} else { VK_IMAGE_LAYOUT_UNDEFINED })
.usage(usage)
.sharingMode(VK_SHARING_MODE_EXCLUSIVE)
.samples(VK_SAMPLE_COUNT_1_BIT)
.flags(VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)
i.extent().set(width, height, depth)
i
}
if(initialLayout != null) {
imageInfo.initialLayout(initialLayout)
}
val image = VU.getLong("create staging image",
{ vkCreateImage(device.vulkanDevice, imageInfo, null, this) }, {})
val reqs = VkMemoryRequirements.calloc()
vkGetImageMemoryRequirements(device.vulkanDevice, image, reqs)
val memorySize = reqs.size()
val memory = if(customAllocator == null) {
val allocInfo = VkMemoryAllocateInfo.calloc()
.sType(VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO)
.pNext(NULL)
.allocationSize(memorySize)
.memoryTypeIndex(device.getMemoryType(reqs.memoryTypeBits(), memoryFlags).first())
VU.getLong("allocate image staging memory of size $memorySize",
{ vkAllocateMemory(device.vulkanDevice, allocInfo, null, this) },
{ imageInfo.free(); allocInfo.free() })
} else {
customAllocator.invoke(reqs, image)
}
reqs.free()
vkBindImageMemory(device.vulkanDevice, image, memory, 0)
return VulkanImage(image, memory, memorySize)
}
var tmpBuffer: VulkanBuffer? = null
/**
* Copies the data for this texture from a [ByteBuffer], [data].
*/
fun copyFrom(data: ByteBuffer): VulkanTexture {
if (depth == 1 && data.remaining() > stagingImage.maxSize) {
logger.warn("Allocated image size for $this (${stagingImage.maxSize}) less than copy source size ${data.remaining()}.")
return this
}
var deallocate = false
var sourceBuffer = data
gt?.let { gt ->
if (gt.channels == 3) {
logger.debug("Loading RGB texture, padding channels to 4 to fit RGBA")
val pixelByteSize = when (gt.type) {
is UnsignedByteType -> 1
is ByteType -> 1
is UnsignedShortType -> 2
is ShortType -> 2
is UnsignedIntType -> 4
is IntType -> 4
is FloatType -> 4
is DoubleType -> 8
else -> throw UnsupportedOperationException("Don't know how to handle textures of type ${gt.type.javaClass.simpleName}")
}
val storage = memAlloc(data.remaining() / 3 * 4)
val view = data.duplicate()
val tmp = ByteArray(pixelByteSize * 3)
val alpha = (0 until pixelByteSize).map { 255.toByte() }.toByteArray()
// pad buffer to 4 channels
while (view.hasRemaining()) {
view.get(tmp, 0, 3)
storage.put(tmp)
storage.put(alpha)
}
storage.flip()
deallocate = true
sourceBuffer = storage
} else {
deallocate = false
sourceBuffer = data
}
}
logger.debug("Updating {} with {} miplevels", this, mipLevels)
if (mipLevels == 1) {
with(VU.newCommandBuffer(device, commandPools.Standard, autostart = true)) {
if(!initialised) {
transitionLayout(stagingImage.image,
VK_IMAGE_LAYOUT_PREINITIALIZED,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, mipLevels,
srcStage = VK_PIPELINE_STAGE_HOST_BIT,
dstStage = VK_PIPELINE_STAGE_TRANSFER_BIT,
commandBuffer = this)
}
if (depth == 1) {
val dest = memAllocPointer(1)
vkMapMemory(device, stagingImage.memory, 0, sourceBuffer.remaining() * 1L, 0, dest)
memCopy(memAddress(sourceBuffer), dest.get(0), sourceBuffer.remaining().toLong())
vkUnmapMemory(device, stagingImage.memory)
memFree(dest)
transitionLayout(image.image,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, mipLevels,
srcStage = VK_PIPELINE_STAGE_HOST_BIT,
dstStage = VK_PIPELINE_STAGE_TRANSFER_BIT,
commandBuffer = this)
image.copyFrom(this, stagingImage)
transitionLayout(image.image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, mipLevels,
srcStage = VK_PIPELINE_STAGE_TRANSFER_BIT,
dstStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
commandBuffer = this)
} else {
val genericTexture = gt
val requiredCapacity = if(genericTexture is UpdatableTexture && genericTexture.hasConsumableUpdates()) {
genericTexture.getConsumableUpdates().map { it.contents.remaining() }.sum().toLong()
} else {
sourceBuffer.capacity().toLong()
}
logger.debug("{} has {} consumeable updates", this@VulkanTexture, (genericTexture as? UpdatableTexture)?.getConsumableUpdates()?.size)
if(tmpBuffer == null || (tmpBuffer?.size ?: 0) < requiredCapacity) {
logger.debug("(${this@VulkanTexture}) Reallocating tmp buffer, old size=${tmpBuffer?.size} new size = ${requiredCapacity.toFloat()/1024.0f/1024.0f} MiB")
tmpBuffer?.close()
// reserve a bit more space if the texture is small, to avoid reallocations
val reservedSize = if(requiredCapacity < 1024*1024*8) {
(requiredCapacity * 1.33).roundToLong()
} else {
requiredCapacity
}
tmpBuffer = VulkanBuffer([email protected],
max(reservedSize, 1024*1024),
VK_BUFFER_USAGE_TRANSFER_SRC_BIT or VK_BUFFER_USAGE_TRANSFER_DST_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT or VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
wantAligned = false)
}
tmpBuffer?.let { buffer ->
transitionLayout(image.image,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, mipLevels,
srcStage = VK_PIPELINE_STAGE_HOST_BIT,
dstStage = VK_PIPELINE_STAGE_TRANSFER_BIT,
commandBuffer = this)
if(genericTexture is UpdatableTexture) {
if(genericTexture.hasConsumableUpdates()) {
val contents = genericTexture.getConsumableUpdates().map { it.contents }
buffer.copyFrom(contents, keepMapped = true)
image.copyFrom(this, buffer, genericTexture.getConsumableUpdates())
genericTexture.clearConsumedUpdates()
} /*else {
// TODO: Semantics, do we want UpdateableTextures to be only
// updateable via updates, or shall they read from buffer on first init?
buffer.copyFrom(sourceBuffer)
image.copyFrom(this, buffer)
}*/
} else {
buffer.copyFrom(sourceBuffer)
image.copyFrom(this, buffer)
}
transitionLayout(image.image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, mipLevels,
srcStage = VK_PIPELINE_STAGE_TRANSFER_BIT,
dstStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
commandBuffer = this)
}
}
endCommandBuffer([email protected], commandPools.Standard, transferQueue, flush = true, dealloc = true, block = true)
}
} else {
val buffer = VulkanBuffer(device,
sourceBuffer.limit().toLong(),
VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
wantAligned = false)
with(VU.newCommandBuffer(device, commandPools.Standard, autostart = true)) {
buffer.copyFrom(sourceBuffer)
transitionLayout(image.image, VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, commandBuffer = this,
srcStage = VK_PIPELINE_STAGE_HOST_BIT,
dstStage = VK_PIPELINE_STAGE_TRANSFER_BIT)
image.copyFrom(this, buffer)
transitionLayout(image.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, 1, commandBuffer = this,
srcStage = VK_PIPELINE_STAGE_TRANSFER_BIT,
dstStage = VK_PIPELINE_STAGE_TRANSFER_BIT)
endCommandBuffer([email protected], commandPools.Standard, transferQueue, flush = true, dealloc = true, block = true)
}
val imageBlit = VkImageBlit.calloc(1)
with(VU.newCommandBuffer(device, commandPools.Standard, autostart = true)) mipmapCreation@{
for (mipLevel in 1 until mipLevels) {
imageBlit.srcSubresource().set(VK_IMAGE_ASPECT_COLOR_BIT, mipLevel - 1, 0, 1)
imageBlit.srcOffsets(1).set(width shr (mipLevel - 1), height shr (mipLevel - 1), 1)
val dstWidth = width shr mipLevel
val dstHeight = height shr mipLevel
if (dstWidth < 2 || dstHeight < 2) {
break
}
imageBlit.dstSubresource().set(VK_IMAGE_ASPECT_COLOR_BIT, mipLevel, 0, 1)
imageBlit.dstOffsets(1).set(width shr (mipLevel), height shr (mipLevel), 1)
val mipSourceRange = VkImageSubresourceRange.calloc()
.aspectMask(VK_IMAGE_ASPECT_COLOR_BIT)
.baseArrayLayer(0)
.layerCount(1)
.baseMipLevel(mipLevel - 1)
.levelCount(1)
val mipTargetRange = VkImageSubresourceRange.calloc()
.aspectMask(VK_IMAGE_ASPECT_COLOR_BIT)
.baseArrayLayer(0)
.layerCount(1)
.baseMipLevel(mipLevel)
.levelCount(1)
if (mipLevel > 1) {
transitionLayout(image.image,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
subresourceRange = mipSourceRange,
srcStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
dstStage = VK_PIPELINE_STAGE_TRANSFER_BIT,
commandBuffer = this@mipmapCreation)
}
transitionLayout(image.image,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
subresourceRange = mipTargetRange,
srcStage = VK_PIPELINE_STAGE_HOST_BIT,
dstStage = VK_PIPELINE_STAGE_TRANSFER_BIT,
commandBuffer = this@mipmapCreation)
vkCmdBlitImage(this@mipmapCreation,
image.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
image.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
imageBlit, VK_FILTER_LINEAR)
transitionLayout(image.image,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresourceRange = mipSourceRange,
srcStage = VK_PIPELINE_STAGE_TRANSFER_BIT,
dstStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
commandBuffer = this@mipmapCreation)
transitionLayout(image.image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresourceRange = mipTargetRange,
srcStage = VK_PIPELINE_STAGE_TRANSFER_BIT,
dstStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
commandBuffer = this@mipmapCreation)
mipSourceRange.free()
mipTargetRange.free()
}
[email protected]([email protected], commandPools.Standard, queue, flush = true, dealloc = true)
}
imageBlit.free()
buffer.close()
}
// deallocate in case we moved pixels around
if (deallocate) {
memFree(sourceBuffer)
}
// image.view = createImageView(image, format)
initialised = true
return this
}
/**
* Copies the first layer, first mipmap of the texture to [buffer].
*/
fun copyTo(buffer: ByteBuffer) {
if(tmpBuffer == null || (tmpBuffer != null && tmpBuffer?.size!! < image.maxSize)) {
tmpBuffer?.close()
tmpBuffer = VulkanBuffer([email protected],
image.maxSize,
VK_BUFFER_USAGE_TRANSFER_SRC_BIT or VK_BUFFER_USAGE_TRANSFER_DST_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT or VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
wantAligned = false)
}
tmpBuffer?.let { b ->
with(VU.newCommandBuffer(device, commandPools.Standard, autostart = true)) {
transitionLayout(image.image,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, 1,
srcStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
dstStage = VK_PIPELINE_STAGE_TRANSFER_BIT,
commandBuffer = this)
val type = VK_IMAGE_ASPECT_COLOR_BIT
val subresource = VkImageSubresourceLayers.calloc()
.aspectMask(type)
.mipLevel(0)
.baseArrayLayer(0)
.layerCount(1)
val regions = VkBufferImageCopy.calloc(1)
.bufferRowLength(0)
.bufferImageHeight(0)
.imageOffset(VkOffset3D.calloc().set(0, 0, 0))
.imageExtent(VkExtent3D.calloc().set(width, height, depth))
.imageSubresource(subresource)
vkCmdCopyImageToBuffer(
this,
image.image,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
b.vulkanBuffer,
regions
)
transitionLayout(image.image,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, 1,
srcStage = VK_PIPELINE_STAGE_TRANSFER_BIT,
dstStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
commandBuffer = this)
endCommandBuffer([email protected], commandPools.Standard, transferQueue, flush = true, dealloc = true, block = true)
}
b.copyTo(buffer)
}
}
/**
* Creates a Vulkan image view with [format] for an [image].
*/
fun createImageView(image: VulkanImage, format: Int): Long {
if(image.view != -1L) {
vkDestroyImageView(device.vulkanDevice, image.view, null)
}
val subresourceRange = VkImageSubresourceRange.calloc().set(VK_IMAGE_ASPECT_COLOR_BIT, 0, mipLevels, 0, 1)
val vi = VkImageViewCreateInfo.calloc()
.sType(VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO)
.pNext(NULL)
.image(image.image)
.viewType(if (depth > 1) {
VK_IMAGE_VIEW_TYPE_3D
} else {
VK_IMAGE_VIEW_TYPE_2D
})
.format(format)
.subresourceRange(subresourceRange)
if(gt?.channels == 1 && depth > 1) {
vi.components().set(VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_R)
}
return VU.getLong("Creating image view",
{ vkCreateImageView(device.vulkanDevice, vi, null, this) },
{ vi.free(); subresourceRange.free(); })
}
private fun RepeatMode.toVulkan(): Int {
return when(this) {
RepeatMode.Repeat -> VK_SAMPLER_ADDRESS_MODE_REPEAT
RepeatMode.MirroredRepeat -> VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT
RepeatMode.ClampToEdge -> VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE
RepeatMode.ClampToBorder -> VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER
}
}
private fun BorderColor.toVulkan(type: NumericType<*>): Int {
var color = when(this) {
BorderColor.TransparentBlack -> VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK
BorderColor.OpaqueBlack -> VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK
BorderColor.OpaqueWhite -> VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE
}
if(type !is FloatType) {
color += 1
}
return color
}
/**
* Creates a default sampler for this texture.
*/
fun createSampler(texture: Texture? = null): Long {
val t = texture ?: gt
val (repeatS, repeatT, repeatU) = if(t != null) {
Triple(
t.repeatUVW.first.toVulkan(),
t.repeatUVW.second.toVulkan(),
t.repeatUVW.third.toVulkan()
)
} else {
if(depth == 1) {
Triple(VK_SAMPLER_ADDRESS_MODE_REPEAT, VK_SAMPLER_ADDRESS_MODE_REPEAT, VK_SAMPLER_ADDRESS_MODE_REPEAT)
} else {
Triple(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE)
}
}
val samplerInfo = VkSamplerCreateInfo.calloc()
.sType(VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO)
.pNext(NULL)
.magFilter(if(minFilterLinear) { VK_FILTER_LINEAR } else { VK_FILTER_NEAREST })
.minFilter(if(maxFilterLinear) { VK_FILTER_LINEAR } else { VK_FILTER_NEAREST })
.mipmapMode(if(depth == 1) { VK_SAMPLER_MIPMAP_MODE_LINEAR } else { VK_SAMPLER_MIPMAP_MODE_NEAREST })
.addressModeU(repeatS)
.addressModeV(repeatT)
.addressModeW(repeatU)
.mipLodBias(0.0f)
.anisotropyEnable(depth == 1)
.maxAnisotropy(if(depth == 1) { 8.0f } else { 1.0f })
.minLod(0.0f)
.maxLod(if(depth == 1) {mipLevels * 1.0f} else { 0.0f })
.borderColor(VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE)
.compareOp(VK_COMPARE_OP_NEVER)
if(t != null) {
samplerInfo.borderColor(t.borderColor.toVulkan(t.type))
}
val sampler = VU.getLong("creating sampler",
{ vkCreateSampler(device.vulkanDevice, samplerInfo, null, this) },
{ samplerInfo.free() })
logger.debug("Created sampler {}", sampler.toHexString().toLowerCase())
val oldSampler = image.sampler
image.sampler = sampler
if(oldSampler != -1L) {
vkDestroySampler(device.vulkanDevice, oldSampler, null)
}
return sampler
}
override fun toString(): String {
return "VulkanTexture on $device (${this.image.image.toHexString()}, ${width}x${height}x$depth, format=${this.format}, mipLevels=${mipLevels}, gt=${this.gt != null} minFilter=${this.minFilterLinear} maxFilter=${this.maxFilterLinear})"
}
/**
* Deallocates and destroys this [VulkanTexture] instance, freeing all memory
* related to it.
*/
override fun close() {
gt?.let { cache.remove(it) }
if (image.view != -1L) {
vkDestroyImageView(device.vulkanDevice, image.view, null)
image.view = -1L
}
if (image.image != -1L) {
vkDestroyImage(device.vulkanDevice, image.image, null)
image.image = -1L
}
if (image.sampler != -1L) {
vkDestroySampler(device.vulkanDevice, image.sampler, null)
image.sampler = -1L
}
if (image.memory != -1L) {
vkFreeMemory(device.vulkanDevice, image.memory, null)
image.memory = -1L
}
if (stagingImage.image != -1L) {
vkDestroyImage(device.vulkanDevice, stagingImage.image, null)
stagingImage.image = -1L
}
if (stagingImage.memory != -1L) {
vkFreeMemory(device.vulkanDevice, stagingImage.memory, null)
stagingImage.memory = -1L
}
tmpBuffer?.close()
}
/**
* Utility methods for [VulkanTexture].
*/
companion object {
@JvmStatic private val logger by LazyLogger()
private val cache = HashMap<Texture, VulkanTexture>()
private val StandardAlphaColorModel = ComponentColorModel(
ColorSpace.getInstance(ColorSpace.CS_sRGB),
intArrayOf(8, 8, 8, 8),
true,
false,
ComponentColorModel.TRANSLUCENT,
DataBuffer.TYPE_BYTE)
private val StandardColorModel = ComponentColorModel(
ColorSpace.getInstance(ColorSpace.CS_sRGB),
intArrayOf(8, 8, 8, 0),
false,
false,
ComponentColorModel.OPAQUE,
DataBuffer.TYPE_BYTE)
fun getReference(texture: Texture): VulkanTexture? {
return cache.get(texture)
}
/**
* Loads a texture from a file given by [filename], and allocates the [VulkanTexture] on [device].
*/
fun loadFromFile(device: VulkanDevice,
commandPools: VulkanRenderer.CommandPools , queue: VkQueue, transferQueue: VkQueue,
filename: String,
linearMin: Boolean, linearMax: Boolean,
generateMipmaps: Boolean = true): VulkanTexture {
val stream = FileInputStream(filename)
val type = filename.substringAfterLast('.')
logger.debug("Loading${if(generateMipmaps) { " mipmapped" } else { "" }} texture from $filename")
return if(type == "raw") {
val path = Paths.get(filename)
val infoFile = path.resolveSibling(path.fileName.toString().substringBeforeLast(".") + ".info")
val dimensions = Files.lines(infoFile).toList().first().split(",").map { it.toLong() }.toLongArray()
loadFromFileRaw(device,
commandPools, queue, transferQueue,
stream, type, dimensions)
} else {
loadFromFile(device,
commandPools, queue, transferQueue,
stream, type, linearMin, linearMax, generateMipmaps)
}
}
/**
* Loads a texture from a file given by a [stream], and allocates the [VulkanTexture] on [device].
*/
fun loadFromFile(device: VulkanDevice,
commandPools: VulkanRenderer.CommandPools, queue: VkQueue, transferQueue: VkQueue,
stream: InputStream, type: String,
linearMin: Boolean, linearMax: Boolean,
generateMipmaps: Boolean = true): VulkanTexture {
val image = Image.fromStream(stream, type, true)
var texWidth = 2
var texHeight = 2
var levelsW = 1
var levelsH = 1
while (texWidth < image.width) {
texWidth *= 2
levelsW++
}
while (texHeight < image.height) {
texHeight *= 2
levelsH++
}
val mipmapLevels = if(generateMipmaps) {
Math.min(levelsW, levelsH)
} else {
1
}
val tex = VulkanTexture(
device,
commandPools, queue, transferQueue,
texWidth, texHeight, 1,
VK_FORMAT_R8G8B8A8_SRGB,
mipmapLevels,
linearMin, linearMax)
tex.copyFrom(image.contents)
return tex
}
/**
* Loads a texture from a raw file given by a [stream], and allocates the [VulkanTexture] on [device].
*/
@Suppress("UNUSED_PARAMETER")
fun loadFromFileRaw(device: VulkanDevice,
commandPools: VulkanRenderer.CommandPools, queue: VkQueue, transferQueue: VkQueue,
stream: InputStream, type: String, dimensions: LongArray): VulkanTexture {
val imageData: ByteBuffer = ByteBuffer.allocateDirect((2 * dimensions[0] * dimensions[1] * dimensions[2]).toInt())
val buffer = ByteArray(1024*1024)
var bytesRead = stream.read(buffer)
while(bytesRead > -1) {
imageData.put(buffer)
bytesRead = stream.read(buffer)
}
val tex = VulkanTexture(
device,
commandPools, queue, transferQueue,
dimensions[0].toInt(), dimensions[1].toInt(), dimensions[2].toInt(),
VK_FORMAT_R16_UINT, 1, true, true)
tex.copyFrom(imageData)
stream.close()
return tex
}
/**
* Transitions Vulkan image layouts, with [srcAccessMask] and [dstAccessMask] explicitly specified.
*/
fun transitionLayout(image: Long, from: Int, to: Int, mipLevels: Int = 1,
subresourceRange: VkImageSubresourceRange? = null,
srcStage: Int = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, dstStage: Int = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
srcAccessMask: Int, dstAccessMask: Int,
commandBuffer: VkCommandBuffer, dependencyFlags: Int = 0, memoryBarrier: Boolean = false) {
stackPush().use { stack ->
val barrier = VkImageMemoryBarrier.callocStack(1, stack)
.sType(VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER)
.pNext(NULL)
.oldLayout(from)
.newLayout(to)
.srcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.dstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.srcAccessMask(srcAccessMask)
.dstAccessMask(dstAccessMask)
.image(image)
if (subresourceRange == null) {
barrier.subresourceRange()
.aspectMask(VK_IMAGE_ASPECT_COLOR_BIT)
.baseMipLevel(0)
.levelCount(mipLevels)
.baseArrayLayer(0)
.layerCount(1)
} else {
barrier.subresourceRange(subresourceRange)
}
logger.trace("Transition: {} -> {} with srcAccessMark={}, dstAccessMask={}, srcStage={}, dstStage={}", from, to, barrier.srcAccessMask(), barrier.dstAccessMask(), srcStage, dstStage)
val memoryBarriers = if(memoryBarrier) {
VkMemoryBarrier.callocStack(1, stack)
.sType(VK_STRUCTURE_TYPE_MEMORY_BARRIER)
.srcAccessMask(srcAccessMask)
.dstAccessMask(dstAccessMask)
} else {
null
}
vkCmdPipelineBarrier(
commandBuffer,
srcStage,
dstStage,
dependencyFlags,
memoryBarriers,
null,
barrier
)
}
}
/**
* Transitions Vulkan image layouts.
*/
fun transitionLayout(image: Long, oldLayout: Int, newLayout: Int, mipLevels: Int = 1,
subresourceRange: VkImageSubresourceRange? = null,
srcStage: Int = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, dstStage: Int = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
commandBuffer: VkCommandBuffer) {
with(commandBuffer) {
val barrier = VkImageMemoryBarrier.calloc(1)
.sType(VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER)
.pNext(NULL)
.oldLayout(oldLayout)
.newLayout(newLayout)
.srcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.dstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.image(image)
if (subresourceRange == null) {
barrier.subresourceRange()
.aspectMask(VK_IMAGE_ASPECT_COLOR_BIT)
.baseMipLevel(0)
.levelCount(mipLevels)
.baseArrayLayer(0)
.layerCount(1)
} else {
barrier.subresourceRange(subresourceRange)
}
if (oldLayout == VK_IMAGE_LAYOUT_PREINITIALIZED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) {
barrier
.srcAccessMask(VK_ACCESS_HOST_WRITE_BIT)
.dstAccessMask(VK_ACCESS_TRANSFER_READ_BIT)
} else if (oldLayout == VK_IMAGE_LAYOUT_PREINITIALIZED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
barrier
.srcAccessMask(VK_ACCESS_HOST_WRITE_BIT)
.dstAccessMask(VK_ACCESS_TRANSFER_WRITE_BIT)
} else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
barrier
.srcAccessMask(VK_ACCESS_TRANSFER_WRITE_BIT)
if(dstStage == VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT) {
barrier.dstAccessMask(VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT)
} else {
barrier.dstAccessMask(VK_ACCESS_SHADER_READ_BIT)
}
} else if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
barrier
.srcAccessMask(0)
.dstAccessMask(VK_ACCESS_TRANSFER_WRITE_BIT)
} else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) {
barrier.srcAccessMask(VK_ACCESS_TRANSFER_WRITE_BIT)
barrier.dstAccessMask(VK_ACCESS_TRANSFER_READ_BIT)
} else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
barrier
.srcAccessMask(VK_ACCESS_TRANSFER_READ_BIT)
.dstAccessMask(VK_ACCESS_SHADER_READ_BIT)
} else if(oldLayout == KHRSwapchain.VK_IMAGE_LAYOUT_PRESENT_SRC_KHR && newLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) {
barrier
.srcAccessMask(VK_ACCESS_MEMORY_READ_BIT)
.dstAccessMask(VK_ACCESS_TRANSFER_READ_BIT)
} else if(oldLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL && newLayout == KHRSwapchain.VK_IMAGE_LAYOUT_PRESENT_SRC_KHR) {
barrier
.srcAccessMask(VK_ACCESS_TRANSFER_READ_BIT)
.dstAccessMask(VK_ACCESS_MEMORY_READ_BIT)
} else if(oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
barrier
.srcAccessMask(0)
.dstAccessMask(VK_ACCESS_SHADER_READ_BIT)
} else if(oldLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) {
barrier.srcAccessMask(VK_ACCESS_SHADER_READ_BIT)
.dstAccessMask(VK_ACCESS_TRANSFER_READ_BIT)
} else if(oldLayout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
barrier.srcAccessMask(VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT)
.dstAccessMask(VK_ACCESS_TRANSFER_WRITE_BIT)
} else if(oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) {
barrier.srcAccessMask(VK_ACCESS_TRANSFER_WRITE_BIT)
.dstAccessMask(VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT)
} else if(oldLayout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) {
barrier.srcAccessMask(VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT)
.dstAccessMask(VK_ACCESS_TRANSFER_READ_BIT)
} else if(oldLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) {
barrier.srcAccessMask(VK_ACCESS_TRANSFER_READ_BIT)
.dstAccessMask(VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT)
} else if(oldLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
barrier.srcAccessMask(VK_ACCESS_INPUT_ATTACHMENT_READ_BIT)
.dstAccessMask(VK_ACCESS_TRANSFER_WRITE_BIT)
} else if(oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) {
barrier.srcAccessMask(VK_ACCESS_TRANSFER_WRITE_BIT)
.dstAccessMask(VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT)
} else if(oldLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) {
barrier.srcAccessMask(VK_ACCESS_TRANSFER_READ_BIT)
.dstAccessMask(VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT)
} else if(oldLayout == KHRSwapchain.VK_IMAGE_LAYOUT_PRESENT_SRC_KHR && newLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) {
barrier.srcAccessMask(VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT)
.dstAccessMask(VK_ACCESS_TRANSFER_READ_BIT)
} else if(oldLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL && newLayout == KHRSwapchain.VK_IMAGE_LAYOUT_PRESENT_SRC_KHR) {
barrier.srcAccessMask(VK_ACCESS_TRANSFER_READ_BIT)
.dstAccessMask(VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT)
} else if(oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) {
barrier.srcAccessMask(VK_ACCESS_TRANSFER_WRITE_BIT)
.dstAccessMask(VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT)
} else {
logger.error("Unsupported layout transition: $oldLayout -> $newLayout")
}
logger.trace("Transition: {} -> {} with srcAccessMark={}, dstAccessMask={}, srcStage={}, dstStage={}", oldLayout, newLayout, barrier.srcAccessMask(), barrier.dstAccessMask(), srcStage, dstStage)
vkCmdPipelineBarrier(this,
srcStage,
dstStage,
0, null, null, barrier)
barrier.free()
}
}
private fun Texture.toVulkanFormat(): Int {
var format = when(this.type) {
is ByteType -> when(this.channels) {
1 -> VK_FORMAT_R8_SNORM
2 -> VK_FORMAT_R8G8_SNORM
3 -> VK_FORMAT_R8G8B8A8_SNORM
4 -> VK_FORMAT_R8G8B8A8_SNORM
else -> { logger.warn("Unknown texture type: $type, with $channels channels, falling back to default"); VK_FORMAT_R8G8B8A8_UNORM }
}
is UnsignedByteType -> when(this.channels) {
1 -> VK_FORMAT_R8_UNORM
2 -> VK_FORMAT_R8G8_UNORM
3 -> VK_FORMAT_R8G8B8A8_UNORM
4 -> VK_FORMAT_R8G8B8A8_UNORM
else -> { logger.warn("Unknown texture type: $type, with $channels channels, falling back to default"); VK_FORMAT_R8G8B8A8_UNORM }
}
is ShortType -> when(this.channels) {
1 -> VK_FORMAT_R16_SNORM
2 -> VK_FORMAT_R16G16_SNORM
3 -> VK_FORMAT_R16G16B16A16_SNORM
4 -> VK_FORMAT_R16G16B16A16_SNORM
else -> { logger.warn("Unknown texture type: $type, with $channels channels, falling back to default"); VK_FORMAT_R8G8B8A8_UNORM }
}
is UnsignedShortType -> when(this.channels) {
1 -> VK_FORMAT_R16_UNORM
2 -> VK_FORMAT_R16G16_UNORM
3 -> VK_FORMAT_R16G16B16A16_UNORM
4 -> VK_FORMAT_R16G16B16A16_UNORM
else -> { logger.warn("Unknown texture type: $type, with $channels channels, falling back to default"); VK_FORMAT_R8G8B8A8_UNORM }
}
is IntType -> when(this.channels) {
1 -> VK_FORMAT_R32_SINT
2 -> VK_FORMAT_R32G32_SINT
3 -> VK_FORMAT_R32G32B32A32_SINT
4 -> VK_FORMAT_R32G32B32A32_SINT
else -> { logger.warn("Unknown texture type: $type, with $channels channels, falling back to default"); VK_FORMAT_R8G8B8A8_UNORM }
}
is UnsignedIntType -> when(this.channels) {
1 -> VK_FORMAT_R32_UINT
2 -> VK_FORMAT_R32G32_UINT
3 -> VK_FORMAT_R32G32B32A32_UINT
4 -> VK_FORMAT_R32G32B32A32_UINT
else -> { logger.warn("Unknown texture type: $type, with $channels channels, falling back to default"); VK_FORMAT_R8G8B8A8_UNORM }
}
is FloatType -> when(this.channels) {
1 -> VK_FORMAT_R32_SFLOAT
2 -> VK_FORMAT_R32G32_SFLOAT
3 -> VK_FORMAT_R32G32B32A32_SFLOAT
4 -> VK_FORMAT_R32G32B32A32_SFLOAT
else -> { logger.warn("Unknown texture type: $type, with $channels channels, falling back to default"); VK_FORMAT_R8G8B8A8_UNORM }
}
is DoubleType -> TODO("Double format textures are not supported")
else -> throw UnsupportedOperationException("Type ${type.javaClass.simpleName} is not supported")
}
if(!this.normalized && this.type !is FloatType && this.type !is ByteType && this.type !is IntType) {
format += 4
}
return format
}
}
}
| lgpl-3.0 | 952c866b45de18a550023bbef2ecbc3e | 43.260156 | 242 | 0.541624 | 4.854394 | false | false | false | false |
google/android-fhir | contrib/barcode/src/main/java/com/google/android/fhir/datacapture/contrib/views/barcode/mlkit/md/camera/CameraReticleAnimator.kt | 1 | 4079 | /*
* Copyright 2021 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
*
* 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.google.android.fhir.datacapture.contrib.views.barcode.mlkit.md.camera
import android.animation.AnimatorSet
import android.animation.ValueAnimator
import androidx.interpolator.view.animation.FastOutSlowInInterpolator
/** Custom animator for the object or barcode reticle in live camera. */
class CameraReticleAnimator(graphicOverlay: GraphicOverlay) {
/** Returns the scale value of ripple alpha ranges in [0, 1]. */
var rippleAlphaScale = 0f
private set
/** Returns the scale value of ripple size ranges in [0, 1]. */
var rippleSizeScale = 0f
private set
/** Returns the scale value of ripple stroke width ranges in [0, 1]. */
var rippleStrokeWidthScale = 1f
private set
private val animatorSet: AnimatorSet
init {
val rippleFadeInAnimator = ValueAnimator.ofFloat(0f, 1f).setDuration(DURATION_RIPPLE_FADE_IN_MS)
rippleFadeInAnimator.addUpdateListener { animation ->
rippleAlphaScale = animation.animatedValue as Float
graphicOverlay.postInvalidate()
}
val rippleFadeOutAnimator =
ValueAnimator.ofFloat(1f, 0f).setDuration(DURATION_RIPPLE_FADE_OUT_MS)
rippleFadeOutAnimator.startDelay = START_DELAY_RIPPLE_FADE_OUT_MS
rippleFadeOutAnimator.addUpdateListener { animation ->
rippleAlphaScale = animation.animatedValue as Float
graphicOverlay.postInvalidate()
}
val rippleExpandAnimator = ValueAnimator.ofFloat(0f, 1f).setDuration(DURATION_RIPPLE_EXPAND_MS)
rippleExpandAnimator.startDelay = START_DELAY_RIPPLE_EXPAND_MS
rippleExpandAnimator.interpolator = FastOutSlowInInterpolator()
rippleExpandAnimator.addUpdateListener { animation ->
rippleSizeScale = animation.animatedValue as Float
graphicOverlay.postInvalidate()
}
val rippleStrokeWidthShrinkAnimator =
ValueAnimator.ofFloat(1f, 0.5f).setDuration(DURATION_RIPPLE_STROKE_WIDTH_SHRINK_MS)
rippleStrokeWidthShrinkAnimator.startDelay = START_DELAY_RIPPLE_STROKE_WIDTH_SHRINK_MS
rippleStrokeWidthShrinkAnimator.interpolator = FastOutSlowInInterpolator()
rippleStrokeWidthShrinkAnimator.addUpdateListener { animation ->
rippleStrokeWidthScale = animation.animatedValue as Float
graphicOverlay.postInvalidate()
}
val fakeAnimatorForRestartDelay =
ValueAnimator.ofInt(0, 0).setDuration(DURATION_RESTART_DORMANCY_MS)
fakeAnimatorForRestartDelay.startDelay = START_DELAY_RESTART_DORMANCY_MS
animatorSet = AnimatorSet()
animatorSet.playTogether(
rippleFadeInAnimator,
rippleFadeOutAnimator,
rippleExpandAnimator,
rippleStrokeWidthShrinkAnimator,
fakeAnimatorForRestartDelay
)
}
fun start() {
if (!animatorSet.isRunning) animatorSet.start()
}
fun cancel() {
animatorSet.cancel()
rippleAlphaScale = 0f
rippleSizeScale = 0f
rippleStrokeWidthScale = 1f
}
companion object {
private const val DURATION_RIPPLE_FADE_IN_MS: Long = 333
private const val DURATION_RIPPLE_FADE_OUT_MS: Long = 500
private const val DURATION_RIPPLE_EXPAND_MS: Long = 833
private const val DURATION_RIPPLE_STROKE_WIDTH_SHRINK_MS: Long = 833
private const val DURATION_RESTART_DORMANCY_MS: Long = 1333
private const val START_DELAY_RIPPLE_FADE_OUT_MS: Long = 667
private const val START_DELAY_RIPPLE_EXPAND_MS: Long = 333
private const val START_DELAY_RIPPLE_STROKE_WIDTH_SHRINK_MS: Long = 333
private const val START_DELAY_RESTART_DORMANCY_MS: Long = 1167
}
}
| apache-2.0 | 72bbf52fb980dce989e2391c24faf86a | 36.768519 | 100 | 0.750429 | 4.588301 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/vulkan/src/templates/kotlin/vulkan/Custom.kt | 1 | 24605 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package vulkan
import org.lwjgl.generator.*
import vulkan.templates.*
fun templateCustomization() {
PFN_vkDebugReportCallbackEXT.function.apply {
additionalCode = """
/**
* Converts the specified {@link VkDebugReportCallbackEXT} argument to a String.
*
* <p>This method may only be used inside a {@code VkDebugReportCallbackEXT} invocation.</p>
*
* @param string the argument to decode
*
* @return the message as a String
*/
public static String getString(long string) {
return memUTF8(string);
}
"""
}
VkShaderModuleCreateInfo.definition.apply {
AutoSize("pCode")..this["codeSize"]
PrimitiveType("uint32_t", PrimitiveMapping.BYTE).const.p("pCode", "points to code that is used to create the shader module")
.replace(this["pCode"])
}
VK10.apply {
IntConstant(
"""
The API version number for Vulkan 1.0.
The patch version number in this macro will always be zero. The supported patch version for a physical device <b>can</b> be queried with
#GetPhysicalDeviceProperties().
""",
"API_VERSION_1_0".."VK_MAKE_API_VERSION(0, 1, 0, 0)"
)
IntConstant(
"The Vulkan registry version used to generate the LWJGL bindings.",
"HEADER_VERSION".."228"
)
LongConstant(
"""
The reserved handle {@code VK_NULL_HANDLE} <b>can</b> be passed in place of valid object handles when explicitly called out in the specification. Any
command that creates an object successfully <b>must</b> not return {@code VK_NULL_HANDLE}. It is valid to pass {@code VK_NULL_HANDLE} to any
{@code vkDestroy*} or {@code vkFree*} command, which will silently ignore these values.
""",
"NULL_HANDLE"..0L
)
macro(expression = "(variant << 29) | (major << 22) | (minor << 12) | patch")..uint32_t(
"VK_MAKE_API_VERSION",
"""
Constructs an API version number.
This macro <b>can</b> be used when constructing the ##VkApplicationInfo{@code ::pname:apiVersion} parameter passed to #CreateInstance().
""",
uint32_t("variant", "the variant number"),
uint32_t("major", "the major version number"),
uint32_t("minor", "the minor version number"),
uint32_t("patch", "the patch version number"),
noPrefix = true
)
macro(expression = "version >>> 29")..uint32_t(
"VK_API_VERSION_VARIANT",
"Extracts the API variant version number from a packed version number.",
uint32_t("version", "the Vulkan API version"),
noPrefix = true
)
macro(expression = "(version >>> 22) & 0x7F")..uint32_t(
"VK_API_VERSION_MAJOR",
"Extracts the API major version number from a packed version number.",
uint32_t("version", "the Vulkan API version"),
noPrefix = true
)
macro(expression = "(version >>> 12) & 0x3FF")..uint32_t(
"VK_API_VERSION_MINOR",
"Extracts the API minor version number from a packed version number.",
uint32_t("version", "the Vulkan API version"),
noPrefix = true
)
macro(expression = "version & 0xFFF")..uint32_t(
"VK_API_VERSION_PATCH",
"Extracts the API patch version number from a packed version number.",
uint32_t("version", "the Vulkan API version"),
noPrefix = true
)
macro(expression = "(major << 22) | (minor << 12) | patch")..uint32_t(
"VK_MAKE_VERSION",
"""
Constructs an API version number.
This macro <b>can</b> be used when constructing the ##VkApplicationInfo{@code ::pname:apiVersion} parameter passed to #CreateInstance().
<em>Deprecated</em>, #VK_MAKE_API_VERSION() should be used instead.
""",
uint32_t("major", "the major version number"),
uint32_t("minor", "the minor version number"),
uint32_t("patch", "the patch version number"),
noPrefix = true
)
macro(expression = "version >>> 22")..uint32_t(
"VK_VERSION_MAJOR",
"""
Extracts the API major version number from a packed version number.
<em>Deprecated</em>, #VK_API_VERSION_MAJOR() should be used instead.
""",
uint32_t("version", "the Vulkan API version"),
noPrefix = true
)
macro(expression = "(version >>> 12) & 0x3FF")..uint32_t(
"VK_VERSION_MINOR",
"""
Extracts the API minor version number from a packed version number.
<em>Deprecated</em>, #VK_API_VERSION_MINOR() should be used instead.
""",
uint32_t("version", "the Vulkan API version"),
noPrefix = true
)
macro(expression = "version & 0xFFF")..uint32_t(
"VK_VERSION_PATCH",
"""
Extracts the API patch version number from a packed version number.
<em>Deprecated</em>, #VK_API_VERSION_PATCH() should be used instead.
""",
uint32_t("version", "the Vulkan API version"),
noPrefix = true
)
IntConstant(
"API Constants",
"MAX_PHYSICAL_DEVICE_NAME_SIZE".."256",
"UUID_SIZE".."16",
"LUID_SIZE".."8",
"MAX_EXTENSION_NAME_SIZE".."256",
"MAX_DESCRIPTION_SIZE".."256",
"MAX_MEMORY_TYPES".."32",
"MAX_MEMORY_HEAPS".."16",
"REMAINING_MIP_LEVELS".."(~0)",
"REMAINING_ARRAY_LAYERS".."(~0)",
"ATTACHMENT_UNUSED".."(~0)",
"TRUE".."1",
"FALSE".."0",
"QUEUE_FAMILY_IGNORED".."(~0)",
"QUEUE_FAMILY_EXTERNAL".."(~0-1)",
"SUBPASS_EXTERNAL".."(~0)",
"MAX_DEVICE_GROUP_SIZE".."32",
"MAX_DRIVER_NAME_SIZE".."256",
"MAX_DRIVER_INFO_SIZE".."256"
)
FloatConstant(
"API Constants",
"LOD_CLAMP_NONE".."1000.0f"
)
LongConstant(
"API Constants",
"WHOLE_SIZE".."(~0L)"
)
nullable..this["GetInstanceProcAddr"].getParam("instance")
MultiType(
PointerMapping.DATA_INT,
PointerMapping.DATA_LONG
)..this["GetQueryPoolResults"].getParam("pData")
MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_LONG,
PointerMapping.DATA_FLOAT,
PointerMapping.DATA_DOUBLE
)..this["CmdUpdateBuffer"].getParam("pData")
MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_LONG,
PointerMapping.DATA_FLOAT,
PointerMapping.DATA_DOUBLE
)..this["CmdPushConstants"].getParam("pValues")
SingleValue("pSubmit")..this["QueueSubmit"].getParam("pSubmits")
SingleValue("pMemoryRange")..this["FlushMappedMemoryRanges"].getParam("pMemoryRanges")
SingleValue("pMemoryRange")..this["InvalidateMappedMemoryRanges"].getParam("pMemoryRanges")
SingleValue("pBindInfo")..this["QueueBindSparse"].getParam("pBindInfo")
SingleValue("pFence")..this["ResetFences"].getParam("pFences")
SingleValue("pFence")..this["WaitForFences"].getParam("pFences")
SingleValue("pDescriptorSet")..this["FreeDescriptorSets"].getParam("pDescriptorSets")
SingleValue("pRange")..this["CmdClearColorImage"].getParam("pRanges")
SingleValue("pRange")..this["CmdClearDepthStencilImage"].getParam("pRanges")
SingleValue("pRegion")..this["CmdResolveImage"].getParam("pRegions")
SingleValue("pCommandBuffer")..this["CmdExecuteCommands"].getParam("pCommandBuffers")
SingleValue("pCommandBuffer")..this["FreeCommandBuffers"].getParam("pCommandBuffers")
}
VK11.apply {
documentation =
"""
The core Vulkan 1.1 functionality.
Vulkan Version 1.1 <em>promoted</em> a number of key extensions into the core API:
${ul(
KHR_16bit_storage.link,
KHR_bind_memory2.link,
KHR_dedicated_allocation.link,
KHR_descriptor_update_template.link,
KHR_device_group.link,
KHR_device_group_creation.link,
KHR_external_memory.link,
KHR_external_memory_capabilities.link,
KHR_external_semaphore.link,
KHR_external_semaphore_capabilities.link,
KHR_external_fence.link,
KHR_external_fence_capabilities.link,
KHR_get_memory_requirements2.link,
KHR_get_physical_device_properties2.link,
KHR_maintenance1.link,
KHR_maintenance2.link,
KHR_maintenance3.link,
KHR_multiview.link,
KHR_relaxed_block_layout.link,
KHR_sampler_ycbcr_conversion.link,
KHR_shader_draw_parameters.link,
KHR_storage_buffer_storage_class.link,
KHR_variable_pointers.link
)}
The only changes to the functionality added by these extensions were to {@code VK_KHR_shader_draw_parameters}, which had a
<a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html\#features-features-shaderDrawParameters">feature bit</a>
added to determine support in the core API, and
<a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html\#features-features-variablePointersStorageBuffer">{@code variablePointersStorageBuffer}</a>
from {@code VK_KHR_variable_pointers} was made optional.
Additionally, Vulkan 1.1 added support for {@link VkPhysicalDeviceSubgroupProperties subgroup operations},
{@link VkPhysicalDeviceProtectedMemoryFeatures protected memory}, and a new command to {@link VK11\#vkEnumerateInstanceVersion enumerate the
instance version}.
"""
IntConstant(
"The API version number for Vulkan 1.1.",
"API_VERSION_1_1".."VK_MAKE_API_VERSION(0, 1, 1, 0)"
)
}
VK12.apply {
documentation =
"""
The core Vulkan 1.2 functionality.
Vulkan Version 1.2 <em>promoted</em> a number of key extensions into the core API:
${ul(
KHR_8bit_storage.link,
KHR_buffer_device_address.link,
KHR_create_renderpass2.link,
KHR_depth_stencil_resolve.link,
KHR_draw_indirect_count.link,
KHR_driver_properties.link,
KHR_image_format_list.link,
KHR_imageless_framebuffer.link,
KHR_sampler_mirror_clamp_to_edge.link,
KHR_separate_depth_stencil_layouts.link,
KHR_shader_atomic_int64.link,
KHR_shader_float16_int8.link,
KHR_shader_float_controls.link,
KHR_shader_subgroup_extended_types.link,
KHR_spirv_1_4.link,
KHR_timeline_semaphore.link,
KHR_uniform_buffer_standard_layout.link,
KHR_vulkan_memory_model.link,
EXT_descriptor_indexing.link,
EXT_host_query_reset.link,
EXT_sampler_filter_minmax.link,
EXT_scalar_block_layout.link,
EXT_separate_stencil_usage.link,
EXT_shader_viewport_index_layer.link
)}
All differences in behavior between these extensions and the corresponding Vulkan 1.2 functionality are summarized below.
<h3>Differences relative to {@code VK_KHR_8bit_storage}</h3>
If the {@code VK_KHR_8bit_storage} extension is not supported, support for the SPIR-V {@code StorageBuffer8BitAccess} capability in shader modules
is optional. Support for this feature is defined by ##VkPhysicalDeviceVulkan12Features{@code ::storageBuffer8BitAccess} when queried via
#GetPhysicalDeviceFeatures2().
<h3>Differences relative to {@code VK_KHR_draw_indirect_count}</h3>
If the {@code VK_KHR_draw_indirect_count} extension is not supported, support for the entry points #CmdDrawIndirectCount() and
#CmdDrawIndexedIndirectCount() is optional. Support for this feature is defined by ##VkPhysicalDeviceVulkan12Features{@code ::drawIndirectCount}
when queried via #GetPhysicalDeviceFeatures2().
<h3>Differences relative to {@code VK_KHR_sampler_mirror_clamp_to_edge}</h3>
If the {@code VK_KHR_sampler_mirror_clamp_to_edge} extension is not supported, support for the {@code VkSamplerAddressMode}
#SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE is optional. Support for this feature is defined by
##VkPhysicalDeviceVulkan12Features{@code ::samplerMirrorClampToEdge} when queried via #GetPhysicalDeviceFeatures2().
<h3>Differences relative to {@code VK_EXT_descriptor_indexing}</h3>
If the {@code VK_EXT_descriptor_indexing} extension is not supported, support for the {@code descriptorIndexing} feature is optional. Support for
this feature is defined by ##VkPhysicalDeviceVulkan12Features{@code ::descriptorIndexing} when queried via #GetPhysicalDeviceFeatures2().
<h3>Differences relative to {@code VK_EXT_scalar_block_layout}</h3>
If the {@code VK_EXT_scalar_block_layout} extension is not supported, support for the {@code scalarBlockLayout} feature is optional. Support for
this feature is defined by ##VkPhysicalDeviceVulkan12Features{@code ::scalarBlockLayout} when queried via #GetPhysicalDeviceFeatures2().
<h3>Differences relative to {@code VK_EXT_shader_viewport_index_layer}</h3>
If the {@code VK_EXT_shader_viewport_index_layer} extension is not supported, support for the {@code ShaderViewportIndexLayerEXT} SPIR-V capability
is optional. Support for this feature is defined by ##VkPhysicalDeviceVulkan12Features{@code ::shaderOutputViewportIndex} and
##VkPhysicalDeviceVulkan12Features{@code ::shaderOutputLayer} when queried via #GetPhysicalDeviceFeatures2().
<h3>Additional Vulkan 1.2 Feature Support</h3>
In addition to the promoted extensions described above, Vulkan 1.2 added support for:
${ul(
"SPIR-V version 1.4.",
"SPIR-V version 1.5.",
"""
The <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html\#features-samplerMirrorClampToEdge">samplerMirrorClampToEdge</a>
feature which indicates whether the implementation supports the #SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE sampler address mode.
""",
"The {@code ShaderNonUniform} capability in SPIR-V version 1.5.",
"""
The <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html\#features-shaderOutputViewportIndex">shaderOutputViewportIndex</a>
feature which indicates that the
<a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html\#spirvenv-capabilities-table-shader-viewport-index">{@code ShaderViewportIndex}</a>
capability can be used.
""",
"""
The <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html\#features-shaderOutputLayer">shaderOutputLayer</a>
feature which indicates that the
<a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html\#spirvenv-capabilities-table-shader-layer">{@code ShaderLayer}</a>
capability can be used.
""",
"""
The <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html\#features-subgroupBroadcastDynamicId">subgroupBroadcastDynamicId</a>
feature which allows the "{@code Id}" operand of {@code OpGroupNonUniformBroadcast} to be dynamically uniform within a subgroup, and the
"{@code Index}" operand of {@code OpGroupNonUniformQuadBroadcast} to be dynamically uniform within a derivative group, in shader modules of
version 1.5 or higher.
""",
"""
The <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html\#features-drawIndirectCount">drawIndirectCount</a>
feature which indicates whether the #CmdDrawIndirectCount() and #CmdDrawIndexedIndirectCount() functions can be used.
""",
"""
The <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html\#features-descriptorIndexing">descriptorIndexing</a>
feature which indicates the implementation supports the minimum number of descriptor indexing features as defined in the
<a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html\#features-requirements">Feature Requirements</a>
section.
""",
"""
The <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html\#features-samplerFilterMinmax">samplerFilterMinmax</a>
feature which indicates whether the implementation supports the minimum number of image formats that support the
#FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_MINMAX_BIT feature bit as defined by the
<a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html\#limits-filterMinmaxSingleComponentFormats-minimum-requirements">{@code filterMinmaxSingleComponentFormats}</a>
property minimum requirements.
""",
"""
The <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html\#limits-framebufferIntegerColorSampleCounts">framebufferIntegerColorSampleCounts</a>
limit which indicates the color sample counts that are supported for all framebuffer color attachments with integer formats.
"""
)}
"""
IntConstant(
"The API version number for Vulkan 1.2.",
"API_VERSION_1_2".."VK_MAKE_API_VERSION(0, 1, 2, 0)"
)
}
VK13.apply {
documentation =
"""
The core Vulkan 1.3 functionality.
Vulkan Version 1.3 <em>promoted</em> a number of key extensions into the core API:
${ul(
KHR_copy_commands2.link,
KHR_dynamic_rendering.link,
KHR_format_feature_flags2.link,
KHR_maintenance4.link,
KHR_shader_integer_dot_product.link,
KHR_shader_non_semantic_info.link,
KHR_shader_terminate_invocation.link,
KHR_synchronization2.link,
KHR_zero_initialize_workgroup_memory.link,
EXT_4444_formats.link,
EXT_extended_dynamic_state.link,
EXT_extended_dynamic_state2.link,
EXT_image_robustness.link,
EXT_inline_uniform_block.link,
EXT_pipeline_creation_cache_control.link,
EXT_pipeline_creation_feedback.link,
EXT_private_data.link,
EXT_shader_demote_to_helper_invocation.link,
EXT_subgroup_size_control.link,
EXT_texel_buffer_alignment.link,
EXT_texture_compression_astc_hdr.link,
EXT_tooling_info.link,
EXT_ycbcr_2plane_444_formats.link
)}
All differences in behavior between these extensions and the corresponding Vulkan 1.3 functionality are summarized below.
<h3>Differences relative to {@code VK_EXT_4444_formats}</h3>
If the {@code VK_EXT_4444_formats} extension is not supported, support for all formats defined by it are optional in Vulkan 1.3. There are no
members in the ##VkPhysicalDeviceVulkan13Features structure corresponding to the ##VkPhysicalDevice4444FormatsFeaturesEXT structure.
<h3>Differences relative to {@code VK_EXT_extended_dynamic_state}</h3>
All dynamic state enumerants and entry points defined by {@code VK_EXT_extended_dynamic_state} are required in Vulkan 1.3. There are no members in
the ##VkPhysicalDeviceVulkan13Features structure corresponding to the ##VkPhysicalDeviceExtendedDynamicStateFeaturesEXT structure.
<h3>Differences relative to {@code VK_EXT_extended_dynamic_state2}</h3>
The optional dynamic state enumerants and entry points defined by {@code VK_EXT_extended_dynamic_state2} for patch control points and logic op are
not promoted in Vulkan 1.3. There are no members in the ##VkPhysicalDeviceVulkan13Features structure corresponding to the
##VkPhysicalDeviceExtendedDynamicState2FeaturesEXT structure.
<h3>Differences relative to {@code VK_EXT_texel_buffer_alignment}</h3>
The more specific alignment requirements defined by ##VkPhysicalDeviceTexelBufferAlignmentProperties are required in Vulkan 1.3. There are no
members in the ##VkPhysicalDeviceVulkan13Features structure corresponding to the ##VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT structure.
<h3>Differences relative to {@code VK_EXT_texture_compression_astc_hdr}</h3>
If the {@code VK_EXT_texture_compression_astc_hdr} extension is not supported, support for all formats defined by it are optional in Vulkan 1.3.
The {@code textureCompressionASTC_HDR} member of ##VkPhysicalDeviceVulkan13Features indicates whether a Vulkan 1.3 implementation supports these
formats.
<h3>Differences relative to {@code VK_EXT_ycbcr_2plane_444_formats}</h3>
If the {@code VK_EXT_ycbcr_2plane_444_formats} extension is not supported, support for all formats defined by it are optional in Vulkan 1.3. There
are no members in the ##VkPhysicalDeviceVulkan13Features structure corresponding to the ##VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT
structure.
<h3>Additional Vulkan 1.3 Feature Support</h3>
In addition to the promoted extensions described above, Vulkan 1.3 added required support for:
${ul(
"SPIR-V version 1.6. SPIR-V 1.6 deprecates (but does not remove) the WorkgroupSize decoration.",
"""
The {@code bufferDeviceAddress} feature which indicates support for accessing memory in shaders as storage buffers via
#GetBufferDeviceAddress().
""",
"""
The {@code vulkanMemoryModel}, {@code vulkanMemoryModelDeviceScope}, and {@code vulkanMemoryModelAvailabilityVisibilityChains} features, which
indicate support for the corresponding Vulkan Memory Model capabilities.
""",
"The {@code maxInlineUniformTotalSize} limit is added to provide the total size of all inline uniform block bindings in a pipeline layout."
)}
"""
IntConstant(
"The API version number for Vulkan 1.3.",
"API_VERSION_1_3".."VK_MAKE_API_VERSION(0, 1, 3, 0)"
)
}
NV_ray_tracing.apply {
MultiType(PointerMapping.DATA_LONG)..this["GetAccelerationStructureHandleNV"].getParam("pData")
}
} | bsd-3-clause | 3bb095f178754a6392c684274c33e127 | 46.871595 | 230 | 0.616501 | 4.67509 | false | false | false | false |
Tickaroo/tikxml | annotationprocessortesting-kt/src/main/java/com/tickaroo/tikxml/annotationprocessing/element/constructor/ServerConstructor.kt | 1 | 1602 | /*
* Copyright (C) 2015 Hannes Dorfmann
* Copyright (C) 2015 Tickaroo, 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.tickaroo.tikxml.annotationprocessing.element.constructor
import com.tickaroo.tikxml.annotation.Attribute
import com.tickaroo.tikxml.annotation.Element
import com.tickaroo.tikxml.annotation.Xml
/**
* @author Hannes Dorfmann
*/
@Xml(name = "server")
class ServerConstructor(
@param:Attribute val name: String?,
@param:Element(name = "serverConfig") val config: ServerConfigConstructor?
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ServerConstructor) return false
val that = other as ServerConstructor?
if (if (name != null) name != that!!.name else that!!.name != null) return false
return if (config != null) config == that.config else that.config == null
}
override fun hashCode(): Int {
var result = name?.hashCode() ?: 0
result = 31 * result + (config?.hashCode() ?: 0)
return result
}
}
| apache-2.0 | fa58f464370b3544dd8ff817df351a54 | 31.693878 | 88 | 0.686642 | 4.182768 | false | true | false | false |
mdanielwork/intellij-community | plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalProjectOptionsProvider.kt | 2 | 3156 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.terminal
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.guessProjectDir
import com.intellij.openapi.util.SystemInfo
import java.io.File
import kotlin.reflect.KMutableProperty1
import kotlin.reflect.KProperty
/**
* @author traff
*/
@State(name = "TerminalProjectOptionsProvider", storages = [(Storage("terminal.xml"))])
class TerminalProjectOptionsProvider(val project: Project) : PersistentStateComponent<TerminalProjectOptionsProvider.State> {
private val myState = State()
override fun getState(): State? {
return myState
}
override fun loadState(state: State) {
myState.myStartingDirectory = state.myStartingDirectory
}
class State {
var myStartingDirectory: String? = null
}
var startingDirectory: String? by ValueWithDefault(State::myStartingDirectory, myState) { defaultStartingDirectory }
val defaultStartingDirectory: String?
get() {
var directory: String? = null
for (customizer in LocalTerminalCustomizer.EP_NAME.extensions) {
try {
if (directory == null) {
directory = customizer.getDefaultFolder(project)
}
}
catch (e: Exception) {
LOG.error("Exception during getting default folder", e)
}
}
return directory ?: currentProjectFolder()
}
private fun currentProjectFolder() = if (project.isDefault) null else project.guessProjectDir()?.canonicalPath
val defaultShellPath: String
get() {
val shell = System.getenv("SHELL")
if (shell != null && File(shell).canExecute()) {
return shell
}
if (SystemInfo.isUnix) {
if (File("/bin/bash").exists()) {
return "/bin/bash"
}
else {
return "/bin/sh"
}
}
else {
return "cmd.exe"
}
}
companion object {
private val LOG = Logger.getInstance(TerminalProjectOptionsProvider::class.java)
fun getInstance(project: Project): TerminalProjectOptionsProvider {
return ServiceManager.getService(project, TerminalProjectOptionsProvider::class.java)
}
}
}
// TODO: In Kotlin 1.1 it will be possible to pass references to instance properties. Until then we need 'state' argument as a receiver for
// to property to apply
class ValueWithDefault<S>(val prop: KMutableProperty1<S, String?>, val state: S, val default: () -> String?) {
operator fun getValue(thisRef: Any?, property: KProperty<*>): String? {
return if (prop.get(state) !== null) prop.get(state) else default()
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String?) {
prop.set(state, if (value == default() || value.isNullOrEmpty()) null else value)
}
}
| apache-2.0 | 8c58f573d2ed7b8146a6e2f2b8abdf53 | 29.346154 | 140 | 0.698035 | 4.508571 | false | false | false | false |
dahlstrom-g/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/ClassToIntConverter.kt | 8 | 2727 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage.impl
import com.intellij.workspaceModel.storage.WorkspaceEntity
import it.unimi.dsi.fastutil.objects.Object2IntMap
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap
import java.util.concurrent.atomic.AtomicReference
/**
* This class fits the cases where there is a relatively small amount of classes (<50).
* The disadvantages are:
* - Two collections copies
*
* N.B. One of the approaches is to generate and assign ids to classes during the code generation.
*/
internal class ClassToIntConverter {
private val map: AtomicReference<Entry> = AtomicReference(Entry(newMap(), emptyArray()))
private class Entry(
val classToInt: Object2IntMap<Class<*>>,
val intToClass: Array<Class<*>?>,
)
fun getInt(clazz: Class<*>): Int {
while (true) {
val entry = map.get()
val result = entry.classToInt.getInt(clazz)
if (result != -1) return result
val classId = entry.classToInt.size
val newEntry = Entry(
newMap(entry.classToInt).also { it.put(clazz, classId) },
entry.intToClass.copyExtendAndPut(classId, clazz)
)
if (map.compareAndSet(entry, newEntry)) return classId
}
}
fun getClassOrDie(id: Int): Class<*> = map.get().intToClass[id] ?: error("Cannot find class by id: $id")
fun getMap(): Map<Class<*>, Int> = map.get().classToInt
fun fromMap(map: Map<Class<*>, Int>) {
val entry = Entry(
Object2IntOpenHashMap(map),
Array<Class<*>?>(map.values.maxOrNull() ?: 0) { null }.also { map.forEach { (clazz, index) -> it[index] = clazz } }
)
this.map.set(entry)
}
private fun newMap(oldMap: Object2IntMap<Class<*>>? = null): Object2IntOpenHashMap<Class<*>> {
val newMap = if (oldMap != null) Object2IntOpenHashMap(oldMap) else Object2IntOpenHashMap()
newMap.defaultReturnValue(-1)
return newMap
}
private inline fun <reified T> Array<T?>.copyExtendAndPut(id: Int, data: T): Array<T?> {
val thisSize = this.size
val res = Array(id + 1) { if (it < thisSize) this[it] else null }
res[id] = data
return res
}
companion object {
val INSTANCE = ClassToIntConverter()
}
}
internal fun Class<*>.toClassId(): Int = ClassToIntConverter.INSTANCE.getInt(this)
@Suppress("UNCHECKED_CAST")
internal inline fun <reified E> Int.findEntityClass(): Class<E> = ClassToIntConverter.INSTANCE.getClassOrDie(this) as Class<E>
@Suppress("UNCHECKED_CAST")
internal fun Int.findWorkspaceEntity(): Class<WorkspaceEntity> = ClassToIntConverter.INSTANCE.getClassOrDie(this) as Class<WorkspaceEntity>
| apache-2.0 | b8d4cfe691d062d8aa54c0051c062032 | 36.356164 | 140 | 0.702237 | 3.923741 | false | false | false | false |
dahlstrom-g/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ActionToolbarGotItTooltip.kt | 12 | 2611 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.ui
import com.intellij.icons.AllIcons
import com.intellij.internal.statistic.collectors.fus.ui.GotItUsageCollector
import com.intellij.internal.statistic.collectors.fus.ui.GotItUsageCollectorGroup
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionToolbar
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.util.Disposer
import com.intellij.ui.GotItTooltip
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.update.Activatable
import com.intellij.util.ui.update.UiNotifyConnector
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import javax.swing.JComponent
internal class ActionToolbarGotItTooltip(@NonNls private val id: String,
@Nls private val tooltipText: String,
disposable: Disposable,
private val toolbar: ActionToolbar,
private val actionComponentSelector: (ActionToolbar) -> JComponent?) : Activatable {
val tooltipDisposable = Disposer.newDisposable().also { Disposer.register(disposable, it) }
private var balloon: Balloon? = null
init {
UiNotifyConnector(toolbar.component, this).also { Disposer.register(tooltipDisposable, it) }
}
override fun showNotify() = showHint()
override fun hideNotify() = hideHint(false)
fun showHint() {
hideBalloon()
val component = actionComponentSelector(toolbar) ?: return
GotItTooltip(id, tooltipText, tooltipDisposable)
.setOnBalloonCreated { balloon = it }
.show(component, GotItTooltip.BOTTOM_MIDDLE)
}
private fun hideBalloon() {
balloon?.hide()
balloon = null
}
fun hideHint(dispose: Boolean) {
hideBalloon()
GotItUsageCollector.instance.logClose(id, GotItUsageCollectorGroup.CloseType.AncestorRemoved)
if (dispose) Disposer.dispose(tooltipDisposable)
}
}
internal val gearButtonOrToolbar: (ActionToolbar) -> JComponent = { toolbar -> toolbar.getGearButton() ?: toolbar.component }
internal val gearButton: (ActionToolbar) -> JComponent? = { toolbar -> toolbar.getGearButton() }
private fun ActionToolbar.getGearButton(): ActionButton? =
UIUtil.uiTraverser(component)
.filter(ActionButton::class.java)
.filter { it.icon == AllIcons.General.GearPlain }
.first()
| apache-2.0 | 66105291bff50751fb6f76fa41a078f2 | 40.444444 | 140 | 0.730755 | 4.478559 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/injection/src/org/jetbrains/kotlin/idea/injection/KotlinLanguageInjectionSupport.kt | 5 | 10465 | // 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.injection
import com.intellij.codeInsight.AnnotationUtil
import com.intellij.lang.Language
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.*
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiTreeUtil.getDeepestLast
import com.intellij.util.Consumer
import com.intellij.util.Processor
import org.intellij.plugins.intelliLang.Configuration
import org.intellij.plugins.intelliLang.inject.*
import org.intellij.plugins.intelliLang.inject.config.BaseInjection
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.KotlinJvmBundle
import org.jetbrains.kotlin.idea.patterns.KotlinPatterns
import org.jetbrains.kotlin.idea.util.addAnnotation
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.findAnnotation
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.siblings
import org.jetbrains.kotlin.psi.psiUtil.startOffset
@NonNls
val KOTLIN_SUPPORT_ID = "kotlin"
class KotlinLanguageInjectionSupport : AbstractLanguageInjectionSupport() {
override fun getId(): String = KOTLIN_SUPPORT_ID
override fun createAddActions(project: Project?, consumer: Consumer<in BaseInjection>?): Array<AnAction> {
return super.createAddActions(project, consumer).apply {
forEach {
it.templatePresentation.icon = KotlinFileType.INSTANCE.icon
}
}
}
override fun getPatternClasses() = arrayOf(KotlinPatterns::class.java)
override fun isApplicableTo(host: PsiLanguageInjectionHost?) = host is KtElement
override fun useDefaultInjector(host: PsiLanguageInjectionHost?): Boolean = false
override fun addInjectionInPlace(language: Language?, host: PsiLanguageInjectionHost?): Boolean {
if (language == null || host == null) return false
val configuration = Configuration.getProjectInstance(host.project).advancedConfiguration
if (!configuration.isSourceModificationAllowed) {
// It's not allowed to modify code without explicit permission. Postpone adding @Inject or comment till it granted.
host.putUserData(InjectLanguageAction.FIX_KEY, Processor { fixHost: PsiLanguageInjectionHost? ->
fixHost != null && addInjectionInstructionInCode(language, fixHost)
})
return false
}
if (!addInjectionInstructionInCode(language, host)) {
return false
}
TemporaryPlacesRegistry.getInstance(host.project).addHostWithUndo(host, InjectedLanguage.create(language.id))
return true
}
override fun removeInjectionInPlace(psiElement: PsiLanguageInjectionHost?): Boolean {
if (psiElement == null || psiElement !is KtElement) return false
val project = psiElement.getProject()
val injectInstructions = listOfNotNull(
findAnnotationInjection(psiElement),
findInjectionComment(psiElement)
)
TemporaryPlacesRegistry.getInstance(project).removeHostWithUndo(project, psiElement)
project.executeWriteCommand(KotlinJvmBundle.message("command.action.remove.injection.in.code.instructions")) {
injectInstructions.forEach(PsiElement::delete)
}
return true
}
override fun findCommentInjection(host: PsiElement, commentRef: Ref<in PsiElement>?): BaseInjection? {
// Do not inject through CommentLanguageInjector, because it injects as simple injection.
// We need to behave special for interpolated strings.
return null
}
fun findCommentInjection(host: KtElement): BaseInjection? {
return InjectorUtils.findCommentInjection(host, "", null)
}
private fun findInjectionComment(host: KtElement): PsiComment? {
val commentRef = Ref.create<PsiElement>(null)
InjectorUtils.findCommentInjection(host, "", commentRef) ?: return null
return commentRef.get() as? PsiComment
}
internal fun findAnnotationInjectionLanguageId(host: KtElement): InjectionInfo? =
findAnnotationInjection(host)?.let(::toInjectionInfo)
internal fun toInjectionInfo(annotationEntry: KtAnnotationEntry): InjectionInfo? {
val extractLanguageFromInjectAnnotation = extractLanguageFromInjectAnnotation(annotationEntry) ?: return null
val prefix = extractStringArgumentByName(annotationEntry, "prefix")
val suffix = extractStringArgumentByName(annotationEntry, "suffix")
return InjectionInfo(extractLanguageFromInjectAnnotation, prefix, suffix)
}
}
private fun extractStringArgumentByName(annotationEntry: KtAnnotationEntry, name: String): String? {
val namedArgument: ValueArgument =
annotationEntry.valueArguments.firstOrNull { it.getArgumentName()?.asName?.asString() == name } ?: return null
return extractStringValue(namedArgument)
}
private fun extractLanguageFromInjectAnnotation(annotationEntry: KtAnnotationEntry): String? {
val firstArgument: ValueArgument = annotationEntry.valueArguments.firstOrNull() ?: return null
return extractStringValue(firstArgument)
}
private fun extractStringValue(valueArgument: ValueArgument): String? {
val firstStringArgument = valueArgument.getArgumentExpression() as? KtStringTemplateExpression ?: return null
val firstStringEntry = firstStringArgument.entries.singleOrNull() ?: return null
return firstStringEntry.text
}
private fun findAnnotationInjection(host: KtElement): KtAnnotationEntry? {
val modifierListOwner = findElementToInjectWithAnnotation(host) ?: return null
val modifierList = modifierListOwner.modifierList ?: return null
// Host can't be before annotation
if (host.startOffset < modifierList.endOffset) return null
return modifierListOwner.findAnnotation(FqName(AnnotationUtil.LANGUAGE))
}
private fun canInjectWithAnnotation(host: PsiElement): Boolean {
val module = ModuleUtilCore.findModuleForPsiElement(host) ?: return false
val javaPsiFacade = JavaPsiFacade.getInstance(module.project)
return javaPsiFacade.findClass(AnnotationUtil.LANGUAGE, GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module)) != null
}
private fun findElementToInjectWithAnnotation(host: KtElement): KtModifierListOwner? = PsiTreeUtil.getParentOfType(
host,
KtModifierListOwner::class.java,
false, /* strict */
KtBlockExpression::class.java, KtParameterList::class.java, KtTypeParameterList::class.java /* Stop at */
)
private fun findElementToInjectWithComment(host: KtElement): KtExpression? {
val parentBlockExpression = PsiTreeUtil.getParentOfType(
host,
KtBlockExpression::class.java,
true, /* strict */
KtDeclaration::class.java /* Stop at */
) ?: return null
return parentBlockExpression.statements.firstOrNull { statement ->
PsiTreeUtil.isAncestor(statement, host, false) && checkIsValidPlaceForInjectionWithLineComment(statement, host)
}
}
private fun addInjectionInstructionInCode(language: Language, host: PsiLanguageInjectionHost): Boolean {
val ktHost = host as? KtElement ?: return false
val project = ktHost.project
// Find the place where injection can be stated with annotation or comment
val modifierListOwner = findElementToInjectWithAnnotation(ktHost)
if (modifierListOwner != null && canInjectWithAnnotation(ktHost)) {
project.executeWriteCommand(KotlinJvmBundle.message("command.action.add.injection.annotation")) {
modifierListOwner.addAnnotation(FqName(AnnotationUtil.LANGUAGE), "\"${language.id}\"")
}
return true
}
// Find the place where injection can be done with one-line comment
val commentBeforeAnchor: PsiElement =
modifierListOwner?.firstNonCommentChild() ?: findElementToInjectWithComment(ktHost) ?: return false
val psiFactory = KtPsiFactory(project)
val injectComment = psiFactory.createComment("//language=" + language.id)
project.executeWriteCommand(KotlinJvmBundle.message("command.action.add.injection.comment")) {
commentBeforeAnchor.parent.addBefore(injectComment, commentBeforeAnchor)
}
return true
}
// Inspired with InjectorUtils.findCommentInjection()
private fun checkIsValidPlaceForInjectionWithLineComment(statement: KtExpression, host: KtElement): Boolean {
// make sure comment is close enough and ...
val statementStartOffset = statement.startOffset
val hostStart = host.startOffset
if (hostStart < statementStartOffset || hostStart - statementStartOffset > 120) {
return false
}
if (hostStart - statementStartOffset > 2) {
// ... there's no non-empty valid host in between comment and e2
if (prevWalker(host, statement).asSequence().takeWhile { it != null }.any {
it is PsiLanguageInjectionHost && it.isValidHost && !StringUtil.isEmptyOrSpaces(it.text)
}
) return false
}
return true
}
private fun PsiElement.firstNonCommentChild(): PsiElement? =
firstChild.siblings().dropWhile { it is PsiComment || it is PsiWhiteSpace }.firstOrNull()
// Based on InjectorUtils.prevWalker
private fun prevWalker(element: PsiElement, scope: PsiElement): Iterator<PsiElement?> {
return object : Iterator<PsiElement?> {
private var e: PsiElement? = element
override fun hasNext(): Boolean = true
override fun next(): PsiElement? {
val current = e
if (current == null || current === scope) return null
val prev = current.prevSibling
e = if (prev != null) {
getDeepestLast(prev)
} else {
val parent = current.parent
if (parent === scope || parent is PsiFile) null else parent
}
return e
}
}
}
| apache-2.0 | 84cfc4f62dc160fac8bf8b2cef892f6d | 40.693227 | 158 | 0.737793 | 5.355681 | false | false | false | false |
ogarcia/ultrasonic | core/subsonic-api/src/main/kotlin/org/moire/ultrasonic/api/subsonic/interceptors/RangeHeaderInterceptor.kt | 2 | 1759 | package org.moire.ultrasonic.api.subsonic.interceptors
import java.util.concurrent.TimeUnit.MILLISECONDS
import okhttp3.Interceptor
import okhttp3.Interceptor.Chain
import okhttp3.Response
internal const val SOCKET_READ_TIMEOUT_DOWNLOAD = 30 * 1000
// Allow 20 seconds extra timeout pear MB offset.
internal const val TIMEOUT_MILLIS_PER_OFFSET_BYTE = 0.02
/**
* Modifies request "Range" header to be according to HTTP standard.
*
* Also increases read timeout to allow server to transcode response and offset it.
*
* See [range rfc](https://tools.ietf.org/html/rfc7233).
*/
internal class RangeHeaderInterceptor : Interceptor {
override fun intercept(chain: Chain): Response {
val originalRequest = chain.request()
val headers = originalRequest.headers()
return if (headers.names().contains("Range")) {
val offsetValue = headers["Range"] ?: "0"
val offset = "bytes=$offsetValue-"
chain.withReadTimeout(getReadTimeout(offsetValue.toInt()), MILLISECONDS)
.proceed(
originalRequest.newBuilder()
.removeHeader("Range").addHeader("Range", offset)
.build()
)
} else {
chain.proceed(originalRequest)
}
}
// Set socket read timeout. Note: The timeout increases as the offset gets larger. This is
// to avoid the thrashing effect seen when offset is combined with transcoding/downsampling
// on the server. In that case, the server uses a long time before sending any data,
// causing the client to time out.
private fun getReadTimeout(offset: Int) =
(SOCKET_READ_TIMEOUT_DOWNLOAD + offset * TIMEOUT_MILLIS_PER_OFFSET_BYTE).toInt()
}
| gpl-3.0 | 88bf62bf82c6401d221dc6044c8b9ec9 | 39.906977 | 95 | 0.671973 | 4.533505 | false | false | false | false |
cdietze/klay | tripleklay/src/main/kotlin/tripleklay/ui/Style.kt | 1 | 13084 | package tripleklay.ui
import klay.core.Canvas
import klay.core.Font
import klay.core.Sound
import klay.core.TextBlock
import tripleklay.ui.Style.Binding
import tripleklay.util.EffectRenderer
import tripleklay.util.EffectRenderer.Gradient
import tripleklay.util.TextStyle
/**
* Defines style properties for interface elements. Some style properties are inherited, such that
* a property not specified in a leaf element will be inherited by the nearest parent for which the
* property is specified. Other style properties are not inherited, and a default value will be
* used in cases where a leaf element lacks a property. The documentation for each style property
* indicates whether or not it is inherited.
*/
abstract class Style<out V> protected constructor(
/** Indicates whether or not this style property is inherited. */
val inherited: Boolean) {
/** Defines element modes which can be used to modify an element's styles. */
enum class Mode(
/** Whether the element is enabled in this mode. */
val enabled: Boolean,
/** Whether the element is selected in this mode. */
val selected: Boolean) {
DEFAULT(true, false),
DISABLED(false, false),
SELECTED(true, true),
DISABLED_SELECTED(false, true)
}
/** Used to configure [Styles] instances. See [Styles.add]. */
class Binding<out V>(
/** The style being configured. */
val style: Style<V>,
/** The value to be bound for the style. */
val value: V)
/** Defines horizontal alignment choices. */
enum class HAlign {
LEFT {
override fun offset(size: Float, extent: Float): Float {
return 0f
}
},
RIGHT {
override fun offset(size: Float, extent: Float): Float {
return extent - size
}
},
CENTER {
override fun offset(size: Float, extent: Float): Float {
return (extent - size) / 2
}
};
abstract fun offset(size: Float, extent: Float): Float
}
/** Defines vertical alignment choices. */
enum class VAlign {
TOP {
override fun offset(size: Float, extent: Float): Float {
return 0f
}
},
BOTTOM {
override fun offset(size: Float, extent: Float): Float {
return extent - size
}
},
CENTER {
override fun offset(size: Float, extent: Float): Float {
return (extent - size) / 2
}
};
abstract fun offset(size: Float, extent: Float): Float
}
/** Defines icon position choices. */
enum class Pos {
LEFT, ABOVE, RIGHT, BELOW;
/** Tests if this position is left or right. */
fun horizontal(): Boolean {
return this == LEFT || this == RIGHT
}
}
/** Used to create text effects. */
interface EffectFactory {
/** Creates the effect renderer to be used by this factory. */
fun createEffectRenderer(elem: Element<*>): EffectRenderer
}
/** Defines supported text effects. */
enum class TextEffect : EffectFactory {
/** Outlines the text in the highlight color. */
PIXEL_OUTLINE {
override fun createEffectRenderer(elem: Element<*>): EffectRenderer {
return EffectRenderer.PixelOutline(Styles.resolveStyle(elem, Style.HIGHLIGHT))
}
},
/** Outlines the text in the highlight color. */
VECTOR_OUTLINE {
override fun createEffectRenderer(elem: Element<*>): EffectRenderer {
return EffectRenderer.VectorOutline(
Styles.resolveStyle(elem, Style.HIGHLIGHT),
Styles.resolveStyle(elem, Style.OUTLINE_WIDTH),
Styles.resolveStyle(elem, Style.OUTLINE_CAP),
Styles.resolveStyle(elem, Style.OUTLINE_JOIN))
}
},
/** Draws a shadow below and to the right of the text in the shadow color. */
SHADOW {
override fun createEffectRenderer(elem: Element<*>): EffectRenderer {
return EffectRenderer.Shadow(Styles.resolveStyle(elem, Style.SHADOW),
Styles.resolveStyle(elem, Style.SHADOW_X),
Styles.resolveStyle(elem, Style.SHADOW_Y))
}
},
/** Draws a gradient from the font color to the gradient color. */
GRADIENT {
override fun createEffectRenderer(elem: Element<*>): EffectRenderer {
return Gradient(Styles.resolveStyle(elem, Style.GRADIENT_COLOR),
Styles.resolveStyle(elem, Style.GRADIENT_TYPE))
}
},
/** No text effect. */
NONE {
override fun createEffectRenderer(elem: Element<*>): EffectRenderer {
return EffectRenderer.NONE
}
}
}
/** Used to provide concise HAlign style declarations. */
class HAlignStyle internal constructor() : Style<HAlign>(false) {
val left = `is`(HAlign.LEFT)
val right = `is`(HAlign.RIGHT)
val center = `is`(HAlign.CENTER)
override fun getDefault(elem: Element<*>): HAlign {
return HAlign.CENTER
}
}
/** Used to provide concise VAlign style declarations. */
class VAlignStyle internal constructor() : Style<VAlign>(false) {
val top = `is`(VAlign.TOP)
val bottom = `is`(VAlign.BOTTOM)
val center = `is`(VAlign.CENTER)
override fun getDefault(elem: Element<*>): VAlign {
return VAlign.CENTER
}
}
/** Used to provide concise Pos style declarations. */
class PosStyle internal constructor() : Style<Pos>(false) {
val left = `is`(Pos.LEFT)
val above = `is`(Pos.ABOVE)
val right = `is`(Pos.RIGHT)
val below = `is`(Pos.BELOW)
override fun getDefault(elem: Element<*>): Pos {
return Pos.LEFT
}
}
/** Used to provide concise TextEffect style declarations. */
class TextEffectStyle internal constructor() : Style<EffectFactory>(true) {
val pixelOutline = `is`(TextEffect.PIXEL_OUTLINE)
val vectorOutline = `is`(TextEffect.VECTOR_OUTLINE)
val shadow = `is`(TextEffect.SHADOW)
val gradient = `is`(TextEffect.GRADIENT)
val none = `is`(TextEffect.NONE)
fun `is`(renderer: EffectRenderer): Binding<EffectFactory> {
return `is`(object : EffectFactory {
override fun createEffectRenderer(elem: Element<*>): EffectRenderer {
return renderer
}
})
}
override fun getDefault(elem: Element<*>): EffectFactory {
return TextEffect.NONE
}
}
class GradientTypeStyle internal constructor() : Style<Gradient.Type>(true) {
val bottom: Binding<Gradient.Type> = `is`(Gradient.Type.BOTTOM)
val top: Binding<Gradient.Type> = `is`(Gradient.Type.TOP)
val center: Binding<Gradient.Type> = `is`(Gradient.Type.CENTER)
override fun getDefault(elem: Element<*>): Gradient.Type {
return Gradient.Type.BOTTOM
}
}
/** A Boolean style, with convenient members for on and off bindings. */
class Flag(inherited: Boolean, private val _default: Boolean) : Style<Boolean>(inherited) {
val off = `is`(false)
val on = `is`(true)
override fun getDefault(mode: Element<*>): Boolean {
return _default
}
}
/**
* Returns the default value for this style for the supplied element.
*/
abstract fun getDefault(mode: Element<*>): V
companion object {
/** The foreground color for an element. Inherited. */
val COLOR: Style<Int> = object : Style<Int>(true) {
override fun getDefault(elem: Element<*>): Int {
return if (elem.isEnabled) 0xFF000000.toInt() else 0xFF666666.toInt()
}
}
/** The highlight color for an element. Inherited. */
val HIGHLIGHT: Style<Int> = object : Style<Int>(true) {
override fun getDefault(elem: Element<*>): Int {
return if (elem.isEnabled) 0xAAFFFFFF.toInt() else 0xAACCCCCC.toInt()
}
}
/** The shadow color for an element. Inherited. */
val SHADOW = newStyle(true, 0x55000000)
/** The shadow offset in pixels. Inherited. */
val SHADOW_X = newStyle(true, 2f)
/** The shadow offset in pixels. Inherited. */
val SHADOW_Y = newStyle(true, 2f)
/** The color of the gradient. Inherited. */
val GRADIENT_COLOR = newStyle(true, 0xFFC70000.toInt())
/** The type of gradient. Inherited. */
val GRADIENT_TYPE = GradientTypeStyle()
/** The stroke width of the outline, when using a vector outline. */
val OUTLINE_WIDTH = newStyle(true, 1f)
/** The line cap for the outline, when using a vector outline. */
val OUTLINE_CAP: Style<Canvas.LineCap> = newStyle(true, Canvas.LineCap.ROUND)
/** The line join for the outline, when using a vector outline. */
val OUTLINE_JOIN: Style<Canvas.LineJoin> = newStyle(true, Canvas.LineJoin.ROUND)
/** The horizontal alignment of an element. Not inherited. */
val HALIGN = HAlignStyle()
/** The vertical alignment of an element. Not inherited. */
val VALIGN = VAlignStyle()
/** The font used to render text. Inherited. */
val FONT = newStyle(true, Font("Helvetica", 16f))
/** Whether or not to allow text to wrap. When text cannot wrap and does not fit into the
* allowed space, it is truncated. Not inherited. */
val TEXT_WRAP = newFlag(false, false)
/** The effect to use when rendering text, if any. Inherited. */
val TEXT_EFFECT = TextEffectStyle()
/** Whether or not to underline text. Inherited. */
val UNDERLINE = newFlag(true, false)
/** Whether or not to automatically shrink a text widget's font size until it fits into the
* horizontal space it has been allotted. Cannot be used with [.TEXT_WRAP]. Not
* inherited. */
val AUTO_SHRINK = newFlag(false, false)
/** The background for an element. Not inherited. */
val BACKGROUND = newStyle(false, Background.blank())
/** The position relative to the text to render an icon for labels, buttons, etc. */
val ICON_POS = PosStyle()
/** The gap between the icon and text in labels, buttons, etc. */
val ICON_GAP = newStyle(false, 2)
/** If true, the icon is cuddled to the text, with extra space between icon and border, if
* false, the icon is placed next to the border with extra space between icon and label. */
val ICON_CUDDLE = newFlag(false, false)
/** The effect to apply to the icon. */
val ICON_EFFECT = newStyle(false, IconEffect.NONE)
/** The sound to be played when this element's action is triggered. */
val ACTION_SOUND = newStyle<Sound?>(false, null)
/**
* Creates a text style instance based on the supplied element's stylings.
*/
fun createTextStyle(elem: Element<*>): TextStyle {
return TextStyle(
Styles.resolveStyle(elem, Style.FONT),
Styles.resolveStyle(elem, Style.TEXT_EFFECT) !== TextEffect.PIXEL_OUTLINE,
Styles.resolveStyle(elem, Style.COLOR),
Styles.resolveStyle(elem, Style.TEXT_EFFECT).createEffectRenderer(elem),
Styles.resolveStyle(elem, Style.UNDERLINE))
}
/**
* Creates a style identifier with the supplied properties.
*/
fun <V> newStyle(inherited: Boolean, defaultValue: V): Style<V> {
return object : Style<V>(inherited) {
override fun getDefault(elem: Element<*>): V {
return defaultValue
}
}
}
/**
* Creates a boolean style identifier with the supplied properties.
*/
fun newFlag(inherited: Boolean, defaultValue: Boolean): Flag {
return Flag(inherited, defaultValue)
}
fun toAlignment(align: HAlign): TextBlock.Align {
when (align) {
Style.HAlign.LEFT -> return TextBlock.Align.LEFT
Style.HAlign.RIGHT -> return TextBlock.Align.RIGHT
Style.HAlign.CENTER -> return TextBlock.Align.CENTER
}
}
}
}
/**
* Returns a [Binding] with this style bound to the specified value.
* This is an extension function to support V's out variance.
*/
fun <V> Style<V>.`is`(value: V): Binding<V> {
return Binding(this, value)
}
| apache-2.0 | 38e1f10bbf662e86bedadf83906b592e | 37.25731 | 100 | 0.58797 | 4.716655 | false | false | false | false |
michaelbull/kotlin-result | kotlin-result/src/commonMain/kotlin/com/github/michaelbull/result/Iterable.kt | 1 | 9519 | package com.github.michaelbull.result
/**
* Accumulates value starting with [initial] value and applying [operation] from left to right to
* current accumulator value and each element.
*/
public inline fun <T, R, E> Iterable<T>.fold(initial: R, operation: (acc: R, T) -> Result<R, E>): Result<R, E> {
var accumulator = initial
for (element in this) {
accumulator = when (val result = operation(accumulator, element)) {
is Ok -> result.value
is Err -> return Err(result.error)
}
}
return Ok(accumulator)
}
/**
* Accumulates value starting with [initial] value and applying [operation] from right to left to
* each element and current accumulator value.
*/
public inline fun <T, R, E> List<T>.foldRight(initial: R, operation: (T, acc: R) -> Result<R, E>): Result<R, E> {
var accumulator = initial
if (!isEmpty()) {
val iterator = listIterator(size)
while (iterator.hasPrevious()) {
accumulator = when (val result = operation(iterator.previous(), accumulator)) {
is Ok -> result.value
is Err -> return Err(result.error)
}
}
}
return Ok(accumulator)
}
/**
* Combines a vararg of [Results][Result] into a single [Result] (holding a [List]).
*
* - Elm: [Result.Extra.combine](http://package.elm-lang.org/packages/elm-community/result-extra/2.2.0/Result-Extra#combine)
*/
public fun <V, E> combine(vararg results: Result<V, E>): Result<List<V>, E> {
return results.asIterable().combine()
}
/**
* Combines an [Iterable] of [Results][Result] into a single [Result] (holding a [List]).
*
* - Elm: [Result.Extra.combine](http://package.elm-lang.org/packages/elm-community/result-extra/2.2.0/Result-Extra#combine)
*/
public fun <V, E> Iterable<Result<V, E>>.combine(): Result<List<V>, E> {
return Ok(map {
when (it) {
is Ok -> it.value
is Err -> return it
}
})
}
/**
* Extracts from a vararg of [Results][Result] all the [Ok] elements. All the [Ok] elements are
* extracted in order.
*
* - Haskell: [Data.Either.lefts](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html#v:lefts)
*/
public fun <V, E> getAll(vararg results: Result<V, E>): List<V> {
return results.asIterable().getAll()
}
/**
* Extracts from an [Iterable] of [Results][Result] all the [Ok] elements. All the [Ok] elements
* are extracted in order.
*
* - Haskell: [Data.Either.lefts](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html#v:lefts)
*/
public fun <V, E> Iterable<Result<V, E>>.getAll(): List<V> {
return filterIsInstance<Ok<V>>().map { it.value }
}
/**
* Extracts from a vararg of [Results][Result] all the [Err] elements. All the [Err] elements are
* extracted in order.
*
* - Haskell: [Data.Either.rights](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html#v:rights)
*/
public fun <V, E> getAllErrors(vararg results: Result<V, E>): List<E> = results.asIterable().getAllErrors()
/**
* Extracts from an [Iterable] of [Results][Result] all the [Err] elements. All the [Err] elements
* are extracted in order.
*
* - Haskell: [Data.Either.rights](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html#v:rights)
*/
public fun <V, E> Iterable<Result<V, E>>.getAllErrors(): List<E> {
return filterIsInstance<Err<E>>().map { it.error }
}
/**
* Partitions a vararg of [Results][Result] into a [Pair] of [Lists][List]. All the [Ok] elements
* are extracted, in order, to the [first][Pair.first] value. Similarly the [Err] elements are
* extracted to the [Pair.second] value.
*
* - Haskell: [Data.Either.partitionEithers](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html#v:partitionEithers)
*/
public fun <V, E> partition(vararg results: Result<V, E>): Pair<List<V>, List<E>> {
return results.asIterable().partition()
}
/**
* Partitions an [Iterable] of [Results][Result] into a [Pair] of [Lists][List]. All the [Ok]
* elements are extracted, in order, to the [first][Pair.first] value. Similarly the [Err] elements
* are extracted to the [Pair.second] value.
*
* - Haskell: [Data.Either.partitionEithers](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html#v:partitionEithers)
*/
public fun <V, E> Iterable<Result<V, E>>.partition(): Pair<List<V>, List<E>> {
val values = mutableListOf<V>()
val errors = mutableListOf<E>()
forEach { result ->
when (result) {
is Ok -> values.add(result.value)
is Err -> errors.add(result.error)
}
}
return Pair(values, errors)
}
/**
* Returns a [Result<List<U>, E>][Result] containing the results of applying the given [transform]
* function to each element in the original collection, returning early with the first [Err] if a
* transformation fails.
*/
public inline fun <V, E, U> Iterable<V>.mapResult(
transform: (V) -> Result<U, E>
): Result<List<U>, E> {
return Ok(map { element ->
when (val transformed = transform(element)) {
is Ok -> transformed.value
is Err -> return transformed
}
})
}
/**
* Applies the given [transform] function to each element of the original collection and appends
* the results to the given [destination], returning early with the first [Err] if a
* transformation fails.
*/
public inline fun <V, E, U, C : MutableCollection<in U>> Iterable<V>.mapResultTo(
destination: C,
transform: (V) -> Result<U, E>
): Result<C, E> {
return Ok(mapTo(destination) { element ->
when (val transformed = transform(element)) {
is Ok -> transformed.value
is Err -> return transformed
}
})
}
/**
* Returns a [Result<List<U>, E>][Result] containing only the non-null results of applying the
* given [transform] function to each element in the original collection, returning early with the
* first [Err] if a transformation fails.
*/
public inline fun <V, E, U : Any> Iterable<V>.mapResultNotNull(
transform: (V) -> Result<U, E>?
): Result<List<U>, E> {
return Ok(mapNotNull { element ->
when (val transformed = transform(element)) {
is Ok -> transformed.value
is Err -> return transformed
null -> null
}
})
}
/**
* Applies the given [transform] function to each element in the original collection and appends
* only the non-null results to the given [destination], returning early with the first [Err] if a
* transformation fails.
*/
public inline fun <V, E, U : Any, C : MutableCollection<in U>> Iterable<V>.mapResultNotNullTo(
destination: C,
transform: (V) -> Result<U, E>?
): Result<C, E> {
return Ok(mapNotNullTo(destination) { element ->
when (val transformed = transform(element)) {
is Ok -> transformed.value
is Err -> return transformed
null -> null
}
})
}
/**
* Returns a [Result<List<U>, E>][Result] containing the results of applying the given [transform]
* function to each element and its index in the original collection, returning early with the
* first [Err] if a transformation fails.
*/
public inline fun <V, E, U> Iterable<V>.mapResultIndexed(
transform: (index: Int, V) -> Result<U, E>
): Result<List<U>, E> {
return Ok(mapIndexed { index, element ->
when (val transformed = transform(index, element)) {
is Ok -> transformed.value
is Err -> return transformed
}
})
}
/**
* Applies the given [transform] function to each element and its index in the original collection
* and appends the results to the given [destination], returning early with the first [Err] if a
* transformation fails.
*/
public inline fun <V, E, U, C : MutableCollection<in U>> Iterable<V>.mapResultIndexedTo(
destination: C,
transform: (index: Int, V) -> Result<U, E>
): Result<C, E> {
return Ok(mapIndexedTo(destination) { index, element ->
when (val transformed = transform(index, element)) {
is Ok -> transformed.value
is Err -> return transformed
}
})
}
/**
* Returns a [Result<List<U>, E>][Result] containing only the non-null results of applying the
* given [transform] function to each element and its index in the original collection, returning
* early with the first [Err] if a transformation fails.
*/
public inline fun <V, E, U : Any> Iterable<V>.mapResultIndexedNotNull(
transform: (index: Int, V) -> Result<U, E>?
): Result<List<U>, E> {
return Ok(mapIndexedNotNull { index, element ->
when (val transformed = transform(index, element)) {
is Ok -> transformed.value
is Err -> return transformed
null -> null
}
})
}
/**
* Applies the given [transform] function to each element and its index in the original collection
* and appends only the non-null results to the given [destination], returning early with the first
* [Err] if a transformation fails.
*/
public inline fun <V, E, U : Any, C : MutableCollection<in U>> Iterable<V>.mapResultIndexedNotNullTo(
destination: C,
transform: (index: Int, V) -> Result<U, E>?
): Result<C, E> {
return Ok(mapIndexedNotNullTo(destination) { index, element ->
when (val transformed = transform(index, element)) {
is Ok -> transformed.value
is Err -> return transformed
null -> null
}
})
}
| isc | 8e57ad53b35ee2f5e716178cb5e21cd3 | 34.651685 | 136 | 0.64345 | 3.649923 | false | false | false | false |
kohry/gorakgarakANPR | app/src/main/java/com/gorakgarak/anpr/parser/GorakgarakXMLParser.kt | 1 | 4114 | package com.gorakgarak.anpr.parser
import org.xmlpull.v1.XmlPullParser
import android.util.Xml
import org.opencv.core.CvType
import org.opencv.core.Mat
import org.xmlpull.v1.XmlPullParserException
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import java.util.*
/**
* Created by kohry on 2017-10-22.
*/
object GorakgarakXMLParser {
private val namespace: String? = null
@Throws(XmlPullParserException::class, IOException::class)
fun parse(inputStream: InputStream, trainingDataTagName: String): Pair<Mat, Mat> {
try {
val parser = Xml.newPullParser()
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false)
parser.setInput(inputStream, null)
parser.nextTag()
parser.require(XmlPullParser.START_TAG, namespace, "opencv_storage")
return Pair(readFeed(parser, trainingDataTagName), readFeed(parser, "classes"))
} finally {
inputStream.close()
}
}
@Throws(XmlPullParserException::class, IOException::class)
private fun readFeed(parser: XmlPullParser, tagName:String): Mat {
var mat = Mat() //you have to initialize opencv first, before loading this.
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.eventType != XmlPullParser.START_TAG) {
continue
}
val name = parser.name
// Starts by looking for the entry tag
if (name == tagName) {
mat = readEntry(parser, tagName)
break
} else {
skip(parser)
}
}
return mat
}
@Throws(XmlPullParserException::class, IOException::class)
private fun readEntry(parser: XmlPullParser, entryName: String): Mat {
parser.require(XmlPullParser.START_TAG, namespace, entryName)
var rows = 0
var cols = 0
var dt = ""
var data = ""
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.eventType != XmlPullParser.START_TAG) {
continue
}
val name = parser.name
when (name) {
"rows" -> rows = readNode(parser, "rows").toInt()
"cols" -> cols = readNode(parser, "cols").toInt()
"dt" -> dt = readNode(parser, "dt")
"data" -> { data = readNode(parser, "data") }
else -> skip(parser)
}
}
var imageType = CvType.CV_32F
if (dt == "f") imageType = CvType.CV_32F else if(dt == "i") imageType = CvType.CV_32S
val mat = Mat(rows, cols, imageType)
val st = StringTokenizer(data)
(0 until rows).forEach { row ->
(0 until cols).forEach { col ->
if (dt == "f") mat.put(row, col, floatArrayOf(st.nextToken().toFloat()))
else if (dt == "i") mat.put(row, col, intArrayOf(st.nextToken().toInt()))
}
}
return mat
}
@Throws(IOException::class, XmlPullParserException::class)
private fun readNode(parser: XmlPullParser, name: String): String {
parser.require(XmlPullParser.START_TAG, namespace, name)
val title = readText(parser)
parser.require(XmlPullParser.END_TAG, namespace, name)
return title
}
@Throws(IOException::class, XmlPullParserException::class)
private fun readText(parser: XmlPullParser): String {
var result = ""
if (parser.next() == XmlPullParser.TEXT) {
result = parser.text
parser.nextTag()
}
return result
}
@Throws(XmlPullParserException::class, IOException::class)
private fun skip(parser: XmlPullParser) {
if (parser.eventType != XmlPullParser.START_TAG) {
throw IllegalStateException()
}
var depth = 1
while (depth != 0) {
when (parser.next()) {
XmlPullParser.END_TAG -> depth--
XmlPullParser.START_TAG -> depth++
}
}
}
} | mit | 617712c013d1730430bcc9053e4e63fe | 31.401575 | 93 | 0.577783 | 4.437972 | false | false | false | false |
AfzalivE/AwakeDebug | app/src/main/java/com/afzaln/awakedebug/data/Prefs.kt | 1 | 3127 | package com.afzaln.awakedebug.data
import android.content.SharedPreferences
import androidx.preference.PreferenceManager
import com.afzaln.awakedebug.DebuggingType
import com.afzaln.awakedebug.AwakeDebugApp
import timber.log.Timber
private const val KEY_USB_DEBUG_ENABLED = "UsbDebugEnabled"
private const val KEY_WIFI_DEBUG_ENABLED = "WifiDebugEnabled"
private const val KEY_AWAKE_DEBUG_ENABLED = "AwakeDebugEnabled"
private const val KEY_AWAKE_DEBUG_ACTIVE = "AwakeDebugActive"
private const val KEY_DISPLAY_TIMEOUT = "DisplayTimeout"
/**
* Responsible for keeping user choices for
* Awake Debug setting and the last system
* display timeout, for restoring.
*
* Created by Dmytro Karataiev on 3/29/17.
*/
class Prefs(val app: AwakeDebugApp) {
private val preferences: SharedPreferences
get() = PreferenceManager.getDefaultSharedPreferences(app)
val enabledDebuggingTypes: List<DebuggingType>
get() {
return arrayListOf<DebuggingType>().apply {
if (usbDebugging) add(DebuggingType.USB)
if (wifiDebugging) add(DebuggingType.WIFI)
}
}
var usbDebugging: Boolean
get() {
val usbDebugging = preferences.getBoolean(KEY_USB_DEBUG_ENABLED, true)
Timber.d("$KEY_USB_DEBUG_ENABLED: %s", usbDebugging)
return usbDebugging
}
set(value) {
Timber.d("Setting $KEY_USB_DEBUG_ENABLED: %s", value)
preferences.edit().putBoolean(KEY_USB_DEBUG_ENABLED, value).apply()
}
var wifiDebugging: Boolean
get() {
val usbDebugging = preferences.getBoolean(KEY_WIFI_DEBUG_ENABLED, true)
Timber.d("$KEY_WIFI_DEBUG_ENABLED: %s", usbDebugging)
return usbDebugging
}
set(value) {
Timber.d("Setting $KEY_WIFI_DEBUG_ENABLED: %s", value)
preferences.edit().putBoolean(KEY_WIFI_DEBUG_ENABLED, value).apply()
}
var awakeDebug: Boolean
get() {
val awakeDebugEnabled = preferences.getBoolean(KEY_AWAKE_DEBUG_ENABLED, false)
Timber.d("$KEY_AWAKE_DEBUG_ENABLED: %s", awakeDebugEnabled)
return awakeDebugEnabled
}
set(value) {
Timber.d("Setting $KEY_AWAKE_DEBUG_ENABLED: %s", value)
preferences.edit().putBoolean(KEY_AWAKE_DEBUG_ENABLED, value).apply()
}
var awakeDebugActive: Boolean
get() {
val awakeDebugActive = preferences.getBoolean(KEY_AWAKE_DEBUG_ACTIVE, false)
Timber.d("$KEY_AWAKE_DEBUG_ACTIVE: %s", awakeDebugActive)
return awakeDebugActive
}
set(value) {
Timber.d("Setting $KEY_AWAKE_DEBUG_ACTIVE: %s", value)
preferences.edit().putBoolean(KEY_AWAKE_DEBUG_ACTIVE, value).apply()
}
var savedTimeout: Int
get() {
return preferences.getInt(KEY_DISPLAY_TIMEOUT, 60000)
}
set(value) {
Timber.d("Setting $KEY_DISPLAY_TIMEOUT = %s", value)
preferences.edit().putInt(KEY_DISPLAY_TIMEOUT, value).apply()
}
}
| apache-2.0 | 933b9e5cbe49b87fbb11a01ba315ecbd | 35.360465 | 90 | 0.639271 | 4.313103 | false | false | false | false |
apache/isis | incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/snapshots/simpleapp1_16_0/RESTFUL_SERVICES.kt | 2 | 4987 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.causeway.client.kroviz.snapshots.simpleapp1_16_0
import org.apache.causeway.client.kroviz.snapshots.Response
// ResultListList.kt
object RESTFUL_SERVICES : Response() {
override val url = "http://localhost:8080/restful/services"
override val str = """
{
"value": [
{
"rel": "urn:org.restfulobjects:rels/serviceserviceId=\"simple.SimpleObjectMenu\"",
"href": "http://localhost:8080/restful/services/simple.SimpleObjectMenu",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "Simple Objects"
},
{
"rel": "urn:org.restfulobjects:rels/serviceserviceId=\"causewayApplib.FixtureScriptsDefault\"",
"href": "http://localhost:8080/restful/services/causewayApplib.FixtureScriptsDefault",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "Prototyping"
},
{
"rel": "urn:org.restfulobjects:rels/serviceserviceId=\"causewayApplib.LayoutServiceMenu\"",
"href": "http://localhost:8080/restful/services/causewayApplib.LayoutServiceMenu",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "Prototyping"
},
{
"rel": "urn:org.restfulobjects:rels/serviceserviceId=\"causewayApplib.MetaModelServicesMenu\"",
"href": "http://localhost:8080/restful/services/causewayApplib.MetaModelServicesMenu",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "Prototyping"
},
{
"rel": "urn:org.restfulobjects:rels/serviceserviceId=\"causewayApplib.SwaggerServiceMenu\"",
"href": "http://localhost:8080/restful/services/causewayApplib.SwaggerServiceMenu",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "Prototyping"
},
{
"rel": "urn:org.restfulobjects:rels/serviceserviceId=\"causewayApplib.TranslationServicePoMenu\"",
"href": "http://localhost:8080/restful/services/causewayApplib.TranslationServicePoMenu",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "Prototyping"
},
{
"rel": "urn:org.restfulobjects:rels/serviceserviceId=\"causewayApplib.HsqlDbManagerMenu\"",
"href": "http://localhost:8080/restful/services/causewayApplib.HsqlDbManagerMenu",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "Prototyping"
},
{
"rel": "urn:org.restfulobjects:rels/serviceserviceId=\"causewayApplib.ConfigurationServiceMenu\"",
"href": "http://localhost:8080/restful/services/causewayApplib.ConfigurationServiceMenu",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "Configuration Service Menu"
}
],
"extensions": {},
"links": [
{
"rel": "self",
"href": "http://localhost:8080/restful/services",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/list\""
},
{
"rel": "up",
"href": "http://localhost:8080/restful/",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/homepage\""
}
]
}"""
}
| apache-2.0 | eb3599081db18035b794c0148428f167 | 47.892157 | 114 | 0.584921 | 4.735992 | false | false | false | false |
allotria/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/impl/LineStatusTrackerManager.kt | 2 | 46737 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.impl
import com.google.common.collect.HashMultiset
import com.google.common.collect.Multiset
import com.intellij.codeWithMe.ClientId
import com.intellij.diagnostic.ThreadDumper
import com.intellij.icons.AllIcons
import com.intellij.notification.Notification
import com.intellij.notification.NotificationAction
import com.intellij.notification.NotificationType
import com.intellij.notification.NotificationsManager
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.*
import com.intellij.openapi.command.CommandEvent
import com.intellij.openapi.command.CommandListener
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.editor.event.EditorFactoryEvent
import com.intellij.openapi.editor.event.EditorFactoryListener
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.util.BackgroundTaskUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.*
import com.intellij.openapi.vcs.changes.*
import com.intellij.openapi.vcs.changes.conflicts.ChangelistConflictFileStatusProvider
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.LOCAL_CHANGES
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.getToolWindowFor
import com.intellij.openapi.vcs.checkin.CheckinHandler
import com.intellij.openapi.vcs.checkin.CheckinHandlerFactory
import com.intellij.openapi.vcs.ex.*
import com.intellij.openapi.vcs.history.VcsRevisionNumber
import com.intellij.openapi.vcs.impl.LineStatusTrackerContentLoader.ContentInfo
import com.intellij.openapi.vcs.impl.LineStatusTrackerContentLoader.TrackerContent
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.openapi.vfs.newvfs.events.VFileMoveEvent
import com.intellij.openapi.vfs.newvfs.events.VFilePropertyChangeEvent
import com.intellij.testFramework.LightVirtualFile
import com.intellij.util.EventDispatcher
import com.intellij.util.concurrency.Semaphore
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.ui.UIUtil
import com.intellij.vcs.commit.isNonModalCommit
import com.intellij.vcsUtil.VcsUtil
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.CalledInAny
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.TestOnly
import java.nio.charset.Charset
import java.util.*
import java.util.concurrent.Future
import java.util.function.Supplier
class LineStatusTrackerManager(private val project: Project) : LineStatusTrackerManagerI, Disposable {
private val LOCK = Any()
private var isDisposed = false
private val trackers = HashMap<Document, TrackerData>()
private val forcedDocuments = HashMap<Document, Multiset<Any>>()
private val eventDispatcher = EventDispatcher.create(Listener::class.java)
private var partialChangeListsEnabled: Boolean = false
private val documentsInDefaultChangeList = HashSet<Document>()
private var clmFreezeCounter: Int = 0
private val filesWithDamagedInactiveRanges = HashSet<VirtualFile>()
private val fileStatesAwaitingRefresh = HashMap<VirtualFile, ChangelistsLocalLineStatusTracker.State>()
private val loader = MyBaseRevisionLoader()
companion object {
private val LOG = Logger.getInstance(LineStatusTrackerManager::class.java)
@JvmStatic
fun getInstance(project: Project): LineStatusTrackerManagerI = project.service()
@JvmStatic
fun getInstanceImpl(project: Project): LineStatusTrackerManager {
return getInstance(project) as LineStatusTrackerManager
}
}
class MyStartupActivity : VcsStartupActivity {
override fun runActivity(project: Project) {
LineStatusTrackerManager.getInstanceImpl(project).startListenForEditors()
}
override fun getOrder(): Int = VcsInitObject.OTHER_INITIALIZATION.order
}
private fun startListenForEditors() {
val busConnection = project.messageBus.connect()
busConnection.subscribe(LineStatusTrackerSettingListener.TOPIC, MyLineStatusTrackerSettingListener())
busConnection.subscribe(VcsFreezingProcess.Listener.TOPIC, MyFreezeListener())
busConnection.subscribe(CommandListener.TOPIC, MyCommandListener())
busConnection.subscribe(ChangeListListener.TOPIC, MyChangeListListener())
busConnection.subscribe(ChangeListAvailabilityListener.TOPIC, MyChangeListAvailabilityListener())
ApplicationManager.getApplication().messageBus.connect(this)
.subscribe(VirtualFileManager.VFS_CHANGES, MyVirtualFileListener())
LocalLineStatusTrackerProvider.EP_NAME.addChangeListener(Runnable { updateTrackingSettings() }, this)
updatePartialChangeListsAvailability()
runInEdt {
if (project.isDisposed) return@runInEdt
ApplicationManager.getApplication().addApplicationListener(MyApplicationListener(), this)
FileStatusManager.getInstance(project).addFileStatusListener(MyFileStatusListener(), this)
EditorFactory.getInstance().eventMulticaster.addDocumentListener(MyDocumentListener(), this)
MyEditorFactoryListener().install(this)
onEverythingChanged()
PartialLineStatusTrackerManagerState.restoreState(project)
}
}
override fun dispose() {
isDisposed = true
Disposer.dispose(loader)
synchronized(LOCK) {
for ((document, multiset) in forcedDocuments) {
for (requester in multiset.elementSet()) {
warn("Tracker is being held on dispose by $requester", document)
}
}
forcedDocuments.clear()
for (data in trackers.values) {
unregisterTrackerInCLM(data)
data.tracker.release()
}
trackers.clear()
}
}
override fun getLineStatusTracker(document: Document): LineStatusTracker<*>? {
synchronized(LOCK) {
return trackers[document]?.tracker
}
}
override fun getLineStatusTracker(file: VirtualFile): LineStatusTracker<*>? {
val document = FileDocumentManager.getInstance().getCachedDocument(file) ?: return null
return getLineStatusTracker(document)
}
@RequiresEdt
override fun requestTrackerFor(document: Document, requester: Any) {
ApplicationManager.getApplication().assertIsWriteThread()
synchronized(LOCK) {
if (isDisposed) {
warn("Tracker is being requested after dispose by $requester", document)
return
}
val multiset = forcedDocuments.computeIfAbsent(document) { HashMultiset.create<Any>() }
multiset.add(requester)
if (trackers[document] == null) {
val virtualFile = FileDocumentManager.getInstance().getFile(document) ?: return
switchTracker(virtualFile, document)
}
}
}
@RequiresEdt
override fun releaseTrackerFor(document: Document, requester: Any) {
ApplicationManager.getApplication().assertIsWriteThread()
synchronized(LOCK) {
val multiset = forcedDocuments[document]
if (multiset == null || !multiset.contains(requester)) {
warn("Tracker release underflow by $requester", document)
return
}
multiset.remove(requester)
if (multiset.isEmpty()) {
forcedDocuments.remove(document)
checkIfTrackerCanBeReleased(document)
}
}
}
override fun invokeAfterUpdate(task: Runnable) {
loader.addAfterUpdateRunnable(task)
}
fun getTrackers(): List<LineStatusTracker<*>> {
synchronized(LOCK) {
return trackers.values.map { it.tracker }
}
}
fun addTrackerListener(listener: Listener, disposable: Disposable) {
eventDispatcher.addListener(listener, disposable)
}
open class ListenerAdapter : Listener
interface Listener : EventListener {
fun onTrackerAdded(tracker: LineStatusTracker<*>) {
}
fun onTrackerRemoved(tracker: LineStatusTracker<*>) {
}
}
@RequiresEdt
private fun checkIfTrackerCanBeReleased(document: Document) {
synchronized(LOCK) {
val data = trackers[document] ?: return
if (forcedDocuments.containsKey(document)) return
if (data.tracker is ChangelistsLocalLineStatusTracker) {
val hasPartialChanges = data.tracker.hasPartialState()
if (hasPartialChanges) {
log("checkIfTrackerCanBeReleased - hasPartialChanges", data.tracker.virtualFile)
return
}
val isLoading = loader.hasRequestFor(document)
if (isLoading) {
log("checkIfTrackerCanBeReleased - isLoading", data.tracker.virtualFile)
if (data.tracker.hasPendingPartialState() ||
fileStatesAwaitingRefresh.containsKey(data.tracker.virtualFile)) {
log("checkIfTrackerCanBeReleased - has pending state", data.tracker.virtualFile)
return
}
}
}
releaseTracker(document)
}
}
@RequiresEdt
private fun onEverythingChanged() {
ApplicationManager.getApplication().assertIsWriteThread()
synchronized(LOCK) {
if (isDisposed) return
log("onEverythingChanged", null)
val files = HashSet<VirtualFile>()
for (data in trackers.values) {
files.add(data.tracker.virtualFile)
}
for (document in forcedDocuments.keys) {
val file = FileDocumentManager.getInstance().getFile(document)
if (file != null) files.add(file)
}
for (file in files) {
onFileChanged(file)
}
}
}
@RequiresEdt
private fun onFileChanged(virtualFile: VirtualFile) {
val document = FileDocumentManager.getInstance().getCachedDocument(virtualFile) ?: return
synchronized(LOCK) {
if (isDisposed) return
log("onFileChanged", virtualFile)
val tracker = trackers[document]?.tracker
if (tracker != null || forcedDocuments.containsKey(document)) {
switchTracker(virtualFile, document, refreshExisting = true)
}
}
}
private fun registerTrackerInCLM(data: TrackerData) {
val tracker = data.tracker
if (tracker !is ChangelistsLocalLineStatusTracker) return
val filePath = VcsUtil.getFilePath(tracker.virtualFile)
if (data.clmFilePath != null) {
LOG.error("[registerTrackerInCLM] tracker already registered")
return
}
ChangeListManagerImpl.getInstanceImpl(project).registerChangeTracker(filePath, tracker)
data.clmFilePath = filePath
}
private fun unregisterTrackerInCLM(data: TrackerData) {
val tracker = data.tracker
if (tracker !is ChangelistsLocalLineStatusTracker) return
val filePath = data.clmFilePath
if (filePath == null) {
LOG.error("[unregisterTrackerInCLM] tracker is not registered")
return
}
ChangeListManagerImpl.getInstanceImpl(project).unregisterChangeTracker(filePath, tracker)
data.clmFilePath = null
val actualFilePath = VcsUtil.getFilePath(tracker.virtualFile)
if (filePath != actualFilePath) {
LOG.error("[unregisterTrackerInCLM] unexpected file path: expected: $filePath, actual: $actualFilePath")
}
}
private fun reregisterTrackerInCLM(data: TrackerData) {
val tracker = data.tracker
if (tracker !is ChangelistsLocalLineStatusTracker) return
val oldFilePath = data.clmFilePath
val newFilePath = VcsUtil.getFilePath(tracker.virtualFile)
if (oldFilePath == null) {
LOG.error("[reregisterTrackerInCLM] tracker is not registered")
return
}
if (oldFilePath != newFilePath) {
ChangeListManagerImpl.getInstanceImpl(project).unregisterChangeTracker(oldFilePath, tracker)
ChangeListManagerImpl.getInstanceImpl(project).registerChangeTracker(newFilePath, tracker)
data.clmFilePath = newFilePath
}
}
private fun canCreateTrackerFor(virtualFile: VirtualFile?): Boolean {
if (isDisposed) return false
if (virtualFile == null || virtualFile is LightVirtualFile) return false
if (runReadAction { !virtualFile.isValid || virtualFile.fileType.isBinary || FileUtilRt.isTooLarge(virtualFile.length) }) return false
return true
}
override fun arePartialChangelistsEnabled(): Boolean = partialChangeListsEnabled
override fun arePartialChangelistsEnabled(virtualFile: VirtualFile): Boolean {
if (!partialChangeListsEnabled) return false
val vcs = VcsUtil.getVcsFor(project, virtualFile)
return vcs != null && vcs.arePartialChangelistsSupported()
}
private fun switchTracker(virtualFile: VirtualFile, document: Document,
refreshExisting: Boolean = false) {
val provider = getTrackerProvider(virtualFile)
val oldTracker = trackers[document]?.tracker
if (oldTracker != null && provider != null && provider.isMyTracker(oldTracker)) {
if (refreshExisting) {
refreshTracker(oldTracker, provider)
}
}
else {
releaseTracker(document)
if (provider != null) installTracker(virtualFile, document, provider)
}
}
private fun installTracker(virtualFile: VirtualFile, document: Document,
provider: LocalLineStatusTrackerProvider): LocalLineStatusTracker<*>? {
if (isDisposed) return null
if (trackers[document] != null) return null
val tracker = provider.createTracker(project, virtualFile) ?: return null
tracker.mode = getTrackingMode()
val data = TrackerData(tracker)
val replacedData = trackers.put(document, data)
LOG.assertTrue(replacedData == null)
registerTrackerInCLM(data)
refreshTracker(tracker, provider)
eventDispatcher.multicaster.onTrackerAdded(tracker)
if (clmFreezeCounter > 0) {
tracker.freeze()
}
log("Tracker installed", virtualFile)
return tracker
}
private fun getTrackerProvider(virtualFile: VirtualFile): LocalLineStatusTrackerProvider? {
if (!canCreateTrackerFor(virtualFile)) return null
val customTracker = LocalLineStatusTrackerProvider.EP_NAME.findFirstSafe { it.isTrackedFile(project, virtualFile) }
if (customTracker != null) return customTracker
return listOf(ChangelistsLocalStatusTrackerProvider, DefaultLocalStatusTrackerProvider).find { it.isTrackedFile(project, virtualFile) }
}
@RequiresEdt
private fun releaseTracker(document: Document) {
val data = trackers.remove(document) ?: return
eventDispatcher.multicaster.onTrackerRemoved(data.tracker)
unregisterTrackerInCLM(data)
data.tracker.release()
log("Tracker released", data.tracker.virtualFile)
}
private fun updatePartialChangeListsAvailability() {
partialChangeListsEnabled = VcsApplicationSettings.getInstance().ENABLE_PARTIAL_CHANGELISTS &&
ChangeListManager.getInstance(project).areChangeListsEnabled()
}
private fun updateTrackingSettings() {
synchronized(LOCK) {
if (isDisposed) return
val mode = getTrackingMode()
for (data in trackers.values) {
data.tracker.mode = mode
}
}
onEverythingChanged()
}
private fun getTrackingMode(): LocalLineStatusTracker.Mode {
val settings = VcsApplicationSettings.getInstance()
return LocalLineStatusTracker.Mode(settings.SHOW_LST_GUTTER_MARKERS,
settings.SHOW_LST_ERROR_STRIPE_MARKERS,
settings.SHOW_WHITESPACES_IN_LST)
}
@RequiresEdt
private fun refreshTracker(tracker: LocalLineStatusTracker<*>,
provider: LocalLineStatusTrackerProvider) {
if (isDisposed) return
if (provider !is LineStatusTrackerContentLoader) return
loader.scheduleRefresh(RefreshRequest(tracker.document, provider))
log("Refresh queued", tracker.virtualFile)
}
private inner class MyBaseRevisionLoader : SingleThreadLoader<RefreshRequest, RefreshData>() {
fun hasRequestFor(document: Document): Boolean {
return hasRequest { it.document == document }
}
override fun loadRequest(request: RefreshRequest): Result<RefreshData> {
if (isDisposed) return Result.Canceled()
val document = request.document
val virtualFile = FileDocumentManager.getInstance().getFile(document)
val loader = request.loader
log("Loading started", virtualFile)
if (virtualFile == null || !virtualFile.isValid) {
log("Loading error: virtual file is not valid", virtualFile)
return Result.Error()
}
if (!canCreateTrackerFor(virtualFile) || !loader.isTrackedFile(project, virtualFile)) {
log("Loading error: virtual file is not a tracked file", virtualFile)
return Result.Error()
}
val newContentInfo = loader.getContentInfo(project, virtualFile)
if (newContentInfo == null) {
log("Loading error: base revision not found", virtualFile)
return Result.Error()
}
synchronized(LOCK) {
val data = trackers[document]
if (data == null) {
log("Loading cancelled: tracker not found", virtualFile)
return Result.Canceled()
}
if (!loader.shouldBeUpdated(data.contentInfo, newContentInfo)) {
log("Loading cancelled: no need to update", virtualFile)
return Result.Canceled()
}
}
val content = loader.loadContent(project, newContentInfo)
if (content == null) {
log("Loading error: provider failure", virtualFile)
return Result.Error()
}
log("Loading successful", virtualFile)
return Result.Success(RefreshData(content, newContentInfo))
}
@RequiresEdt
override fun handleResult(request: RefreshRequest, result: Result<RefreshData>) {
val document = request.document
when (result) {
is Result.Canceled -> handleCanceled(document)
is Result.Error -> handleError(request, document)
is Result.Success -> handleSuccess(request, document, result.data)
}
checkIfTrackerCanBeReleased(document)
}
private fun handleCanceled(document: Document) {
restorePendingTrackerState(document)
}
private fun handleError(request: RefreshRequest, document: Document) {
synchronized(LOCK) {
val loader = request.loader
val data = trackers[document] ?: return
val tracker = data.tracker
if (loader.isMyTracker(tracker)) {
loader.handleLoadingError(tracker)
}
data.contentInfo = null
}
}
private fun handleSuccess(request: RefreshRequest, document: Document, refreshData: RefreshData) {
val virtualFile = FileDocumentManager.getInstance().getFile(document)!!
val loader = request.loader
val tracker: LocalLineStatusTracker<*>
synchronized(LOCK) {
val data = trackers[document]
if (data == null) {
log("Loading finished: tracker already released", virtualFile)
return
}
if (!loader.shouldBeUpdated(data.contentInfo, refreshData.contentInfo)) {
log("Loading finished: no need to update", virtualFile)
return
}
data.contentInfo = refreshData.contentInfo
tracker = data.tracker
}
if (loader.isMyTracker(tracker)) {
loader.setLoadedContent(tracker, refreshData.content)
log("Loading finished: success", virtualFile)
}
else {
log("Loading finished: wrong tracker. tracker: $tracker, loader: $loader", virtualFile)
}
restorePendingTrackerState(document)
}
private fun restorePendingTrackerState(document: Document) {
val tracker = getLineStatusTracker(document)
if (tracker is ChangelistsLocalLineStatusTracker) {
val virtualFile = tracker.virtualFile
val state = synchronized(LOCK) {
fileStatesAwaitingRefresh.remove(virtualFile) ?: return
}
val success = tracker.restoreState(state)
log("Pending state restored. success - $success", virtualFile)
}
}
}
/**
* We can speedup initial content loading if it was already loaded by someone.
* We do not set 'contentInfo' here to ensure, that following refresh will fix potential inconsistency.
*/
@RequiresEdt
@ApiStatus.Internal
fun offerTrackerContent(document: Document, text: CharSequence) {
try {
val tracker: LocalLineStatusTracker<*>
synchronized(LOCK) {
val data = trackers[document]
if (data == null || data.contentInfo != null) return
tracker = data.tracker
}
if (tracker is LocalLineStatusTrackerImpl<*>) {
ClientId.withClientId(ClientId.localId) {
tracker.setBaseRevision(text)
log("Offered content", tracker.virtualFile)
}
}
}
catch (e: Throwable) {
LOG.error(e)
}
}
private inner class MyFileStatusListener : FileStatusListener {
override fun fileStatusesChanged() {
onEverythingChanged()
}
override fun fileStatusChanged(virtualFile: VirtualFile) {
onFileChanged(virtualFile)
}
}
private inner class MyEditorFactoryListener : EditorFactoryListener {
fun install(disposable: Disposable) {
val editorFactory = EditorFactory.getInstance()
for (editor in editorFactory.allEditors) {
if (isTrackedEditor(editor)) {
requestTrackerFor(editor.document, editor)
}
}
editorFactory.addEditorFactoryListener(this, disposable)
}
override fun editorCreated(event: EditorFactoryEvent) {
val editor = event.editor
if (isTrackedEditor(editor)) {
requestTrackerFor(editor.document, editor)
}
}
override fun editorReleased(event: EditorFactoryEvent) {
val editor = event.editor
if (isTrackedEditor(editor)) {
releaseTrackerFor(editor.document, editor)
}
}
private fun isTrackedEditor(editor: Editor): Boolean {
// can't filter out "!isInLocalFileSystem" files, custom VcsBaseContentProvider can handle them
if (FileDocumentManager.getInstance().getFile(editor.document) == null) {
return false
}
return editor.project == null || editor.project == project
}
}
private inner class MyVirtualFileListener : BulkFileListener {
override fun before(events: List<VFileEvent>) {
for (event in events) {
when (event) {
is VFileDeleteEvent -> handleFileDeletion(event.file)
}
}
}
override fun after(events: List<VFileEvent>) {
for (event in events) {
when (event) {
is VFilePropertyChangeEvent -> when {
VirtualFile.PROP_ENCODING == event.propertyName -> onFileChanged(event.file)
event.isRename -> handleFileMovement(event.file)
}
is VFileMoveEvent -> handleFileMovement(event.file)
}
}
}
private fun handleFileMovement(file: VirtualFile) {
if (!partialChangeListsEnabled) return
synchronized(LOCK) {
forEachTrackerUnder(file) { data ->
reregisterTrackerInCLM(data)
}
}
}
private fun handleFileDeletion(file: VirtualFile) {
if (!partialChangeListsEnabled) return
synchronized(LOCK) {
forEachTrackerUnder(file) { data ->
releaseTracker(data.tracker.document)
}
}
}
private fun forEachTrackerUnder(file: VirtualFile, action: (TrackerData) -> Unit) {
if (file.isDirectory) {
val affected = trackers.values.filter { VfsUtil.isAncestor(file, it.tracker.virtualFile, false) }
for (data in affected) {
action(data)
}
}
else {
val document = FileDocumentManager.getInstance().getCachedDocument(file) ?: return
val data = trackers[document] ?: return
action(data)
}
}
}
private inner class MyDocumentListener : DocumentListener {
override fun documentChanged(event: DocumentEvent) {
if (!ApplicationManager.getApplication().isDispatchThread) return // disable for documents forUseInNonAWTThread
if (!partialChangeListsEnabled || project.isDisposed) return
val document = event.document
if (documentsInDefaultChangeList.contains(document)) return
val virtualFile = FileDocumentManager.getInstance().getFile(document) ?: return
if (getLineStatusTracker(document) != null) return
val provider = getTrackerProvider(virtualFile)
if (provider != ChangelistsLocalStatusTrackerProvider) return
val changeList = ChangeListManager.getInstance(project).getChangeList(virtualFile)
val inAnotherChangelist = changeList != null && !ActiveChangeListTracker.getInstance(project).isActiveChangeList(changeList)
if (inAnotherChangelist) {
log("Tracker install from DocumentListener: ", virtualFile)
val tracker = synchronized(LOCK) {
installTracker(virtualFile, document, provider)
}
if (tracker is ChangelistsLocalLineStatusTracker) {
tracker.replayChangesFromDocumentEvents(listOf(event))
}
}
else {
documentsInDefaultChangeList.add(document)
}
}
}
private inner class MyApplicationListener : ApplicationListener {
override fun afterWriteActionFinished(action: Any) {
documentsInDefaultChangeList.clear()
synchronized(LOCK) {
val documents = trackers.values.map { it.tracker.document }
for (document in documents) {
checkIfTrackerCanBeReleased(document)
}
}
}
}
private inner class MyLineStatusTrackerSettingListener : LineStatusTrackerSettingListener {
override fun settingsUpdated() {
updatePartialChangeListsAvailability()
updateTrackingSettings()
}
}
private inner class MyChangeListListener : ChangeListAdapter() {
override fun defaultListChanged(oldDefaultList: ChangeList?, newDefaultList: ChangeList?) {
runInEdt(ModalityState.any()) {
if (project.isDisposed) return@runInEdt
expireInactiveRangesDamagedNotifications()
EditorFactory.getInstance().allEditors
.forEach { if (it is EditorEx) it.gutterComponentEx.repaint() }
}
}
}
private inner class MyChangeListAvailabilityListener : ChangeListAvailabilityListener {
override fun onBefore() {
if (ChangeListManager.getInstance(project).areChangeListsEnabled()) {
val fileStates = LineStatusTrackerManager.getInstanceImpl(project).collectPartiallyChangedFilesStates()
if (fileStates.isNotEmpty()) {
PartialLineStatusTrackerManagerState.saveCurrentState(project, fileStates)
}
}
}
override fun onAfter() {
updatePartialChangeListsAvailability()
onEverythingChanged()
if (ChangeListManager.getInstance(project).areChangeListsEnabled()) {
PartialLineStatusTrackerManagerState.restoreState(project)
}
}
}
private inner class MyCommandListener : CommandListener {
override fun commandFinished(event: CommandEvent) {
if (!partialChangeListsEnabled) return
if (CommandProcessor.getInstance().currentCommand == null &&
!filesWithDamagedInactiveRanges.isEmpty()) {
showInactiveRangesDamagedNotification()
}
}
}
class CheckinFactory : CheckinHandlerFactory() {
override fun createHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler {
val project = panel.project
return object : CheckinHandler() {
override fun checkinSuccessful() {
resetExcludedFromCommit()
}
override fun checkinFailed(exception: MutableList<VcsException>?) {
resetExcludedFromCommit()
}
private fun resetExcludedFromCommit() {
runInEdt {
// TODO Move this to SingleChangeListCommitWorkflow
if (!project.isDisposed && !panel.isNonModalCommit) getInstanceImpl(project).resetExcludedFromCommitMarkers()
}
}
}
}
}
private inner class MyFreezeListener : VcsFreezingProcess.Listener {
override fun onFreeze() {
runReadAction {
synchronized(LOCK) {
if (clmFreezeCounter == 0) {
for (data in trackers.values) {
try {
data.tracker.freeze()
}
catch (e: Throwable) {
LOG.error(e)
}
}
}
clmFreezeCounter++
}
}
}
override fun onUnfreeze() {
runInEdt(ModalityState.any()) {
synchronized(LOCK) {
clmFreezeCounter--
if (clmFreezeCounter == 0) {
for (data in trackers.values) {
try {
data.tracker.unfreeze()
}
catch (e: Throwable) {
LOG.error(e)
}
}
}
}
}
}
}
private class TrackerData(val tracker: LocalLineStatusTracker<*>,
var contentInfo: ContentInfo? = null,
var clmFilePath: FilePath? = null)
private class RefreshRequest(val document: Document, val loader: LineStatusTrackerContentLoader) {
override fun equals(other: Any?): Boolean = other is RefreshRequest && document == other.document
override fun hashCode(): Int = document.hashCode()
override fun toString(): String = "RefreshRequest: " + (FileDocumentManager.getInstance().getFile(document)?.path ?: "unknown") // NON-NLS
}
private class RefreshData(val content: TrackerContent,
val contentInfo: ContentInfo)
private fun log(@NonNls message: String, file: VirtualFile?) {
if (LOG.isDebugEnabled) {
if (file != null) {
LOG.debug(message + "; file: " + file.path)
}
else {
LOG.debug(message)
}
}
}
private fun warn(@NonNls message: String, document: Document?) {
val file = document?.let { FileDocumentManager.getInstance().getFile(it) }
warn(message, file)
}
private fun warn(@NonNls message: String, file: VirtualFile?) {
if (file != null) {
LOG.warn(message + "; file: " + file.path)
}
else {
LOG.warn(message)
}
}
@RequiresEdt
fun resetExcludedFromCommitMarkers() {
ApplicationManager.getApplication().assertIsWriteThread()
synchronized(LOCK) {
val documents = mutableListOf<Document>()
for (data in trackers.values) {
val tracker = data.tracker
if (tracker is ChangelistsLocalLineStatusTracker) {
tracker.resetExcludedFromCommitMarkers()
documents.add(tracker.document)
}
}
for (document in documents) {
checkIfTrackerCanBeReleased(document)
}
}
}
internal fun collectPartiallyChangedFilesStates(): List<ChangelistsLocalLineStatusTracker.FullState> {
ApplicationManager.getApplication().assertReadAccessAllowed()
val result = mutableListOf<ChangelistsLocalLineStatusTracker.FullState>()
synchronized(LOCK) {
for (data in trackers.values) {
val tracker = data.tracker
if (tracker is ChangelistsLocalLineStatusTracker) {
val hasPartialChanges = tracker.affectedChangeListsIds.size > 1
if (hasPartialChanges) {
result.add(tracker.storeTrackerState())
}
}
}
}
return result
}
@RequiresEdt
internal fun restoreTrackersForPartiallyChangedFiles(trackerStates: List<ChangelistsLocalLineStatusTracker.State>) {
runWriteAction {
synchronized(LOCK) {
if (isDisposed) return@runWriteAction
for (state in trackerStates) {
val virtualFile = state.virtualFile
val document = FileDocumentManager.getInstance().getDocument(virtualFile) ?: continue
val provider = getTrackerProvider(virtualFile)
if (provider != ChangelistsLocalStatusTrackerProvider) continue
switchTracker(virtualFile, document)
val tracker = trackers[document]?.tracker
if (tracker !is ChangelistsLocalLineStatusTracker) continue
val isLoading = loader.hasRequestFor(document)
if (isLoading) {
fileStatesAwaitingRefresh.put(state.virtualFile, state)
log("State restoration scheduled", virtualFile)
}
else {
val success = tracker.restoreState(state)
log("State restored. success - $success", virtualFile)
}
}
loader.addAfterUpdateRunnable(Runnable {
synchronized(LOCK) {
log("State restoration finished", null)
fileStatesAwaitingRefresh.clear()
}
})
}
}
onEverythingChanged()
}
@RequiresEdt
internal fun notifyInactiveRangesDamaged(virtualFile: VirtualFile) {
ApplicationManager.getApplication().assertIsWriteThread()
if (filesWithDamagedInactiveRanges.contains(virtualFile) || virtualFile == FileEditorManagerEx.getInstanceEx(project).currentFile) {
return
}
filesWithDamagedInactiveRanges.add(virtualFile)
}
private fun showInactiveRangesDamagedNotification() {
val currentNotifications = NotificationsManager.getNotificationsManager()
.getNotificationsOfType(InactiveRangesDamagedNotification::class.java, project)
val lastNotification = currentNotifications.lastOrNull { !it.isExpired }
if (lastNotification != null) filesWithDamagedInactiveRanges.addAll(lastNotification.virtualFiles)
currentNotifications.forEach { it.expire() }
val files = filesWithDamagedInactiveRanges.toSet()
filesWithDamagedInactiveRanges.clear()
InactiveRangesDamagedNotification(project, files).notify(project)
}
@RequiresEdt
private fun expireInactiveRangesDamagedNotifications() {
filesWithDamagedInactiveRanges.clear()
val currentNotifications = NotificationsManager.getNotificationsManager()
.getNotificationsOfType(InactiveRangesDamagedNotification::class.java, project)
currentNotifications.forEach { it.expire() }
}
private class InactiveRangesDamagedNotification(project: Project, val virtualFiles: Set<VirtualFile>)
: Notification(VcsNotifier.STANDARD_NOTIFICATION.displayId,
AllIcons.Toolwindows.ToolWindowChanges,
null,
null,
VcsBundle.message("lst.inactive.ranges.damaged.notification"),
NotificationType.INFORMATION,
null) {
init {
addAction(NotificationAction.createSimple(
Supplier { VcsBundle.message("action.NotificationAction.InactiveRangesDamagedNotification.text.view.changes") },
Runnable {
val defaultList = ChangeListManager.getInstance(project).defaultChangeList
val changes = defaultList.changes.filter { virtualFiles.contains(it.virtualFile) }
val window = getToolWindowFor(project, LOCAL_CHANGES)
window?.activate { ChangesViewManager.getInstance(project).selectChanges(changes) }
expire()
}))
}
}
@TestOnly
fun waitUntilBaseContentsLoaded() {
assert(ApplicationManager.getApplication().isUnitTestMode)
if (ApplicationManager.getApplication().isDispatchThread) {
UIUtil.dispatchAllInvocationEvents()
}
val semaphore = Semaphore()
semaphore.down()
loader.addAfterUpdateRunnable(Runnable {
semaphore.up()
})
val start = System.currentTimeMillis()
while (true) {
if (ApplicationManager.getApplication().isDispatchThread) {
UIUtil.dispatchAllInvocationEvents()
}
if (semaphore.waitFor(10)) {
return
}
if (System.currentTimeMillis() - start > 10000) {
loader.dumpInternalState()
System.err.println(ThreadDumper.dumpThreadsToString())
throw IllegalStateException("Couldn't await base contents") // NON-NLS
}
}
}
@TestOnly
fun releaseAllTrackers() {
synchronized(LOCK) {
forcedDocuments.clear()
for (data in trackers.values) {
unregisterTrackerInCLM(data)
data.tracker.release()
}
trackers.clear()
}
}
}
/**
* Single threaded queue with the following properties:
* - Ignores duplicated requests (the first queued is used).
* - Allows to check whether request is scheduled or is waiting for completion.
* - Notifies callbacks when queue is exhausted.
*/
private abstract class SingleThreadLoader<Request, T> : Disposable {
private val LOG = Logger.getInstance(SingleThreadLoader::class.java)
private val LOCK: Any = Any()
private val taskQueue = ArrayDeque<Request>()
private val waitingForRefresh = HashSet<Request>()
private val callbacksWaitingUpdateCompletion = ArrayList<Runnable>()
private var isScheduled: Boolean = false
private var isDisposed: Boolean = false
private var lastFuture: Future<*>? = null
@RequiresBackgroundThread
protected abstract fun loadRequest(request: Request): Result<T>
@RequiresEdt
protected abstract fun handleResult(request: Request, result: Result<T>)
@RequiresEdt
fun scheduleRefresh(request: Request) {
if (isDisposed) return
synchronized(LOCK) {
if (taskQueue.contains(request)) return
taskQueue.add(request)
schedule()
}
}
@RequiresEdt
override fun dispose() {
val callbacks = mutableListOf<Runnable>()
synchronized(LOCK) {
isDisposed = true
taskQueue.clear()
waitingForRefresh.clear()
lastFuture?.cancel(true)
callbacks += callbacksWaitingUpdateCompletion
callbacksWaitingUpdateCompletion.clear()
}
executeCallbacks(callbacksWaitingUpdateCompletion)
}
@RequiresEdt
protected fun hasRequest(condition: (Request) -> Boolean): Boolean {
synchronized(LOCK) {
return taskQueue.any(condition) ||
waitingForRefresh.any(condition)
}
}
@CalledInAny
fun addAfterUpdateRunnable(task: Runnable) {
val updateScheduled = putRunnableIfUpdateScheduled(task)
if (updateScheduled) return
runInEdt(ModalityState.any()) {
if (!putRunnableIfUpdateScheduled(task)) {
task.run()
}
}
}
private fun putRunnableIfUpdateScheduled(task: Runnable): Boolean {
synchronized(LOCK) {
if (taskQueue.isEmpty() && waitingForRefresh.isEmpty()) return false
callbacksWaitingUpdateCompletion.add(task)
return true
}
}
private fun schedule() {
if (isDisposed) return
synchronized(LOCK) {
if (isScheduled) return
if (taskQueue.isEmpty()) return
isScheduled = true
lastFuture = ApplicationManager.getApplication().executeOnPooledThread {
ClientId.withClientId(ClientId.localId) {
BackgroundTaskUtil.runUnderDisposeAwareIndicator(this, Runnable {
handleRequests()
})
}
}
}
}
private fun handleRequests() {
while (true) {
val request = synchronized(LOCK) {
val request = taskQueue.poll()
if (isDisposed || request == null) {
isScheduled = false
return
}
waitingForRefresh.add(request)
return@synchronized request
}
handleSingleRequest(request)
}
}
private fun handleSingleRequest(request: Request) {
val result: Result<T> = try {
loadRequest(request)
}
catch (e: ProcessCanceledException) {
Result.Canceled()
}
catch (e: Throwable) {
LOG.error(e)
Result.Error()
}
runInEdt(ModalityState.any()) {
try {
synchronized(LOCK) {
waitingForRefresh.remove(request)
}
handleResult(request, result)
}
finally {
notifyTrackerRefreshed()
}
}
}
@RequiresEdt
private fun notifyTrackerRefreshed() {
if (isDisposed) return
val callbacks = mutableListOf<Runnable>()
synchronized(LOCK) {
if (taskQueue.isEmpty() && waitingForRefresh.isEmpty()) {
callbacks += callbacksWaitingUpdateCompletion
callbacksWaitingUpdateCompletion.clear()
}
}
executeCallbacks(callbacks)
}
@RequiresEdt
private fun executeCallbacks(callbacks: List<Runnable>) {
for (callback in callbacks) {
try {
callback.run()
}
catch (e: ProcessCanceledException) {
}
catch (e: Throwable) {
LOG.error(e)
}
}
}
@TestOnly
fun dumpInternalState() {
synchronized(LOCK) {
LOG.debug("isScheduled - $isScheduled")
LOG.debug("pending callbacks: ${callbacksWaitingUpdateCompletion.size}")
taskQueue.forEach {
LOG.debug("pending task: ${it}")
}
waitingForRefresh.forEach {
LOG.debug("waiting refresh: ${it}")
}
}
}
}
private sealed class Result<T> {
class Success<T>(val data: T) : Result<T>()
class Canceled<T> : Result<T>()
class Error<T> : Result<T>()
}
private object ChangelistsLocalStatusTrackerProvider : BaseRevisionStatusTrackerContentLoader() {
override fun isTrackedFile(project: Project, file: VirtualFile): Boolean {
if (!LineStatusTrackerManager.getInstance(project).arePartialChangelistsEnabled(file)) return false
if (!super.isTrackedFile(project, file)) return false
val status = FileStatusManager.getInstance(project).getStatus(file)
if (status != FileStatus.MODIFIED &&
status != ChangelistConflictFileStatusProvider.MODIFIED_OUTSIDE &&
status != FileStatus.NOT_CHANGED) return false
val change = ChangeListManager.getInstance(project).getChange(file)
return change == null ||
change.javaClass == Change::class.java &&
(change.type == Change.Type.MODIFICATION || change.type == Change.Type.MOVED) &&
change.afterRevision is CurrentContentRevision
}
override fun isMyTracker(tracker: LocalLineStatusTracker<*>): Boolean = tracker is ChangelistsLocalLineStatusTracker
override fun createTracker(project: Project, file: VirtualFile): LocalLineStatusTracker<*>? {
val document = FileDocumentManager.getInstance().getDocument(file) ?: return null
return ChangelistsLocalLineStatusTracker.createTracker(project, document, file)
}
}
private object DefaultLocalStatusTrackerProvider : BaseRevisionStatusTrackerContentLoader() {
override fun isMyTracker(tracker: LocalLineStatusTracker<*>): Boolean = tracker is SimpleLocalLineStatusTracker
override fun createTracker(project: Project, file: VirtualFile): LocalLineStatusTracker<*>? {
val document = FileDocumentManager.getInstance().getDocument(file) ?: return null
return SimpleLocalLineStatusTracker.createTracker(project, document, file)
}
}
private abstract class BaseRevisionStatusTrackerContentLoader : LineStatusTrackerContentLoader {
override fun isTrackedFile(project: Project, file: VirtualFile): Boolean {
if (!VcsFileStatusProvider.getInstance(project).isSupported(file)) return false
val status = FileStatusManager.getInstance(project).getStatus(file)
if (status == FileStatus.ADDED ||
status == FileStatus.DELETED ||
status == FileStatus.UNKNOWN ||
status == FileStatus.IGNORED) {
return false
}
return true
}
override fun getContentInfo(project: Project, file: VirtualFile): ContentInfo? {
val baseContent = VcsFileStatusProvider.getInstance(project).getBaseRevision(file) ?: return null
return BaseRevisionContentInfo(baseContent, file.charset)
}
override fun shouldBeUpdated(oldInfo: ContentInfo?, newInfo: ContentInfo): Boolean {
newInfo as BaseRevisionContentInfo
return oldInfo == null ||
oldInfo !is BaseRevisionContentInfo ||
oldInfo.baseContent.revisionNumber != newInfo.baseContent.revisionNumber ||
oldInfo.baseContent.revisionNumber == VcsRevisionNumber.NULL ||
oldInfo.charset != newInfo.charset
}
override fun loadContent(project: Project, info: ContentInfo): BaseRevisionContent? {
info as BaseRevisionContentInfo
val lastUpToDateContent = info.baseContent.loadContent() ?: return null
val correctedText = StringUtil.convertLineSeparators(lastUpToDateContent)
return BaseRevisionContent(correctedText)
}
override fun setLoadedContent(tracker: LocalLineStatusTracker<*>, content: TrackerContent) {
tracker as LocalLineStatusTrackerImpl<*>
content as BaseRevisionContent
tracker.setBaseRevision(content.text)
}
override fun handleLoadingError(tracker: LocalLineStatusTracker<*>) {
tracker as LocalLineStatusTrackerImpl<*>
tracker.dropBaseRevision()
}
private class BaseRevisionContentInfo(val baseContent: VcsBaseContentProvider.BaseContent, val charset: Charset) : ContentInfo
private class BaseRevisionContent(val text: CharSequence) : TrackerContent
}
interface LocalLineStatusTrackerProvider {
fun isTrackedFile(project: Project, file: VirtualFile): Boolean
fun isMyTracker(tracker: LocalLineStatusTracker<*>): Boolean
fun createTracker(project: Project, file: VirtualFile): LocalLineStatusTracker<*>?
companion object {
val EP_NAME: ExtensionPointName<LocalLineStatusTrackerProvider> =
ExtensionPointName.create("com.intellij.openapi.vcs.impl.LocalLineStatusTrackerProvider")
}
}
interface LineStatusTrackerContentLoader : LocalLineStatusTrackerProvider {
fun getContentInfo(project: Project, file: VirtualFile): ContentInfo?
fun shouldBeUpdated(oldInfo: ContentInfo?, newInfo: ContentInfo): Boolean
fun loadContent(project: Project, info: ContentInfo): TrackerContent?
fun setLoadedContent(tracker: LocalLineStatusTracker<*>, content: TrackerContent)
fun handleLoadingError(tracker: LocalLineStatusTracker<*>)
interface ContentInfo
interface TrackerContent
} | apache-2.0 | fe7a3cfcb51b61ebfa535624f5c9369b | 32.336662 | 142 | 0.701286 | 5.473999 | false | false | false | false |
datafrost1997/GitterChat | app/src/main/java/com/devslopes/datafrost1997/gitterchat/Controller/MainActivity.kt | 1 | 9214 | package com.devslopes.datafrost1997.gitterchat.Controller
import android.content.*
import android.graphics.Color
import android.os.Bundle
import android.support.v4.content.LocalBroadcastManager
import android.support.v4.view.GravityCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.ArrayAdapter
import android.widget.EditText
import android.widget.LinearLayout
import com.devslopes.datafrost1997.gitterchat.Adapters.MessageAdapter
import com.devslopes.datafrost1997.gitterchat.Model.Channel
import com.devslopes.datafrost1997.gitterchat.Model.Message
import com.devslopes.datafrost1997.gitterchat.R
import com.devslopes.datafrost1997.gitterchat.R.id.*
import com.devslopes.datafrost1997.gitterchat.Services.AuthService
import com.devslopes.datafrost1997.gitterchat.Services.MessageService
import com.devslopes.datafrost1997.gitterchat.Services.UserDataService
import com.devslopes.datafrost1997.gitterchat.Utilities.BROADCAST_USER_DATA_CHANGE
import com.devslopes.datafrost1997.gitterchat.Utilities.SOCKET_URL
import io.socket.client.IO
import io.socket.emitter.Emitter
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.app_bar_main.*
import kotlinx.android.synthetic.main.content_main.*
import kotlinx.android.synthetic.main.nav_header_main.*
class MainActivity : AppCompatActivity() {
val socket = IO.socket(SOCKET_URL)
lateinit var channelAdapter: ArrayAdapter<Channel>
lateinit var messageAdapter: MessageAdapter
var selectedChannel: Channel? = null
private fun setupAdapters() {
channelAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, MessageService.channels)
channel_list.adapter = channelAdapter
messageAdapter = MessageAdapter(this,MessageService.messages)
messageListView.adapter = messageAdapter
val layoutManager = LinearLayoutManager(this)
messageListView.layoutManager = layoutManager
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
socket.connect()
socket.on("channelCreated", onNewChannel)
socket.on("messageCreated", onNewMessage)
val toggle = ActionBarDrawerToggle(
this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawer_layout.addDrawerListener(toggle)
toggle.syncState()
setupAdapters()
LocalBroadcastManager.getInstance(this).registerReceiver(userDataChangeReceiver,
IntentFilter(BROADCAST_USER_DATA_CHANGE))
channel_list.setOnItemClickListener { _, _, i, _ ->
selectedChannel = MessageService.channels[i]
drawer_layout.closeDrawer(GravityCompat.START)
updateWithChanel()
}
if (App.prefs.isLoggedIn) {
AuthService.findUserByEmail(this) {}
}
}
override fun onDestroy() {
socket.disconnect()
LocalBroadcastManager.getInstance(this).unregisterReceiver(userDataChangeReceiver)
super.onDestroy()
}
private val userDataChangeReceiver = object: BroadcastReceiver () {
override fun onReceive(context: Context, intent: Intent?) {
if (App.prefs.isLoggedIn) {
userNameNavHeader.text = UserDataService.name
userEmailNavHeader.text = UserDataService.email
val resourceId = resources.getIdentifier(UserDataService.avatarName, "drawable",
packageName)
userImageNavHeader.setImageResource(resourceId)
userImageNavHeader.setBackgroundColor(UserDataService.returnAvatarColor(UserDataService.avatarColor))
loginBtnNavHeader.text = "Logout"
MessageService.getChannels { complete ->
if(complete) {
if (MessageService.channels.count()>0) {
selectedChannel = MessageService.channels[0]
channelAdapter.notifyDataSetChanged()
updateWithChanel()
}
}
}
}
}
}
fun updateWithChanel() {
mainChannelName.text = "#${selectedChannel?.name}"
if (selectedChannel != null) {
MessageService.getMessages(selectedChannel!!.id) { complete ->
if (complete) {
// for (message in MessageService.messages) {
// println(message.message)
// }
messageAdapter.notifyDataSetChanged()
if (messageAdapter.itemCount > 0) {
messageListView.smoothScrollToPosition(messageAdapter.itemCount - 1)
}
}
}
}
}
override fun onBackPressed() {
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
drawer_layout.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
fun loginBtnNavClicked(view: View) {
if (App.prefs.isLoggedIn) {
// log out
UserDataService.logout()
channelAdapter.notifyDataSetChanged()
messageAdapter.notifyDataSetChanged()
userNameNavHeader.text = ""
userEmailNavHeader.text = ""
userImageNavHeader.setImageResource(R.drawable.profiledefault)
userImageNavHeader.setBackgroundColor(Color.TRANSPARENT)
loginBtnNavHeader.text = "Login"
mainChannelName.text = "Please Log In"
} else {
val loginIntent = Intent(this, loginActivity::class.java)
startActivity(loginIntent)
}
}
fun addChannelClicked(view: View) {
if(App.prefs.isLoggedIn) {
val builder = AlertDialog.Builder(this)
val dialogView = layoutInflater.inflate(R.layout.add_channel_dialog,null)
builder.setView(dialogView)
.setPositiveButton("Add") { _, _ ->
val nameTextField = dialogView.findViewById<EditText>(R.id.addChannelNameTxt)
val descTextField = dialogView.findViewById<EditText>(R.id.addChannelDescTxt)
val channelName = nameTextField.text.toString()
val channelDesc = descTextField.text.toString()
socket.emit("newChannel", channelName, channelDesc)
}
.setNegativeButton("Cancel") { _, _ ->
}
.show()
}
}
private val onNewChannel = Emitter.Listener { args ->
// println(args[0] as String)
if(App.prefs.isLoggedIn){
runOnUiThread {
val channelName = args[0] as String
val channelDescription = args[1] as String
val channelId = args[2] as String
val newChannel = Channel(channelName, channelDescription, channelId)
MessageService.channels.add(newChannel)
channelAdapter.notifyDataSetChanged()
}
}
}
private val onNewMessage = Emitter.Listener { args ->
if(App.prefs.isLoggedIn) {
runOnUiThread {
val channelId = args[2] as String
if(channelId == selectedChannel?.id) {
val msgBody = args[0] as String
val userName = args[3] as String
val userAvatar = args[4] as String
val userAvatarColor = args[5] as String
val id = args[6] as String
val timeStamp = args[7] as String
val newMessage = Message(msgBody, userName, channelId, userAvatar, userAvatarColor, id, timeStamp)
MessageService.messages.add(newMessage)
messageAdapter.notifyDataSetChanged()
messageListView.smoothScrollToPosition(messageAdapter.itemCount - 1)
}
}
}
}
fun sendMesgBtnClicked(view: View) {
if (App.prefs.isLoggedIn && messageTextField.text.isNotEmpty() && selectedChannel != null) {
val userId = UserDataService.id
val channelId = selectedChannel!!.id
socket.emit("newMessage", messageTextField.text.toString(), userId, channelId,
UserDataService.name, UserDataService.avatarName, UserDataService.avatarColor)
messageTextField.text.clear()
hideKeyboard()
}
}
fun hideKeyboard () {
val inputManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
if (inputManager.isAcceptingText) {
inputManager.hideSoftInputFromWindow(currentFocus.windowToken, 0)
}
}
}
| gpl-3.0 | 515a74eb86e6f8a16bfec1c5e20d141a | 39.06087 | 118 | 0.634903 | 5.316792 | false | false | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateCheckResults.kt | 1 | 1772 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.updateSettings.impl
import com.intellij.ide.externalComponents.ExternalComponentSource
import com.intellij.ide.externalComponents.UpdatableExternalComponent
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.openapi.util.BuildNumber
class UpdateChain internal constructor(val chain: List<BuildNumber>, val size: String?)
class CheckForUpdateResult {
val state: UpdateStrategy.State
val newBuild: BuildInfo?
val updatedChannel: UpdateChannel?
val patches: UpdateChain?
val error: Exception?
internal constructor(newBuild: BuildInfo?, updatedChannel: UpdateChannel?, patches: UpdateChain?) {
this.state = UpdateStrategy.State.LOADED
this.newBuild = newBuild
this.updatedChannel = updatedChannel
this.patches = patches
this.error = null
}
internal constructor(state: UpdateStrategy.State, error: Exception?) {
this.state = state
this.newBuild = null
this.updatedChannel = null
this.patches = null
this.error = error
}
}
/**
* [enabled] - new versions of enabled plugins compatible with the specified build
*
* [disabled] - new versions of disabled plugins compatible with the specified build
*
* [incompatible] - plugins that would become incompatible and don't have updates compatible with the specified build
*/
data class PluginUpdates(
val enabled: Collection<PluginDownloader>,
val disabled: Collection<PluginDownloader>,
val incompatible: Collection<IdeaPluginDescriptor>,
)
data class ExternalUpdate(
val source: ExternalComponentSource,
val components: Collection<UpdatableExternalComponent>
)
| apache-2.0 | 8903a0cba1195a52d30208937a1280da | 33.745098 | 140 | 0.778781 | 4.789189 | false | true | false | false |
allotria/intellij-community | uast/uast-common/src/org/jetbrains/uast/util/IndentedPrintingVisitor.kt | 13 | 1056 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.util
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import kotlin.reflect.KClass
abstract class IndentedPrintingVisitor(val shouldIndent: (PsiElement) -> Boolean) : PsiElementVisitor() {
constructor(vararg kClasses: KClass<*>) : this({ psi -> kClasses.any { it.isInstance(psi) } })
private val builder = StringBuilder()
var level = 0
private set
override fun visitElement(element: PsiElement) {
val charSequence = render(element)
if (charSequence != null) {
builder.append(" ".repeat(level))
builder.append(charSequence)
builder.appendln()
}
val shouldIndent = shouldIndent(element)
if (shouldIndent) level++
element.acceptChildren(this)
if (shouldIndent) level--
}
protected abstract fun render(element: PsiElement): CharSequence?
val result: String
get() = builder.toString()
} | apache-2.0 | 53a7b28d2618bd7ee5b02559418a0fe1 | 30.088235 | 140 | 0.719697 | 4.275304 | false | false | false | false |
DeflatedPickle/Quiver | zipstep/src/main/kotlin/com/deflatedpickle/quiver/zipstep/ZipStepSettings.kt | 1 | 937 | /* Copyright (c) 2021 DeflatedPickle under the MIT license */
package com.deflatedpickle.quiver.zipstep
import kotlinx.serialization.Required
import kotlinx.serialization.Serializable
import net.lingala.zip4j.model.ZipParameters
import net.lingala.zip4j.model.enums.CompressionLevel
import net.lingala.zip4j.model.enums.CompressionMethod
@Serializable
data class ZipStepSettings(
@Required var compressionMethod: CompressionMethod = CompressionMethod.DEFLATE,
@Required var compressionLevel: CompressionLevel = CompressionLevel.NORMAL,
@Required var readHiddenFiles: Boolean = true,
@Required var readHiddenFolders: Boolean = true,
@Required var writeExtendedLocalFileHeader: Boolean = true,
@Required var fileComment: String = "",
@Required var symbolicLinkAction: ZipParameters.SymbolicLinkAction = ZipParameters.SymbolicLinkAction.INCLUDE_LINKED_FILE_ONLY,
@Required var unixMode: Boolean = false
)
| mit | 6832a4fb3b6b134d21849c8939076256 | 43.619048 | 131 | 0.80683 | 4.461905 | false | false | false | false |
F43nd1r/acra-backend | acrarium/src/main/kotlin/com/faendir/acra/ui/component/Card.kt | 1 | 2075 | /*
* (C) Copyright 2018 Lukas Morawietz (https://github.com/F43nd1r)
*
* 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.faendir.acra.ui.component
import com.faendir.acra.ui.ext.booleanProperty
import com.vaadin.flow.component.Component
import com.vaadin.flow.component.HasComponents
import com.vaadin.flow.component.HasSize
import com.vaadin.flow.component.HasStyle
import com.vaadin.flow.component.Tag
import com.vaadin.flow.component.dependency.JsModule
import com.vaadin.flow.component.littemplate.LitTemplate
/**
* @author lukas
* @since 18.10.18
*/
@Tag("acrarium-card")
@JsModule("./elements/card.ts")
class Card() : LitTemplate(), HasSize, HasStyle, HasComponents, HasSlottedComponents<Card.Slot> {
constructor(vararg components: Component) : this() {
add(*components)
}
fun setHeader(vararg components: Component) {
add(Slot.HEADER, *components)
}
var allowCollapse by booleanProperty("canCollapse")
var isCollapsed by booleanProperty("isCollapsed")
var dividerEnabled by booleanProperty("divider")
fun setHeaderColor(textColor: String?, backgroundColor: String?) {
style["--acrarium-card-header-text-color"] = textColor
style["--acrarium-card-header-color"] = backgroundColor
}
fun removeContent() {
children.filter { it.element.getAttribute("slot") == null }.forEach { this.remove(it) }
}
fun hasContent() = children.anyMatch { it.element.getAttribute("slot") == null }
enum class Slot : HasSlottedComponents.Slot {
HEADER
}
} | apache-2.0 | a261e0bd31f4525c239a5a7863f1b63a | 33.6 | 97 | 0.724819 | 4.044834 | false | false | false | false |
udevbe/westford | compositor/src/main/kotlin/org/westford/compositor/drm/egl/DrmEglPlatformFactory.kt | 3 | 14597 | /*
* Westford Wayland Compositor.
* Copyright (C) 2016 Erik De Rijcke
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.westford.compositor.drm.egl
import org.freedesktop.jaccall.Pointer
import org.westford.compositor.core.GlRenderer
import org.westford.compositor.core.OutputFactory
import org.westford.compositor.core.OutputGeometry
import org.westford.compositor.core.OutputMode
import org.westford.compositor.drm.DrmOutput
import org.westford.compositor.drm.DrmPlatform
import org.westford.compositor.protocol.WlOutput
import org.westford.compositor.protocol.WlOutputFactory
import org.westford.launch.LifeCycleSignals
import org.westford.launch.Privileges
import org.westford.nativ.libEGL.EglCreatePlatformWindowSurfaceEXT
import org.westford.nativ.libEGL.EglGetPlatformDisplayEXT
import org.westford.nativ.libEGL.LibEGL
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_BACK_BUFFER
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_CLIENT_APIS
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_CONTEXT_CLIENT_VERSION
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_EXTENSIONS
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_NONE
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_NO_CONTEXT
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_NO_DISPLAY
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_PLATFORM_GBM_KHR
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_RENDER_BUFFER
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_VENDOR
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_VERSION
import org.westford.nativ.libGLESv2.LibGLESv2
import org.westford.nativ.libgbm.Libgbm
import java.lang.String.format
import java.util.*
import java.util.logging.Logger
import javax.inject.Inject
class DrmEglPlatformFactory @Inject internal constructor(private val wlOutputFactory: WlOutputFactory,
private val outputFactory: OutputFactory,
private val privateDrmEglPlatformFactory: PrivateDrmEglPlatformFactory,
private val libgbm: Libgbm,
private val gbmBoFactory: GbmBoFactory,
private val libEGL: LibEGL,
private val libGLESv2: LibGLESv2,
private val drmPlatform: DrmPlatform,
private val drmEglOutputFactory: DrmEglOutputFactory,
private val glRenderer: GlRenderer,
private val lifeCycleSignals: LifeCycleSignals,
private val privileges: Privileges) {
fun create(): DrmEglPlatform {
val gbmDevice = this.libgbm.gbm_create_device(this.drmPlatform.drmFd)
val eglDisplay = createEglDisplay(gbmDevice)
val eglExtensions = Pointer.wrap<String>(String::class.java,
this.libEGL.eglQueryString(eglDisplay,
EGL_EXTENSIONS)).get()
val eglClientApis = Pointer.wrap<String>(String::class.java,
this.libEGL.eglQueryString(eglDisplay,
EGL_CLIENT_APIS)).get()
val eglVendor = Pointer.wrap<String>(String::class.java,
this.libEGL.eglQueryString(eglDisplay,
EGL_VENDOR)).get()
val eglVersion = Pointer.wrap<String>(String::class.java,
this.libEGL.eglQueryString(eglDisplay,
EGL_VERSION)).get()
LOGGER.info(format("Creating DRM EGL output:\n" + "\tEGL client apis: %s\n" + "\tEGL vendor: %s\n" + "\tEGL version: %s\n" + "\tEGL extensions: %s",
eglClientApis,
eglVendor,
eglVersion,
eglExtensions))
val eglConfig = this.glRenderer.eglConfig(eglDisplay,
eglExtensions)
val eglContext = createEglContext(eglDisplay,
eglConfig)
val drmOutputs = this.drmPlatform.renderOutputs
val drmEglRenderOutputs = ArrayList<DrmEglOutput>(drmOutputs.size)
val wlOutputs = ArrayList<WlOutput>(drmEglRenderOutputs.size)
drmOutputs.forEach {
drmEglRenderOutputs.add(createDrmEglRenderOutput(it,
gbmDevice,
eglDisplay,
eglContext,
eglConfig))
}
drmEglRenderOutputs.forEach {
wlOutputs.add(createWlOutput(it))
}
this.lifeCycleSignals.activateSignal.connect {
this.privileges.setDrmMaster(this.drmPlatform.drmFd)
wlOutputs.forEach {
val drmEglOutput = it.output.renderOutput as DrmEglOutput
drmEglOutput.setDefaultMode()
drmEglOutput.enable(it)
}
}
this.lifeCycleSignals.deactivateSignal.connect {
drmEglRenderOutputs.forEach {
it.disable()
}
this.privileges.dropDrmMaster(this.drmPlatform.drmFd)
}
return this.privateDrmEglPlatformFactory.create(gbmDevice,
eglDisplay,
eglContext,
eglExtensions,
wlOutputs)
}
private fun createWlOutput(drmEglOutput: DrmEglOutput): WlOutput {
val drmOutput = drmEglOutput.drmOutput
val drmModeConnector = drmOutput.drmModeConnector
val drmModeModeInfo = drmOutput.mode
val fallBackDpi = 96
var mmWidth = drmModeConnector.mmWidth
val hdisplay = drmOutput.mode.hdisplay
if (mmWidth == 0) {
mmWidth = (hdisplay * 25.4 / fallBackDpi).toInt()
}
var mmHeight = drmModeConnector.mmHeight
val vdisplay = drmOutput.mode.vdisplay
if (mmHeight == 0) {
mmHeight = (vdisplay * 25.4 / fallBackDpi).toInt()
}
//TODO gather more geo & drmModeModeInfo info
val outputGeometry = OutputGeometry(physicalWidth = mmWidth,
physicalHeight = mmHeight,
make = "unknown",
model = "unknown",
x = 0,
y = 0,
subpixel = drmModeConnector.drmModeSubPixel,
transform = 0)
val outputMode = OutputMode(width = hdisplay.toInt(),
height = vdisplay.toInt(),
refresh = drmOutput.mode.vrefresh,
flags = drmModeModeInfo.flags)
//FIXME deduce an output name from the drm connector
return this.wlOutputFactory.create(this.outputFactory.create(drmEglOutput,
"fixme",
outputGeometry,
outputMode))
}
private fun createEglDisplay(gbmDevice: Long): Long {
val noDisplayExtensions = Pointer.wrap<String>(String::class.java,
this.libEGL.eglQueryString(EGL_NO_DISPLAY,
EGL_EXTENSIONS))
if (noDisplayExtensions.address == 0L) {
throw RuntimeException("Could not query egl extensions.")
}
val extensions = noDisplayExtensions.get()
if (!extensions.contains("EGL_MESA_platform_gbm")) {
throw RuntimeException("Required extension EGL_MESA_platform_gbm not available.")
}
val eglGetPlatformDisplayEXT = Pointer.wrap<EglGetPlatformDisplayEXT>(EglGetPlatformDisplayEXT::class.java,
this.libEGL.eglGetProcAddress(Pointer.nref("eglGetPlatformDisplayEXT").address))
val eglDisplay = eglGetPlatformDisplayEXT.get()(EGL_PLATFORM_GBM_KHR,
gbmDevice,
0L)
if (eglDisplay == 0L) {
throw RuntimeException("eglGetDisplay() failed")
}
if (this.libEGL.eglInitialize(eglDisplay,
0L,
0L) == 0) {
throw RuntimeException("eglInitialize() failed")
}
return eglDisplay
}
private fun createEglContext(eglDisplay: Long,
config: Long): Long {
val eglContextAttribs = Pointer.nref(//@formatter:off
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
//@formatter:on
)
val context = this.libEGL.eglCreateContext(eglDisplay,
config,
EGL_NO_CONTEXT,
eglContextAttribs.address)
if (context == 0L) {
throw RuntimeException("eglCreateContext() failed")
}
return context
}
private fun createDrmEglRenderOutput(drmOutput: DrmOutput,
gbmDevice: Long,
eglDisplay: Long,
eglContext: Long,
eglConfig: Long): DrmEglOutput {
val drmModeModeInfo = drmOutput.mode
//TODO test if format is supported (gbm_device_is_format_supported)?
val gbmSurface = this.libgbm.gbm_surface_create(gbmDevice,
drmModeModeInfo.hdisplay.toInt(),
drmModeModeInfo.vdisplay.toInt(),
Libgbm.GBM_FORMAT_XRGB8888,
Libgbm.GBM_BO_USE_SCANOUT or Libgbm.GBM_BO_USE_RENDERING)
if (gbmSurface == 0L) {
throw RuntimeException("failed to create gbm surface")
}
val eglSurface = createEglSurface(eglDisplay,
eglConfig,
gbmSurface)
this.libEGL.eglMakeCurrent(eglDisplay,
eglSurface,
eglSurface,
eglContext)
this.libGLESv2.glClearColor(1.0f,
1.0f,
1.0f,
1.0f)
this.libGLESv2.glClear(LibGLESv2.GL_COLOR_BUFFER_BIT)
this.libEGL.eglSwapBuffers(eglDisplay,
eglSurface)
val gbmBo = this.gbmBoFactory.create(gbmSurface)
val drmEglRenderOutput = this.drmEglOutputFactory.create(this.drmPlatform.drmFd,
gbmDevice,
gbmBo,
gbmSurface,
drmOutput,
eglSurface,
eglContext,
eglDisplay)
drmEglRenderOutput.setDefaultMode()
return drmEglRenderOutput
}
private fun createEglSurface(eglDisplay: Long,
config: Long,
gbmSurface: Long): Long {
val eglSurfaceAttribs = Pointer.nref(EGL_RENDER_BUFFER,
EGL_BACK_BUFFER,
EGL_NONE)
val eglGetPlatformDisplayEXT = Pointer.wrap<EglCreatePlatformWindowSurfaceEXT>(EglCreatePlatformWindowSurfaceEXT::class.java,
this.libEGL.eglGetProcAddress(Pointer.nref("eglCreatePlatformWindowSurfaceEXT").address))
val eglSurface = eglGetPlatformDisplayEXT.get()(eglDisplay,
config,
gbmSurface,
eglSurfaceAttribs.address)
if (eglSurface == 0L) {
throw RuntimeException("eglCreateWindowSurface() failed")
}
return eglSurface
}
companion object {
private val LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME)
}
}
| agpl-3.0 | 7da3ba6617fd8bfd11a5ce4765c01fa8 | 48.481356 | 176 | 0.497568 | 6.169484 | false | false | false | false |
leafclick/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/BaseCommitExecutorAction.kt | 1 | 1829 | // 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.openapi.vcs.changes.actions
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.vcs.actions.getContextCommitWorkflowHandler
import com.intellij.openapi.vcs.changes.CommitExecutor
import com.intellij.vcs.commit.CommitWorkflowHandler
abstract class BaseCommitExecutorAction : DumbAwareAction() {
init {
isEnabledInModalContext = true
}
override fun update(e: AnActionEvent) {
val workflowHandler = e.getContextCommitWorkflowHandler()
val executor = getCommitExecutor(workflowHandler)
e.presentation.isVisible = workflowHandler != null && executor != null
e.presentation.isEnabled = workflowHandler != null && executor != null && workflowHandler.isExecutorEnabled(executor)
}
override fun actionPerformed(e: AnActionEvent) {
val workflowHandler = e.getContextCommitWorkflowHandler()!!
val executor = getCommitExecutor(workflowHandler)!!
workflowHandler.execute(executor)
}
protected open val executorId: String = ""
protected open fun getCommitExecutor(handler: CommitWorkflowHandler?) = handler?.getExecutor(executorId)
companion object {
fun AnActionEvent.getAmendCommitModePrefix(): String {
val isAmend = getContextCommitWorkflowHandler()?.amendCommitHandler?.isAmendCommitMode == true
return if (isAmend) "Amend " else ""
}
}
}
internal class DefaultCommitExecutorAction(private val executor: CommitExecutor) : BaseCommitExecutorAction() {
init {
templatePresentation.text = executor.actionText
}
override fun getCommitExecutor(handler: CommitWorkflowHandler?): CommitExecutor? = executor
} | apache-2.0 | a2699623a07bae2cc9c615e403dbaa35 | 37.93617 | 140 | 0.780208 | 5.210826 | false | false | false | false |
zdary/intellij-community | platform/platform-api/src/com/intellij/openapi/wm/ToolWindowManager.kt | 2 | 7671 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.wm
import com.intellij.openapi.Disposable
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.ui.popup.BalloonBuilder
import com.intellij.openapi.util.NlsContexts
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.NonNls
import java.util.function.Consumer
import java.util.function.Predicate
import javax.swing.Icon
import javax.swing.JComponent
import javax.swing.event.HyperlinkListener
/**
* If you want to register a toolwindow, which will be enabled during the dumb mode, please use [ToolWindowManager]'s
* registration methods which have 'canWorkInDumbMode' parameter.
*/
abstract class ToolWindowManager {
companion object {
@JvmStatic
fun getInstance(project: Project): ToolWindowManager = project.getService(ToolWindowManager::class.java)
}
abstract val focusManager: IdeFocusManager
abstract fun canShowNotification(toolWindowId: String): Boolean
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Use ToolWindowFactory and toolWindow extension point")
fun registerToolWindow(id: String, component: JComponent, anchor: ToolWindowAnchor): ToolWindow {
return registerToolWindow(RegisterToolWindowTask(id = id, component = component, anchor = anchor, canCloseContent = false, canWorkInDumbMode = false))
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Use ToolWindowFactory and toolWindow extension point")
@ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
fun registerToolWindow(id: String,
component: JComponent,
anchor: ToolWindowAnchor,
@Suppress("UNUSED_PARAMETER") parentDisposable: Disposable,
canWorkInDumbMode: Boolean): ToolWindow {
return registerToolWindow(RegisterToolWindowTask(id = id, component = component, anchor = anchor, canWorkInDumbMode = canWorkInDumbMode))
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Use ToolWindowFactory and toolWindow extension point")
fun registerToolWindow(id: String, canCloseContent: Boolean, anchor: ToolWindowAnchor): ToolWindow {
return registerToolWindow(RegisterToolWindowTask(id = id, anchor = anchor, canCloseContent = canCloseContent, canWorkInDumbMode = false))
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Use ToolWindowFactory and toolWindow extension point")
fun registerToolWindow(id: String,
canCloseContent: Boolean,
anchor: ToolWindowAnchor,
secondary: Boolean): ToolWindow {
return registerToolWindow(RegisterToolWindowTask(id = id, anchor = anchor, sideTool = secondary, canCloseContent = canCloseContent, canWorkInDumbMode = false))
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Use ToolWindowFactory and toolWindow extension point")
fun registerToolWindow(id: String,
canCloseContent: Boolean,
anchor: ToolWindowAnchor,
@Suppress("UNUSED_PARAMETER") parentDisposable: Disposable,
canWorkInDumbMode: Boolean): ToolWindow {
return registerToolWindow(RegisterToolWindowTask(id = id, anchor = anchor, canCloseContent = canCloseContent, canWorkInDumbMode = canWorkInDumbMode))
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Use ToolWindowFactory and toolWindow extension point")
fun registerToolWindow(id: String,
canCloseContent: Boolean,
anchor: ToolWindowAnchor,
@Suppress("UNUSED_PARAMETER") parentDisposable: Disposable,
canWorkInDumbMode: Boolean,
secondary: Boolean): ToolWindow {
return registerToolWindow(RegisterToolWindowTask(id = id, anchor = anchor, sideTool = secondary, canCloseContent = canCloseContent, canWorkInDumbMode = canWorkInDumbMode))
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Use ToolWindowFactory and toolWindow extension point")
@ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
fun registerToolWindow(id: String,
canCloseContent: Boolean,
anchor: ToolWindowAnchor,
@Suppress("UNUSED_PARAMETER") parentDisposable: Disposable): ToolWindow {
return registerToolWindow(RegisterToolWindowTask(id = id, anchor = anchor, canCloseContent = canCloseContent, canWorkInDumbMode = false))
}
abstract fun registerToolWindow(task: RegisterToolWindowTask): ToolWindow
/**
* does nothing if tool window with specified isn't registered.
*/
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Use ToolWindowFactory and toolWindow extension point")
abstract fun unregisterToolWindow(id: String)
abstract fun activateEditorComponent()
/**
* @return `true` if and only if editor component is active.
*/
abstract val isEditorComponentActive: Boolean
/**
* @return array of `id`s of all registered tool windows.
*/
abstract val toolWindowIds: Array<String>
abstract val toolWindowIdSet: Set<String>
/**
* @return `ID` of currently active tool window or `null` if there is no active
* tool window.
*/
abstract val activeToolWindowId: String?
/**
* @return `ID` of tool window that was activated last time.
*/
abstract val lastActiveToolWindowId: String?
/**
* @return registered tool window with specified `id`. If there is no registered
* tool window with specified `id` then the method returns `null`.
* @see ToolWindowId
*/
abstract fun getToolWindow(@NonNls id: String?): ToolWindow?
/**
* Puts specified runnable to the tail of current command queue.
*/
abstract fun invokeLater(runnable: Runnable)
abstract fun notifyByBalloon(toolWindowId: String, type: MessageType, @NlsContexts.NotificationContent htmlBody: String)
fun notifyByBalloon(toolWindowId: String,
type: MessageType,
@NlsContexts.PopupContent htmlBody: String,
icon: Icon?,
listener: HyperlinkListener?) {
notifyByBalloon(ToolWindowBalloonShowOptions(toolWindowId = toolWindowId, type = type, htmlBody = htmlBody, icon = icon, listener = listener))
}
abstract fun notifyByBalloon(options: ToolWindowBalloonShowOptions)
abstract fun getToolWindowBalloon(id: String): Balloon?
abstract fun isMaximized(window: ToolWindow): Boolean
abstract fun setMaximized(window: ToolWindow, maximized: Boolean)
/*
* Returns visual representation of tool window location
* @see AllIcons.Actions#MoveToBottomLeft ... com.intellij.icons.AllIcons.Actions#MoveToWindow icon set
*/
open fun getLocationIcon(id: String, fallbackIcon: Icon): Icon = fallbackIcon
abstract fun getLastActiveToolWindow(condition: Predicate<in JComponent>?): ToolWindow?
}
data class ToolWindowBalloonShowOptions(val toolWindowId: String,
val type: MessageType,
@NlsContexts.PopupContent val htmlBody: String,
val icon: Icon? = null,
val listener: HyperlinkListener? = null,
val balloonCustomizer: Consumer<BalloonBuilder>? = null) | apache-2.0 | fa3601ebcb21fb0676a462cfcb005f89 | 43.346821 | 175 | 0.706557 | 5.767669 | false | false | false | false |
leafclick/intellij-community | platform/lang-impl/src/com/intellij/ide/ui/TargetPresentationMainRenderer.kt | 1 | 2533 | // 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.ide.ui
import com.intellij.navigation.LocationPresentation.DEFAULT_LOCATION_PREFIX
import com.intellij.navigation.LocationPresentation.DEFAULT_LOCATION_SUFFIX
import com.intellij.navigation.TargetPopupPresentation
import com.intellij.ui.ColoredListCellRenderer
import com.intellij.ui.JBColor
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.SimpleTextAttributes.*
import com.intellij.ui.speedSearch.SearchAwareRenderer
import com.intellij.ui.speedSearch.SpeedSearchUtil.appendColoredFragmentForMatcher
import com.intellij.util.text.MatcherHolder
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.ApiStatus.Experimental
import javax.swing.JList
@Experimental
abstract class TargetPresentationMainRenderer<T> : ColoredListCellRenderer<T>(), SearchAwareRenderer<T> {
protected abstract fun getPresentation(value: T): TargetPopupPresentation?
final override fun getItemSearchString(item: T): String? = getPresentation(item)?.presentableText
final override fun customizeCellRenderer(list: JList<out T>, value: T, index: Int, selected: Boolean, hasFocus: Boolean) {
val presentation = getPresentation(value) ?: run {
append("Invalid", ERROR_ATTRIBUTES)
return
}
val attributes = presentation.presentableAttributes
val bgColor = attributes?.backgroundColor ?: UIUtil.getListBackground()
icon = presentation.icon
background = if (selected) UIUtil.getListSelectionBackground(hasFocus) else bgColor
val nameAttributes = attributes?.let(::fromTextAttributes)
?: SimpleTextAttributes(STYLE_PLAIN, list.foreground)
val matcher = MatcherHolder.getAssociatedMatcher(list)
appendColoredFragmentForMatcher(presentation.presentableText, this, nameAttributes, matcher, bgColor, selected)
presentation.locationText?.let { locationText ->
val locationAttributes = presentation.locationAttributes?.let {
merge(defaultLocationAttributes, fromTextAttributes(it))
} ?: defaultLocationAttributes
append(DEFAULT_LOCATION_PREFIX, defaultLocationAttributes)
append("in ", defaultLocationAttributes)
append(locationText, locationAttributes)
append(DEFAULT_LOCATION_SUFFIX, defaultLocationAttributes)
}
}
companion object {
private val defaultLocationAttributes = SimpleTextAttributes(STYLE_PLAIN, JBColor.GRAY)
}
}
| apache-2.0 | 22c30f57997d2d6bcddc44ac837dba5b | 45.054545 | 140 | 0.789578 | 4.976424 | false | false | false | false |
zdary/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/fixtures/ActionLinkFixture.kt | 8 | 3009 | // 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.testGuiFramework.fixtures
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.testGuiFramework.impl.findComponent
import com.intellij.ui.components.labels.ActionLink
import org.fest.swing.core.MouseButton
import org.fest.swing.core.MouseClickInfo
import org.fest.swing.core.Robot
import org.fest.swing.driver.ComponentDriver
import org.fest.swing.driver.JComponentDriver
import java.awt.Component
import java.awt.Container
import java.awt.Point
class ActionLinkFixture constructor(robot: Robot, target: ActionLink) : JComponentFixture<ActionLinkFixture, ActionLink>(
ActionLinkFixture::class.java, robot, target) {
init {
replaceDriverWith(ActionLinkDriver(robot))
}
internal class ActionLinkDriver(robot: Robot) : JComponentDriver<ActionLink>(robot) {
override fun click(c: ActionLink) {
clickActionLinkText(c, MouseButton.LEFT_BUTTON, 1)
}
override fun click(c: ActionLink, button: MouseButton) {
clickActionLinkText(c, button, 1)
}
override fun click(c: ActionLink, mouseClickInfo: MouseClickInfo) {
clickActionLinkText(c, mouseClickInfo.button(), mouseClickInfo.times())
}
override fun doubleClick(c: ActionLink) {
clickActionLinkText(c, MouseButton.LEFT_BUTTON, 2)
}
override fun rightClick(c: ActionLink) {
clickActionLinkText(c, MouseButton.RIGHT_BUTTON, 2)
}
override fun click(c: ActionLink, button: MouseButton, times: Int) {
clickActionLinkText(c, button, times)
}
override fun click(c: ActionLink, where: Point) {
click(c, where, MouseButton.LEFT_BUTTON, 1)
}
private fun clickActionLinkText(c: Component, mouseButton: MouseButton, times: Int) {
assert(c is ActionLink)
val textRectangleCenter = (c as ActionLink).textRectangleCenter
click(c, textRectangleCenter, mouseButton, times)
}
private fun click(c: Component, where: Point, mouseButton: MouseButton, times: Int) {
ComponentDriver.checkInEdtEnabledAndShowing(c)
this.robot.click(c, where, mouseButton, times)
}
}
companion object {
fun findByActionId(actionId: String, robot: Robot, container: Container?): ActionLinkFixture {
val actionLink = robot.findComponent(container, ActionLink::class.java) {
if (it.isVisible && it.isShowing)
actionId == ActionManager.getInstance().getId(it.action)
else
false
}
return ActionLinkFixture(robot, actionLink)
}
fun actionLinkFixtureByName(actionName: String, robot: Robot, container: Container): ActionLinkFixture {
val actionLink = robot.findComponent(container, ActionLink::class.java) {
if (it.isVisible && it.isShowing) {
it.text == actionName
}
else false
}
return ActionLinkFixture(robot, actionLink)
}
}
}
| apache-2.0 | fb5fe9e1f3d89eaa56310431ebee8d98 | 32.808989 | 140 | 0.71984 | 4.386297 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/boxInline/anonymousObject/properRecapturingInClass/lambdaChain_3.kt | 3 | 699 | // FILE: 1.kt
package test
class A {
val param = "start"
var result = "fail"
var addParam = "_additional_"
inline fun inlineFun(arg: String, crossinline f: (String) -> Unit) {
{
f(arg + addParam)
}()
}
fun box(): String {
inlineFun("1") { c ->
{
inlineFun("2") { a ->
{
result = param + c + a
}()
}
}()
}
return if (result == "start1_additional_2_additional_") "OK" else "fail: $result"
}
}
// FILE: 2.kt
//NO_CHECK_LAMBDA_INLINING
import test.*
fun box(): String {
return A().box()
}
| apache-2.0 | 7c45563762d5a4377bda43a50310d132 | 16.475 | 89 | 0.423462 | 3.905028 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-tests/testSrc/com/intellij/internal/statistics/StatisticsTestEventValidator.kt | 12 | 2930 | // 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.statistics
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import com.google.gson.JsonPrimitive
import kotlin.test.assertEquals
import kotlin.test.assertTrue
object StatisticsTestEventValidator {
fun assertLogEventIsValid(json: JsonObject, isState: Boolean, vararg dataOptions: String) {
assertTrue(json.get("time").isJsonPrimitive)
assertTrue(json.get("session").isJsonPrimitive)
assertTrue(isValid(json.get("session").asString))
assertTrue(json.get("bucket").isJsonPrimitive)
assertTrue(isValid(json.get("bucket").asString))
assertTrue(json.get("build").isJsonPrimitive)
assertTrue(isValid(json.get("build").asString))
assertTrue(json.get("group").isJsonObject)
assertTrue(json.getAsJsonObject("group").get("id").isJsonPrimitive)
assertTrue(json.getAsJsonObject("group").get("version").isJsonPrimitive)
assertTrue(isValid(json.getAsJsonObject("group").get("id").asString))
assertTrue(isValid(json.getAsJsonObject("group").get("version").asString))
assertTrue(json.get("event").isJsonObject)
assertTrue(json.getAsJsonObject("event").get("id").isJsonPrimitive)
assertEquals(isState, json.getAsJsonObject("event").has("state"))
if (isState) {
assertTrue(json.getAsJsonObject("event").get("state").asBoolean)
}
assertEquals(!isState, json.getAsJsonObject("event").has("count"))
if (!isState) {
assertTrue(json.getAsJsonObject("event").get("count").asJsonPrimitive.isNumber)
}
assertTrue(json.getAsJsonObject("event").get("data").isJsonObject)
assertTrue(isValid(json.getAsJsonObject("event").get("id").asString))
val obj = json.getAsJsonObject("event").get("data").asJsonObject
validateJsonObject(dataOptions, obj)
}
private fun validateJsonObject(dataOptions: Array<out String>, obj: JsonObject) {
for (option in dataOptions) {
assertTrue(isValid(option))
when (val jsonElement = obj.get(option)) {
is JsonPrimitive -> assertTrue(isValid(jsonElement.asString))
is JsonArray -> {
for (dataPart in jsonElement) {
if (dataPart is JsonObject) {
validateJsonObject(dataPart.keySet().toTypedArray(), dataPart)
}
else {
assertTrue(isValid(dataPart.asString))
}
}
}
is JsonObject -> {
validateJsonObject(jsonElement.keySet().toTypedArray(), jsonElement)
}
}
}
}
fun isValid(str : String) : Boolean {
val noTabsOrLineSeparators = str.indexOf("\r") == -1 && str.indexOf("\n") == -1 && str.indexOf("\t") == -1
val noQuotes = str.indexOf("\"") == -1
return noTabsOrLineSeparators && noQuotes && str.matches("[\\p{ASCII}]*".toRegex())
}
} | apache-2.0 | f3c8519582367219d91ddd6449241dea | 38.08 | 140 | 0.685324 | 4.514638 | false | false | false | false |
FTL-Lang/FTL-Compiler | src/main/kotlin/com/thomas/needham/ftl/frontend/lexer/Span.kt | 1 | 3040 | /*
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.SourceFile
/**
* Class to represent a location within a source file
* @author Thomas Needham
*/
class Span {
/**
* The SourceFile that this span is contained in
* @see SourceFile
*/
val file: SourceFile
/**
* The Line that this span starts on
*/
val beginLine: Int
/**
* The Column that this span starts on
*/
val beginColumn: Int
/**
* The Line that this span ends on
*/
val endLine: Int
/**
* The Column that this span ends on
*/
val endColumn: Int
/**
* Constructor for Span
* @param sourceFile The SourceFile that this span is contained in
* @param beginLine The Line that this span starts on
* @param beginColumn The Column that this span starts on
* @param endLine The Line that this span ends on Leave blank if unknown
* @param endColumn The Column that this span ends on Leave blank if unknown
* @see SourceFile
*/
constructor(sourceFile: SourceFile, beginLine: Int, beginColumn: Int, endLine: Int = -1, endColumn: Int = -1) {
this.file = sourceFile
this.beginLine = beginLine
this.beginColumn = beginColumn
this.endLine = endLine
this.endColumn = endColumn
}
/**
* Function to get the beginning location of this span
* @return A string which represents the beginning of this span
*/
fun getBeginPosition(): String {
return "Line: ${beginLine}, Column: ${beginColumn}"
}
/**
* Function to get the ending location of this span
* @return A string which represents the end of this span
*/
fun getEndPosition(): String {
return "Line: ${endLine}, Column: ${endColumn}"
}
/**
* Function to get a string which represents this span
* @return A string that represents this span
*/
override fun toString(): String {
return "${file.file.name}: ${getBeginPosition()} To ${getEndPosition()}"
}
}
| mit | aee41a290ecf39100f095e2ea704369a | 29.707071 | 112 | 0.715789 | 4.239888 | false | false | false | false |
ingokegel/intellij-community | plugins/repository-search/src/main/kotlin/org/jetbrains/idea/packagesearch/http/HttpWrapper.kt | 1 | 4199 | /*
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* 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.jetbrains.idea.packagesearch.http
import com.intellij.openapi.diagnostic.Logger
import com.intellij.util.castSafelyTo
import com.intellij.util.io.HttpRequests
import kotlinx.coroutines.suspendCancellableCoroutine
import org.jetbrains.idea.reposearch.DependencySearchBundle
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.io.OutputStream
import java.net.HttpURLConnection
import java.util.concurrent.ConcurrentHashMap
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
class HttpWrapper {
private val logger = Logger.getInstance(HttpWrapper::class.java)
private val cache = ConcurrentHashMap<String, String>()
internal suspend fun requestString(
url: String,
acceptContentType: String,
timeoutInSeconds: Int = 10,
headers: List<Pair<String, String>>,
useCache: Boolean = false,
verbose: Boolean = true
): String = suspendCancellableCoroutine { cont ->
try {
val cacheKey = getCacheKey(url, acceptContentType, timeoutInSeconds, headers)
if (useCache) {
cache[cacheKey]?.let { cont.resume(it) }
}
val builder = HttpRequests.request(url)
.productNameAsUserAgent()
.accept(acceptContentType)
.connectTimeout(timeoutInSeconds * 1000)
.readTimeout(timeoutInSeconds * 1000)
.tuner { connection ->
headers.forEach {
connection.setRequestProperty(it.first, it.second)
}
}
builder.connect { request ->
val statusCode = request.connection.castSafelyTo<HttpURLConnection>()?.responseCode ?: -1
val responseText = request.connection.getInputStream().use { it.readBytes { cont.isCancelled }.toString(Charsets.UTF_8) }
if (cont.isCancelled) return@connect
if (statusCode != HttpURLConnection.HTTP_OK && verbose) {
logger.trace(
"""
|
|<-- HTTP GET $url
| Accept: $acceptContentType
|${headers.joinToString("\n") { " ${it.first}: ${it.second}" }}
|
|--> RESPONSE HTTP $statusCode
|$responseText
|
""".trimMargin()
)
}
when {
responseText.isEmpty() -> cont.resumeWithException(EmptyBodyException())
else -> cont.resume(responseText).also { if (useCache) cache[cacheKey] = responseText }
}
}
}
catch (t: Throwable) {
cont.resumeWithException(t)
}
}
private fun getCacheKey(
url: String,
acceptContentType: String,
timeoutInSeconds: Int,
headers: List<Pair<String, String>>
) = (listOf(url, acceptContentType, timeoutInSeconds) + headers.map { it.toString() }).joinToString(":")
private fun InputStream.copyTo(out: OutputStream, bufferSize: Int = DEFAULT_BUFFER_SIZE, cancellationRequested: () -> Boolean): Long {
var bytesCopied: Long = 0
val buffer = ByteArray(bufferSize)
var bytes = read(buffer)
while (bytes >= 0 && !cancellationRequested()) {
out.write(buffer, 0, bytes)
bytesCopied += bytes
bytes = read(buffer)
}
return bytesCopied
}
private fun InputStream.readBytes(cancellationRequested: () -> Boolean): ByteArray {
val buffer = ByteArrayOutputStream(maxOf(DEFAULT_BUFFER_SIZE, this.available()))
copyTo(buffer, cancellationRequested = cancellationRequested)
return buffer.toByteArray()
}
}
internal class EmptyBodyException : RuntimeException(
DependencySearchBundle.message("reposearch.search.client.response.body.is.empty")
) | apache-2.0 | 6127e2cb2faa8f0632f2f4fc288b1c4d | 34.59322 | 136 | 0.683734 | 4.619362 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/data/coroutineStackFrames.kt | 1 | 5239 | // 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.debugger.coroutine.data
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.debugger.engine.JavaStackFrame
import com.intellij.debugger.engine.JavaValue
import com.intellij.debugger.impl.DebuggerContextImpl
import com.intellij.debugger.jdi.StackFrameProxyImpl
import com.intellij.debugger.ui.tree.render.DescriptorLabelListener
import com.intellij.icons.AllIcons
import com.intellij.openapi.application.ReadAction
import com.intellij.xdebugger.XSourcePosition
import com.intellij.xdebugger.frame.XCompositeNode
import com.intellij.xdebugger.frame.XValueChildrenList
import com.intellij.xdebugger.impl.frame.XDebuggerFramesList
import com.sun.jdi.Location
import org.jetbrains.kotlin.idea.debugger.coroutine.KotlinDebuggerCoroutinesBundle
import org.jetbrains.kotlin.idea.debugger.coroutine.KotlinVariableNameFinder
import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.safeCoroutineStackFrameProxy
import org.jetbrains.kotlin.idea.debugger.safeLocation
import org.jetbrains.kotlin.idea.debugger.stackFrame.KotlinStackFrame
/**
* Coroutine exit frame represented by a stack frames
* invokeSuspend():-1
* resumeWith()
*
*/
class CoroutinePreflightFrame(
val coroutineInfoData: CoroutineInfoData,
val frame: StackFrameProxyImpl,
val threadPreCoroutineFrames: List<StackFrameProxyImpl>,
val mode: SuspendExitMode,
firstFrameVariables: List<JavaValue> = coroutineInfoData.topFrameVariables()
) : CoroutineStackFrame(frame, null, firstFrameVariables) {
override fun isInLibraryContent() = false
override fun isSynthetic() = false
}
class CreationCoroutineStackFrame(
frame: StackFrameProxyImpl,
sourcePosition: XSourcePosition?,
val first: Boolean,
location: Location? = frame.safeLocation()
) : CoroutineStackFrame(frame, sourcePosition, emptyList(), false, location), XDebuggerFramesList.ItemWithSeparatorAbove {
override fun getCaptionAboveOf() =
KotlinDebuggerCoroutinesBundle.message("coroutine.dump.creation.trace")
override fun hasSeparatorAbove() =
first
}
open class CoroutineStackFrame(
frame: StackFrameProxyImpl,
private val position: XSourcePosition?,
private val spilledVariables: List<JavaValue> = emptyList(),
private val includeFrameVariables: Boolean = true,
location: Location? = frame.safeLocation(),
) : KotlinStackFrame(safeCoroutineStackFrameProxy(location, spilledVariables, frame)) {
init {
descriptor.updateRepresentation(null, DescriptorLabelListener.DUMMY_LISTENER)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
val frame = other as? JavaStackFrame ?: return false
return descriptor.frameProxy == frame.descriptor.frameProxy
}
override fun hashCode(): Int {
return descriptor.frameProxy.hashCode()
}
override fun buildVariablesThreadAction(debuggerContext: DebuggerContextImpl, children: XValueChildrenList, node: XCompositeNode) {
if (includeFrameVariables || spilledVariables.isEmpty()) {
super.buildVariablesThreadAction(debuggerContext, children, node)
val debugProcess = debuggerContext.debugProcess ?: return
addOptimisedVariables(debugProcess, children)
} else {
// ignore original frame variables
for (variable in spilledVariables) {
children.add(variable)
}
}
}
private fun addOptimisedVariables(debugProcess: DebugProcessImpl, children: XValueChildrenList) {
val visibleVariableNames by lazy { children.getUniqueNames() }
for (variable in spilledVariables) {
val name = variable.name
if (name !in visibleVariableNames) {
children.add(variable)
visibleVariableNames.add(name)
}
}
val declaredVariableNames = findVisibleVariableNames(debugProcess)
for (name in declaredVariableNames) {
if (name !in visibleVariableNames) {
children.add(createOptimisedVariableMessageNode(name))
}
}
}
private fun createOptimisedVariableMessageNode(name: String) =
createMessageNode(
KotlinDebuggerCoroutinesBundle.message("optimised.variable.message", "\'$name\'"),
AllIcons.General.Information
)
private fun XValueChildrenList.getUniqueNames(): MutableSet<String> {
val names = mutableSetOf<String>()
for (i in 0 until size()) {
names.add(getName(i))
}
return names
}
private fun findVisibleVariableNames(debugProcess: DebugProcessImpl): List<String> {
val location = stackFrameProxy.safeLocation() ?: return emptyList()
return ReadAction.nonBlocking<List<String>> {
KotlinVariableNameFinder(debugProcess)
.findVisibleVariableNames(location)
}.executeSynchronously()
}
override fun getSourcePosition() =
position ?: super.getSourcePosition()
}
| apache-2.0 | cf99de5b724a7961bd4255be4dc986c2 | 37.240876 | 158 | 0.726665 | 5.28125 | false | false | false | false |
siosio/intellij-community | plugins/git4idea/src/git4idea/merge/GitDefaultMergeDialogCustomizer.kt | 1 | 16601 | // 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.merge
import com.intellij.diff.DiffEditorTitleCustomizer
import com.intellij.dvcs.repo.Repository
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.openapi.util.text.HtmlBuilder
import com.intellij.openapi.util.text.HtmlChunk.br
import com.intellij.openapi.util.text.HtmlChunk.text
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.committed.CommittedChangesTreeBrowser
import com.intellij.openapi.vcs.changes.ui.ChangeListViewerDialog
import com.intellij.openapi.vcs.merge.MergeDialogCustomizer
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.components.ActionLink
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.JBLabel
import com.intellij.util.Consumer
import com.intellij.util.ui.components.BorderLayoutPanel
import com.intellij.vcs.log.Hash
import com.intellij.vcs.log.VcsCommitMetadata
import com.intellij.vcs.log.impl.HashImpl
import com.intellij.vcs.log.impl.VcsCommitMetadataImpl
import com.intellij.vcs.log.ui.details.MultipleCommitInfoDialog
import com.intellij.vcs.log.util.VcsLogUtil
import git4idea.GitBranch
import git4idea.GitRevisionNumber
import git4idea.GitUtil.*
import git4idea.GitVcs
import git4idea.changes.GitChangeUtils
import git4idea.history.GitCommitRequirements
import git4idea.history.GitHistoryUtils
import git4idea.history.GitLogUtil
import git4idea.history.GitLogUtil.readFullDetails
import git4idea.history.GitLogUtil.readFullDetailsForHashes
import git4idea.i18n.GitBundle
import git4idea.i18n.GitBundleExtensions.html
import git4idea.rebase.GitRebaseUtils
import git4idea.repo.GitRepository
import git4idea.repo.GitRepositoryManager
import org.jetbrains.annotations.Nls
import javax.swing.JPanel
internal open class GitDefaultMergeDialogCustomizer(
private val project: Project
) : MergeDialogCustomizer() {
override fun getMultipleFileMergeDescription(files: MutableCollection<VirtualFile>): String {
val repos = getRepositoriesForFiles(project, files)
.ifEmpty { getRepositories(project).filter { it.stagingAreaHolder.allConflicts.isNotEmpty() } }
val mergeBranches = repos.mapNotNull { resolveMergeBranch(it)?.presentable }.toSet()
if (mergeBranches.isNotEmpty()) {
val currentBranches = getCurrentBranchNameSet(repos)
return html(
"merge.dialog.description.merge.label.text",
mergeBranches.size, text(getFirstBranch(mergeBranches)).bold(),
currentBranches.size, text(getFirstBranch(currentBranches)).bold()
)
}
val rebaseOntoBranches = repos.mapNotNull { resolveRebaseOntoBranch(it) }
if (rebaseOntoBranches.isNotEmpty()) {
val singleCurrentBranch = getSingleCurrentBranchName(repos)
val singleOntoBranch = rebaseOntoBranches.toSet().singleOrNull()
return getDescriptionForRebase(singleCurrentBranch, singleOntoBranch?.branchName, singleOntoBranch?.hash)
}
val cherryPickCommitDetails = repos.mapNotNull { loadCherryPickCommitDetails(it) }
if (cherryPickCommitDetails.isNotEmpty()) {
val singleCherryPick = cherryPickCommitDetails.distinctBy { it.authorName + it.commitMessage }.singleOrNull()
return html(
"merge.dialog.description.cherry.pick.label.text",
cherryPickCommitDetails.size, text(cherryPickCommitDetails.single().shortHash).code(),
(singleCherryPick != null).toInt(),
text(singleCherryPick?.authorName ?: ""),
HtmlBuilder().append(br()).append(text(singleCherryPick?.commitMessage ?: "").code())
)
}
return super.getMultipleFileMergeDescription(files)
}
override fun getTitleCustomizerList(file: FilePath): DiffEditorTitleCustomizerList {
val repository = GitRepositoryManager.getInstance(project).getRepositoryForFileQuick(file) ?: return DEFAULT_CUSTOMIZER_LIST
return when (repository.state) {
Repository.State.MERGING -> getMergeTitleCustomizerList(repository, file)
Repository.State.REBASING -> getRebaseTitleCustomizerList(repository, file)
Repository.State.GRAFTING -> getCherryPickTitleCustomizerList(repository, file)
else -> DEFAULT_CUSTOMIZER_LIST
}
}
private fun getCherryPickTitleCustomizerList(repository: GitRepository, file: FilePath): DiffEditorTitleCustomizerList {
val cherryPickHead = tryResolveRef(repository, CHERRY_PICK_HEAD) ?: return DEFAULT_CUSTOMIZER_LIST
val mergeBase = GitHistoryUtils.getMergeBase(
repository.project,
repository.root,
CHERRY_PICK_HEAD,
HEAD
)?.rev ?: return DEFAULT_CUSTOMIZER_LIST
val leftTitleCustomizer = getTitleWithCommitsRangeDetailsCustomizer(
GitBundle.message("merge.dialog.diff.left.title.cherry.pick.label.text"),
repository,
file,
Pair(mergeBase, HEAD)
)
val rightTitleCustomizer = getTitleWithCommitDetailsCustomizer(
html("merge.dialog.diff.right.title.cherry.pick.label.text", cherryPickHead.toShortString()),
repository,
file,
cherryPickHead.asString()
)
return DiffEditorTitleCustomizerList(leftTitleCustomizer, null, rightTitleCustomizer)
}
@NlsSafe
private fun getFirstBranch(branches: Collection<String>): String = branches.first()
private fun getMergeTitleCustomizerList(repository: GitRepository, file: FilePath): DiffEditorTitleCustomizerList {
val currentBranchHash = getHead(repository) ?: return DEFAULT_CUSTOMIZER_LIST
val currentBranchPresentable = repository.currentBranchName ?: currentBranchHash.toShortString()
val mergeBranch = resolveMergeBranch(repository) ?: return DEFAULT_CUSTOMIZER_LIST
val mergeBranchHash = mergeBranch.hash
val mergeBase = GitHistoryUtils.getMergeBase(
repository.project,
repository.root,
currentBranchHash.asString(),
mergeBranchHash.asString()
)?.rev ?: return DEFAULT_CUSTOMIZER_LIST
val leftTitleCustomizer = getTitleWithCommitsRangeDetailsCustomizer(
html("merge.dialog.diff.title.changes.from.branch.label.text", text(currentBranchPresentable).bold()),
repository,
file,
Pair(mergeBase, currentBranchHash.asString())
)
val rightTitleCustomizer = getTitleWithCommitsRangeDetailsCustomizer(
html("merge.dialog.diff.title.changes.from.branch.label.text", text(mergeBranch.presentable).bold()),
repository,
file,
Pair(mergeBase, mergeBranchHash.asString())
)
return DiffEditorTitleCustomizerList(leftTitleCustomizer, null, rightTitleCustomizer)
}
private fun getRebaseTitleCustomizerList(repository: GitRepository, file: FilePath): DiffEditorTitleCustomizerList {
val currentBranchHash = getHead(repository) ?: return DEFAULT_CUSTOMIZER_LIST
val rebasingBranchPresentable = repository.currentBranchName ?: currentBranchHash.toShortString()
val upstreamBranch = resolveRebaseOntoBranch(repository) ?: return DEFAULT_CUSTOMIZER_LIST
val upstreamBranchHash = upstreamBranch.hash
val rebaseHead = tryResolveRef(repository, REBASE_HEAD) ?: return DEFAULT_CUSTOMIZER_LIST
val mergeBase = GitHistoryUtils.getMergeBase(
repository.project,
repository.root,
REBASE_HEAD,
upstreamBranchHash.asString()
)?.rev ?: return DEFAULT_CUSTOMIZER_LIST
val leftTitle = html(
"merge.dialog.diff.left.title.rebase.label.text",
rebaseHead.toShortString(),
text(rebasingBranchPresentable).bold()
)
val leftTitleCustomizer = getTitleWithCommitDetailsCustomizer(leftTitle, repository, file, rebaseHead.asString())
val rightTitle =
if (upstreamBranch.branchName != null) {
html("merge.dialog.diff.right.title.rebase.with.branch.label.text", text(upstreamBranch.branchName).bold())
}
else {
html("merge.dialog.diff.right.title.rebase.without.branch.label.text")
}
val rightTitleCustomizer = getTitleWithCommitsRangeDetailsCustomizer(rightTitle, repository, file, Pair(mergeBase, HEAD))
return DiffEditorTitleCustomizerList(leftTitleCustomizer, null, rightTitleCustomizer)
}
private fun loadCherryPickCommitDetails(repository: GitRepository): CherryPickDetails? {
val cherryPickHead = tryResolveRef(repository, CHERRY_PICK_HEAD) ?: return null
val shortDetails = GitLogUtil.collectMetadata(project, GitVcs.getInstance(project), repository.root,
listOf(cherryPickHead.asString()))
val result = shortDetails.singleOrNull() ?: return null
return CherryPickDetails(cherryPickHead.toShortString(), result.author.name, result.subject)
}
private data class CherryPickDetails(@NlsSafe val shortHash: String, @NlsSafe val authorName: String, @NlsSafe val commitMessage: String)
}
internal fun getDescriptionForRebase(@NlsSafe rebasingBranch: String?, @NlsSafe baseBranch: String?, baseHash: Hash?): String =
when {
baseBranch != null -> html(
"merge.dialog.description.rebase.with.onto.branch.label.text",
(rebasingBranch != null).toInt(), text(rebasingBranch ?: "").bold(),
text(baseBranch).bold(),
(baseHash != null).toInt(), baseHash?.toShortString() ?: ""
)
baseHash != null -> html(
"merge.dialog.description.rebase.with.hash.label.text",
(rebasingBranch != null).toInt(), text(rebasingBranch ?: "").bold(),
text(baseHash.toShortString()).bold()
)
else -> html(
"merge.dialog.description.rebase.without.onto.info.label.text",
(rebasingBranch != null).toInt(), text(rebasingBranch ?: "").bold()
)
}
internal fun getDefaultLeftPanelTitleForBranch(@NlsSafe branchName: String): String =
html("merge.dialog.diff.left.title.default.branch.label.text", text(branchName).bold())
internal fun getDefaultRightPanelTitleForBranch(@NlsSafe branchName: String?, baseHash: Hash?): String =
when {
branchName != null -> html(
"merge.dialog.diff.right.title.default.with.onto.branch.label.text",
text(branchName).bold(),
(baseHash != null).toInt(), baseHash?.toShortString() ?: ""
)
baseHash != null -> html(
"merge.dialog.diff.right.title.default.with.hash.label.text",
text(baseHash.toShortString()).bold()
)
else -> GitBundle.message("merge.dialog.diff.right.title.default.without.onto.info.label.text")
}
@NlsSafe
private fun resolveMergeBranchOrCherryPick(repository: GitRepository): String? {
val mergeBranch = resolveMergeBranch(repository)
if (mergeBranch != null) return mergeBranch.presentable
val rebaseOntoBranch = resolveRebaseOntoBranch(repository)
if (rebaseOntoBranch != null) return rebaseOntoBranch.presentable
val cherryHead = tryResolveRef(repository, CHERRY_PICK_HEAD)
if (cherryHead != null) return "cherry-pick"
return null
}
private fun resolveMergeBranch(repository: GitRepository): RefInfo? {
val mergeHead = tryResolveRef(repository, MERGE_HEAD) ?: return null
return resolveBranchName(repository, mergeHead)
}
private fun resolveRebaseOntoBranch(repository: GitRepository): RefInfo? {
val ontoHash = GitRebaseUtils.getOntoHash(repository.project, repository.root) ?: return null
val repo = GitRepositoryManager.getInstance(repository.project).getRepositoryForRoot(repository.root) ?: return null
return resolveBranchName(repo, ontoHash)
}
private fun resolveBranchName(repository: GitRepository, hash: Hash): RefInfo {
var branches: Collection<GitBranch> = repository.branches.findLocalBranchesByHash(hash)
if (branches.isEmpty()) branches = repository.branches.findRemoteBranchesByHash(hash)
return RefInfo(hash, branches.singleOrNull()?.name)
}
private fun tryResolveRef(repository: GitRepository, @NlsSafe ref: String): Hash? {
try {
val revision = GitRevisionNumber.resolve(repository.project, repository.root, ref)
return HashImpl.build(revision.asString())
}
catch (e: VcsException) {
return null
}
}
@NlsSafe
internal fun getSingleMergeBranchName(roots: Collection<GitRepository>): String? = getMergeBranchNameSet(roots).singleOrNull()
private fun getMergeBranchNameSet(roots: Collection<GitRepository>): Set<@NlsSafe String> = roots.mapNotNull { repo ->
resolveMergeBranchOrCherryPick(repo)
}.toSet()
@NlsSafe
internal fun getSingleCurrentBranchName(roots: Collection<GitRepository>): String? = getCurrentBranchNameSet(roots).singleOrNull()
private fun getCurrentBranchNameSet(roots: Collection<GitRepository>): Set<@NlsSafe String> = roots.asSequence().mapNotNull { repo ->
repo.currentBranchName ?: repo.currentRevision?.let { VcsLogUtil.getShortHash(it) }
}.toSet()
internal fun getTitleWithCommitDetailsCustomizer(
@Nls title: String,
repository: GitRepository,
file: FilePath,
@NlsSafe commit: String
) = DiffEditorTitleCustomizer {
getTitleWithShowDetailsAction(title) {
val dlg = ChangeListViewerDialog(repository.project)
dlg.loadChangesInBackground {
val changeList = GitChangeUtils.getRevisionChanges(
repository.project,
repository.root,
commit,
true,
false,
false
)
ChangeListViewerDialog.ChangelistData(changeList, file)
}
dlg.title = StringUtil.stripHtml(title, false)
dlg.isModal = true
dlg.show()
}
}
internal fun getTitleWithCommitsRangeDetailsCustomizer(
@NlsContexts.Label title: String,
repository: GitRepository,
file: FilePath,
range: Pair<@NlsSafe String, @NlsSafe String>
) = DiffEditorTitleCustomizer {
getTitleWithShowDetailsAction(title) {
val details = mutableListOf<VcsCommitMetadata>()
val filteredCommits = HashSet<VcsCommitMetadata>()
ProgressManager.getInstance().runProcessWithProgressSynchronously(
{
readFullDetails(
repository.project,
repository.root,
Consumer { commit ->
val commitMetadata = VcsCommitMetadataImpl(
commit.id, commit.parents, commit.commitTime, commit.root, commit.subject,
commit.author, commit.fullMessage, commit.committer, commit.authorTime)
if (commit.affectedPaths.contains(file)) {
filteredCommits.add(commitMetadata)
}
details.add(commitMetadata)
},
"${range.first}..${range.second}")
},
GitBundle.message("merge.dialog.customizer.collecting.details.progress"),
true,
repository.project)
val dlg = MergeConflictMultipleCommitInfoDialog(repository.project, repository.root, details, filteredCommits)
dlg.title = StringUtil.stripHtml(title, false)
dlg.show()
}
}
internal fun getTitleWithShowDetailsAction(@Nls title: String, action: () -> Unit): JPanel =
BorderLayoutPanel()
.addToCenter(JBLabel(title).setCopyable(true))
.addToRight(ActionLink(GitBundle.message("merge.dialog.customizer.show.details.link.label")) { action() })
private fun Boolean.toInt() = if (this) 1 else 0
private class MergeConflictMultipleCommitInfoDialog(
private val project: Project,
private val root: VirtualFile,
commits: List<VcsCommitMetadata>,
private val filteredCommits: Set<VcsCommitMetadata>
) : MultipleCommitInfoDialog(project, commits) {
init {
filterCommitsByConflictingFile()
}
@Throws(VcsException::class)
override fun loadChanges(commits: List<VcsCommitMetadata>): List<Change> {
val changes = mutableListOf<Change>()
readFullDetailsForHashes(project, root, commits.map { commit -> commit.id.asString() }, GitCommitRequirements.DEFAULT) { gitCommit ->
changes.addAll(gitCommit.changes)
}
return CommittedChangesTreeBrowser.zipChanges(changes)
}
private fun filterCommitsByConflictingFile() {
setFilter { commit -> filteredCommits.contains(commit) }
}
override fun createSouthAdditionalPanel(): JPanel {
val checkbox = JBCheckBox(GitBundle.message("merge.dialog.customizer.filter.by.conflicted.file.checkbox"), true)
checkbox.addItemListener {
if (checkbox.isSelected) {
filterCommitsByConflictingFile()
}
else {
resetFilter()
}
}
return BorderLayoutPanel().addToCenter(checkbox)
}
}
private data class RefInfo(val hash: Hash, @NlsSafe val branchName: String?) {
@NlsSafe
val presentable: String = branchName ?: hash.toShortString()
} | apache-2.0 | b6904e52496f2258ce5b6a3ff4ee8de6 | 41.569231 | 140 | 0.751943 | 4.654051 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/frame/frameInlineFunCallInsideInlineFun.kt | 4 | 674 | package frameInlineFunCallInsideInlineFun
class A {
inline fun inlineFun(s: (Int) -> Unit) {
val element = 1.0
s(1)
}
val prop = 1
}
class B {
inline fun foo(s: (Int) -> Unit) {
val element = 2
val a = A()
// STEP_INTO: 1
// STEP_OVER: 1
//Breakpoint!
a.inlineFun {
val e = element
}
s(1)
}
}
class C {
fun bar() {
val element = 1f
B().foo {
val e = element
}
}
}
fun main(args: Array<String>) {
C().bar()
}
// PRINT_FRAME
// EXPRESSION: element
// RESULT: 1.0: D
// EXPRESSION: this.prop
// RESULT: 1: I
| apache-2.0 | 752edcbf52882ddb1e2b25c64748f997 | 13.652174 | 44 | 0.465875 | 3.320197 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/bolone/bolone-package-1.kt | 1 | 2428 | package bolone
import alraune.*
import aplight.GelNew
import bolone.rp.OrderFields
import pieces100.*
import vgrechka.*
import java.sql.Timestamp
import kotlin.reflect.KMutableProperty0
import kotlin.reflect.KMutableProperty1
val boConfig get() = alConfig.bolone!!
class BoloneConfig(
val frontTSOutDir: String,
val distDir: String)
abstract class Field {
var error by place<String?>()
}
class TextField : Field() {
var value by place<String>()
companion object {
fun make(value: String, error: String?) = TextField().also {
it.value = value
it.error = error
}
fun noError(value: String) = make(value, null)
}
fun intValue() = value.toInt()
}
class DateTimeValidationRange(minHoursFromNow: Int = 4, calendarMinOffsetHours: Int = 1) {
val min = TimePile.hoursFromRealNow_ms(minHoursFromNow.toLong())
val minToShowInCalendar = TimePile.plusHours_ms(min, calendarMinOffsetHours.toLong())
val max = System.currentTimeMillis() + 365L * 24 * 60 * 60 * 1000
fun toFrontCalendarRange() = BoFrontFuns.JSLongRange(
min = JSLong(minToShowInCalendar),
max = JSLong(max))
}
class BiddingParamsDateValidationRanges {
val workDeadlineShownToWritersDuringBidding = DateTimeValidationRange()
val closeBiddingReminderTime = DateTimeValidationRange()
}
fun orderDeadlineRange() = DateTimeValidationRange()
fun bucketNameForSite(site: AlSite): String {
return bucketNameForSite(BoSite.from(site))
}
fun bucketNameForSite(site: BoSite): String {
return site.name
}
enum class BoSite {
Customer, Writer, Admin;
companion object {
fun from(x: AlSite) = when (x) {
AlSite.BoloneCustomer -> Customer
AlSite.BoloneWriter -> Writer
AlSite.BoloneAdmin -> Admin
else -> wtf(x.name)
}
}
}
fun nextOrderFileID() = dbNextSequenceValue(AlConst.orderFileIdSequence)
@GelNew class ReminderJobParams {
var time by place<Timestamp>()
var jobUUID by place<String>()
var taskUUID by place<String>()
fun deleteJobAndTaskIfExists() {
AlGlobal.jobManager.removeIfExists(jobUUID)
dbDeleteTaskByUuid(taskUUID)
}
fun createJob() {
// TODO:vgrechka .....
// AlGlobal.jobManager.add(jobUuid = order.data.bidding!!.closeBiddingReminderJobUUID, job = CloseBiddingReminderJob(order))
}
}
| apache-2.0 | a9550ffa6342877933e23fb55e2a296b | 23.039604 | 132 | 0.687809 | 4.033223 | false | false | false | false |
Atsky/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/debugger/HaskellDebuggerEditorsProvider.kt | 1 | 1899 | package org.jetbrains.haskell.debugger
import com.intellij.xdebugger.evaluation.XDebuggerEditorsProviderBase
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.openapi.fileTypes.FileType
import org.jetbrains.haskell.fileType.HaskellFileType
import org.jetbrains.haskell.fileType.HaskellFile
import org.jetbrains.haskell.HaskellViewProvider
import com.intellij.psi.impl.PsiManagerImpl
import com.intellij.openapi.vfs.VirtualFileManager
import org.jetbrains.haskell.fileType.HaskellFileViewProviderFactory
import com.intellij.psi.PsiFileFactory
import com.intellij.openapi.fileTypes.PlainTextFileType
import com.intellij.psi.impl.source.PsiExpressionCodeFragmentImpl
import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider
import com.intellij.xdebugger.XSourcePosition
import com.intellij.xdebugger.evaluation.EvaluationMode
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.EditorFactory
import com.intellij.psi.PsiDocumentManager
class HaskellDebuggerEditorsProvider : XDebuggerEditorsProvider() {
override fun createDocument(project: Project,
text: String,
sourcePosition: XSourcePosition?,
mode: EvaluationMode): Document {
if(sourcePosition != null) {
val hsPsiFile = PsiFileFactory.getInstance(project)!!.createFileFromText(sourcePosition.file.name,
HaskellFileType.INSTANCE,
text)
val hsDocument = PsiDocumentManager.getInstance(project)!!.getDocument(hsPsiFile)
if(hsDocument != null) {
return hsDocument
}
}
return EditorFactory.getInstance()!!.createDocument(text)
}
override fun getFileType(): FileType = HaskellFileType.INSTANCE
} | apache-2.0 | 06e75ddc5ff63bd3ef07f0f5ee0b8bc0 | 43.186047 | 110 | 0.750395 | 5.260388 | false | false | false | false |
nimakro/tornadofx | src/test/kotlin/tornadofx/testapps/ListMenuTest.kt | 3 | 2520 | import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon.*
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIconView
import javafx.geometry.Orientation
import javafx.geometry.Pos
import javafx.geometry.Side
import javafx.scene.paint.Color
import tornadofx.*
class ListMenuTestApp : App(ListMenuTest::class)
class ListMenuTest : View("ListMenu Test") {
val listmenu = listmenu(theme = "blue") {
addMenuItems()
activeItem = items.first()
maxHeight = Double.MAX_VALUE
}
override val root = borderpane {
setPrefSize(650.0, 500.0)
top {
vbox(10) {
label(title).style { fontSize = 3.em }
hbox(10) {
alignment = Pos.CENTER
label("Orientation")
combobox(listmenu.orientationProperty, Orientation.values().toList())
label("Icon Position")
combobox(listmenu.iconPositionProperty, values = Side.values().toList())
label("Theme")
combobox(listmenu.themeProperty, values = listOf("none", "blue"))
checkbox("Icons Only") {
selectedProperty().onChange {
with(listmenu) {
items.clear()
if (it) {
iconOnlyMenuItems()
} else {
addMenuItems()
}
}
}
}
}
label(stringBinding(listmenu.activeItemProperty) { "Currently selected: ${value?.text}" }) {
style { textFill = Color.RED }
}
style {
alignment = Pos.CENTER
}
}
}
center = listmenu
style {
backgroundColor += Color.WHITE
}
paddingAll = 20
}
private fun ListMenu.iconOnlyMenuItems() {
item(graphic = icon(USER))
item(graphic = icon(SUITCASE))
item(graphic = icon(COG))
}
private fun ListMenu.addMenuItems() {
item("Contacts", icon(USER))
item("Projects", icon(SUITCASE))
item("Settings", icon(COG))
}
private fun icon(icon: FontAwesomeIcon) = FontAwesomeIconView(icon).apply { glyphSize = 20 }
} | apache-2.0 | 1fb6f4aaafe88e606b6cb670fe61c3de | 33.534247 | 108 | 0.500794 | 5.121951 | false | true | false | false |
androidx/androidx | compose/ui/ui-unit/src/commonMain/kotlin/androidx/compose/ui/unit/IntSize.kt | 3 | 2976 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("NOTHING_TO_INLINE")
package androidx.compose.ui.unit
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.util.packInts
import androidx.compose.ui.util.unpackInt1
import androidx.compose.ui.util.unpackInt2
/**
* Constructs an [IntSize] from width and height [Int] values.
*/
@Stable
fun IntSize(width: Int, height: Int): IntSize = IntSize(packInts(width, height))
/**
* A two-dimensional size class used for measuring in [Int] pixels.
*/
@Immutable
@kotlin.jvm.JvmInline
value class IntSize internal constructor(@PublishedApi internal val packedValue: Long) {
/**
* The horizontal aspect of the size in [Int] pixels.
*/
@Stable
val width: Int
get() = unpackInt1(packedValue)
/**
* The vertical aspect of the size in [Int] pixels.
*/
@Stable
val height: Int
get() = unpackInt2(packedValue)
@Stable
inline operator fun component1(): Int = width
@Stable
inline operator fun component2(): Int = height
/**
* Returns an IntSize scaled by multiplying [width] and [height] by [other]
*/
@Stable
operator fun times(other: Int): IntSize =
IntSize(width = width * other, height = height * other)
/**
* Returns an IntSize scaled by dividing [width] and [height] by [other]
*/
@Stable
operator fun div(other: Int): IntSize =
IntSize(width = width / other, height = height / other)
@Stable
override fun toString(): String = "$width x $height"
companion object {
/**
* IntSize with a zero (0) width and height.
*/
val Zero = IntSize(0L)
}
}
/**
* Returns an [IntSize] with [size]'s [IntSize.width] and [IntSize.height]
* multiplied by [this].
*/
@Stable
operator fun Int.times(size: IntSize) = size * this
/**
* Convert a [IntSize] to a [IntRect].
*/
@Stable
fun IntSize.toIntRect(): IntRect {
return IntRect(IntOffset.Zero, this)
}
/**
* Returns the [IntOffset] of the center of the rect from the point of [0, 0]
* with this [IntSize].
*/
@Stable
val IntSize.center: IntOffset
get() = IntOffset(width / 2, height / 2)
// temporary while PxSize is transitioned to Size
@Stable
fun IntSize.toSize() = Size(width.toFloat(), height.toFloat()) | apache-2.0 | d27a1047ec62d1cc0e6f9ea23fad4cf5 | 25.81982 | 88 | 0.676411 | 3.890196 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.