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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
iMeePwni/LCExercise | src/test/kotlin/HammingDistanceTest.kt | 1 | 801 | import org.junit.Assert
import org.junit.Test
/*
* Created by guofeng on 2017/6/20.
*/
class HammingDistanceTest {
@Test
fun hammingDistanceTest() {
val x = 1
val y = 4
val solution = HammingDistance().solution(x, y)
val expected = 2
Assert.assertEquals(expected, solution)
}
@Test
fun hammingDistanceXTest() {
val x = -1
val y = 4
val solution = HammingDistance().solution(x, y)
val expected = null
Assert.assertEquals(expected, solution)
}
@Test
fun hammingDistanceYTest() {
val x = 1
val y = Math.pow(2.0, 31.0).toInt()
val solution = HammingDistance().solution(x, y)
val expected = null
Assert.assertEquals(expected, solution)
}
}
| apache-2.0 | 4487cd8642652fdd988e8f078ed4f3b5 | 18.536585 | 55 | 0.580524 | 3.945813 | false | true | false | false |
nryotaro/edgar-crawler | src/main/kotlin/org/nryotaro/edgar/retriever/FiledDocumentRetriever.kt | 1 | 2658 | package org.nryotaro.edgar.retriever
import org.nryotaro.edgar.client.EdgarClient
import org.nryotaro.edgar.client.LastHttpContent
import org.nryotaro.edgar.client.PartialHttpContent
import org.nryotaro.edgar.client.Status
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Repository
import reactor.core.publisher.Mono
import java.io.File
import java.nio.ByteBuffer
import java.nio.channels.FileChannel
import java.nio.file.StandardOpenOption
import java.time.Duration
@Repository
class FiledDocumentRetriever(
@Value("\${edgar.traffic.limit}") private val trafficLimit: Long,
private val client: EdgarClient) {
val log = LoggerFactory.getLogger(this::class.java)
/**
* TODO handle the case dest exists
*/
fun retrieve(documentUrl: String, dest: File): Mono<Boolean> {
dest.parentFile.mkdirs()
var destination = FileChannel.open(dest.toPath(), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)
return Mono.just(documentUrl).delayElement(Duration.ofMillis(trafficLimit))
.flatMapMany{ client.getResponse(it) }.reduce(true, {success ,b ->
when(success) {
false -> false
true -> when(b) {
is Status -> if(b.status == 200)
true
else {
log.error("status: ${b.status}, url: $documentUrl")
false
}
is PartialHttpContent -> {
val c: ByteBuffer = ByteBuffer.allocate(b.content.size)
c.put(b.content)
c.flip()
destination.write(c)
true
}
is LastHttpContent -> {
val c: ByteBuffer = ByteBuffer.allocate(b.content.size)
c.put(b.content)
c.flip()
destination.write(c)
destination.close()
true
}
}}}).doOnError {
log.debug("$it occurred.")
dest.delete()
destination = FileChannel.open(dest.toPath(), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)
}.retry(3).doOnNext{log.debug("downloaded $documentUrl")}.onErrorResume {
destination.close()
dest.delete()
log.error("failed to download: $documentUrl.${System.lineSeparator()}{}", it)
Mono.just(false)
}
}
}
| mit | 6519afced6a5846f2e580bd4b39c0907 | 38.671642 | 114 | 0.568849 | 4.877064 | false | false | false | false |
tipsy/javalin | javalin/src/main/java/io/javalin/plugin/rendering/template/JavalinThymeleaf.kt | 1 | 1422 | /*
* Javalin - https://javalin.io
* Copyright 2017 David Åse
* Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE
*/
package io.javalin.plugin.rendering.template
import io.javalin.core.util.OptionalDependency
import io.javalin.core.util.Util
import io.javalin.http.Context
import io.javalin.plugin.rendering.FileRenderer
import org.thymeleaf.TemplateEngine
import org.thymeleaf.context.WebContext
import org.thymeleaf.templatemode.TemplateMode
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver
object JavalinThymeleaf : FileRenderer {
private var templateEngine: TemplateEngine? = null
private val defaultTemplateEngine: TemplateEngine by lazy { defaultThymeLeafEngine() }
@JvmStatic
fun configure(staticTemplateEngine: TemplateEngine) {
templateEngine = staticTemplateEngine
}
override fun render(filePath: String, model: Map<String, Any?>, ctx: Context): String {
Util.ensureDependencyPresent(OptionalDependency.THYMELEAF)
val context = WebContext(ctx.req, ctx.res, ctx.req.servletContext)
context.setVariables(model)
return (templateEngine ?: defaultTemplateEngine).process(filePath, context)
}
private fun defaultThymeLeafEngine() = TemplateEngine().apply {
setTemplateResolver(ClassLoaderTemplateResolver().apply {
templateMode = TemplateMode.HTML
})
}
}
| apache-2.0 | dfce19e83cc2da7238ffddaffd16f39b | 33.658537 | 91 | 0.757213 | 4.413043 | false | false | false | false |
Eyepea/FrameworkBenchmarks | frameworks/Kotlin/hexagon/src/main/kotlin/co/there4/hexagon/Benchmark.kt | 2 | 3039 | package co.there4.hexagon
import co.there4.hexagon.serialization.convertToMap
import co.there4.hexagon.serialization.serialize
import co.there4.hexagon.server.Call
import co.there4.hexagon.server.Router
import co.there4.hexagon.server.Server
import co.there4.hexagon.server.jetty.JettyServletEngine
import co.there4.hexagon.server.router
import co.there4.hexagon.server.servlet.ServletServer
import co.there4.hexagon.settings.SettingsManager.settings
import co.there4.hexagon.templates.pebble.PebbleEngine
import java.lang.System.getProperty
import java.lang.System.getenv
import java.util.*
import java.util.concurrent.ThreadLocalRandom
import javax.servlet.annotation.WebListener
import java.net.InetAddress.getByName as address
// DATA CLASSES
internal data class Message(val message: String)
internal data class Fortune(val _id: Int, val message: String)
internal data class World(val _id: Int, val id: Int, val randomNumber: Int)
// CONSTANTS
private const val TEXT_MESSAGE: String = "Hello, World!"
private const val CONTENT_TYPE_JSON = "application/json"
private const val QUERIES_PARAM = "queries"
// UTILITIES
internal fun randomWorld() = ThreadLocalRandom.current().nextInt(WORLD_ROWS) + 1
private fun Call.returnWorlds(worldsList: List<World>) {
val worlds = worldsList.map { it.convertToMap() - "_id" }
val result = if (worlds.size == 1) worlds.first().serialize() else worlds.serialize()
ok(result, CONTENT_TYPE_JSON)
}
private fun Call.getWorldsCount() = (request[QUERIES_PARAM]?.toIntOrNull() ?: 1).let {
when {
it < 1 -> 1
it > 500 -> 500
else -> it
}
}
// HANDLERS
private fun Call.listFortunes(store: Store) {
val fortunes = store.findAllFortunes() + Fortune(0, "Additional fortune added at request time.")
val locale = Locale.getDefault()
response.contentType = "text/html; charset=utf-8"
template(PebbleEngine, "fortunes.html", locale, "fortunes" to fortunes.sortedBy { it.message })
}
private fun Call.getWorlds(store: Store) {
returnWorlds(store.findWorlds(getWorldsCount()))
}
private fun Call.updateWorlds(store: Store) {
returnWorlds(store.replaceWorlds(getWorldsCount()))
}
// CONTROLLER
private fun router(): Router = router {
val store = createStore(getProperty("DBSTORE") ?: getenv("DBSTORE") ?: "mongodb")
before {
response.addHeader("Server", "Servlet/3.1")
response.addHeader("Transfer-Encoding", "chunked")
response.addHeader("Date", httpDate())
}
get("/plaintext") { ok(TEXT_MESSAGE, "text/plain") }
get("/json") { ok(Message(TEXT_MESSAGE).serialize(), CONTENT_TYPE_JSON) }
get("/fortunes") { listFortunes(store) }
get("/db") { getWorlds(store) }
get("/query") { getWorlds(store) }
get("/update") { updateWorlds(store) }
}
@WebListener class Web : ServletServer () {
override fun createRouter() = router()
}
internal var server: Server? = null
fun main(vararg args: String) {
server = Server(JettyServletEngine(), settings, router()).apply { run() }
}
| bsd-3-clause | 34654183e9dd6222a1db375064a704f7 | 32.395604 | 100 | 0.72129 | 3.733415 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/util/SoundFx.kt | 1 | 1919 | package de.westnordost.streetcomplete.util
import android.content.Context
import android.media.AudioAttributes
import android.media.SoundPool
import android.provider.Settings
import android.util.SparseIntArray
import androidx.annotation.RawRes
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.coroutines.Continuation
import kotlin.coroutines.resume
/** Simple wrapper to enable just playing a sound effect from raw resources */
@Singleton class SoundFx @Inject constructor(private val context: Context) {
private val soundPool = SoundPool.Builder()
.setMaxStreams(10)
.setAudioAttributes(AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build())
.build()
private val soundIds: SparseIntArray = SparseIntArray()
// map of sampleId -> continuation of sampleId
private val loadCompleteContinuations = mutableMapOf<Int, Continuation<Int>>()
init {
soundPool.setOnLoadCompleteListener { _, soundId, _ ->
loadCompleteContinuations[soundId]?.resume(soundId)
}
}
// will not return until the loading of the sound is complete
private suspend fun prepare(@RawRes resId: Int): Int = suspendCancellableCoroutine { cont ->
val soundId = soundPool.load(context, resId, 1)
loadCompleteContinuations[soundId] = cont
}
suspend fun play(@RawRes resId: Int) = withContext(Dispatchers.IO) {
val isTouchSoundsEnabled = Settings.System.getInt(context.contentResolver, Settings.System.SOUND_EFFECTS_ENABLED, 1) != 0
if (isTouchSoundsEnabled) {
if (soundIds[resId] == 0) soundIds.put(resId, prepare(resId))
soundPool.play(soundIds[resId], 1f, 1f, 1, 0, 1f)
}
}
}
| gpl-3.0 | 8bc7a36fc3726de3241f01f4c9b76ff0 | 37.38 | 129 | 0.728504 | 4.714988 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/LoginActivity.kt | 1 | 8878 | package com.boardgamegeek.ui
import android.accounts.Account
import android.accounts.AccountAuthenticatorResponse
import android.accounts.AccountManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.inputmethod.EditorInfo
import androidx.activity.viewModels
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.os.bundleOf
import com.boardgamegeek.R
import com.boardgamegeek.auth.Authenticator
import com.boardgamegeek.auth.BggCookieJar
import com.boardgamegeek.databinding.ActivityLoginBinding
import com.boardgamegeek.extensions.*
import com.boardgamegeek.ui.viewmodel.LoginViewModel
import timber.log.Timber
/**
* Activity which displays a login screen to the user, offering registration as well.
*/
class LoginActivity : AppCompatActivity() {
private lateinit var binding: ActivityLoginBinding
private val viewModel by viewModels<LoginViewModel>()
private var accountAuthenticatorResponse: AccountAuthenticatorResponse? = null
private var username: String? = null
private var password: String? = null
private lateinit var accountManager: AccountManager
private var isRequestingNewAccount = false
private var isAuthenticating = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
accountAuthenticatorResponse = intent.getParcelableExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE)
accountAuthenticatorResponse?.onRequestContinued()
binding = ActivityLoginBinding.inflate(layoutInflater)
setContentView(binding.root)
accountManager = AccountManager.get(this)
username = intent.getStringExtra(KEY_USERNAME)
isRequestingNewAccount = username == null
binding.usernameView.setText(username)
binding.usernameView.isEnabled = isRequestingNewAccount
if (isRequestingNewAccount) {
binding.usernameView.requestFocus()
} else {
binding.passwordView.requestFocus()
}
binding.passwordView.setOnEditorActionListener { _, actionId, _ ->
if (actionId == R.integer.login_action_id || actionId == EditorInfo.IME_NULL) {
attemptLogin()
return@setOnEditorActionListener true
}
false
}
binding.signInButton.setOnClickListener {
attemptLogin()
}
viewModel.isAuthenticating.observe(this) {
isAuthenticating = it ?: false
showProgress(isAuthenticating)
}
viewModel.authenticationResult.observe(this) {
if (it == null) {
binding.passwordContainer.error = getString(R.string.error_incorrect_password)
binding.passwordView.requestFocus()
} else {
createAccount(it)
}
}
}
override fun onBackPressed() {
if (isAuthenticating) {
viewModel.cancel()
} else {
super.onBackPressed()
}
}
/**
* Attempts to sign in or register the account specified by the login form. If there are form errors (invalid email,
* missing fields, etc.), the errors are presented and no actual login attempt is made.
*/
private fun attemptLogin() {
if (isAuthenticating) {
return
}
// Reset errors.
binding.usernameContainer.error = null
binding.passwordContainer.error = null
// Store values at the time of the login attempt.
if (isRequestingNewAccount) {
username = binding.usernameView.text.toString().trim()
}
password = binding.passwordView.text.toString()
val focusView = when {
username.isNullOrBlank() -> {
binding.usernameContainer.error = getString(R.string.error_field_required)
binding.usernameView
}
password.isNullOrEmpty() -> {
binding.passwordContainer.error = getString(R.string.error_field_required)
binding.passwordView
}
else -> null
}
if (focusView != null) {
// There was an error; don't attempt login and focus the first form field with an error.
focusView.requestFocus()
} else {
// Show a progress spinner, and kick off a background task to perform the user login attempt.
binding.loginStatusMessageView.setText(R.string.login_progress_signing_in)
showProgress(true)
viewModel.login(username, password)
}
}
/**
* Shows the progress UI and hides the login form.
*/
private fun showProgress(show: Boolean) {
binding.loginStatusView.fade(show)
binding.loginFormView.fade(!show)
}
private fun createAccount(bggCookieJar: BggCookieJar) {
Timber.i("Creating account")
val account = Account(username, Authenticator.ACCOUNT_TYPE)
try {
accountManager.setAuthToken(account, Authenticator.AUTH_TOKEN_TYPE, bggCookieJar.authToken)
} catch (e: SecurityException) {
AlertDialog.Builder(this)
.setTitle(R.string.title_error)
.setMessage(R.string.error_account_set_auth_token_security_exception)
.show()
return
}
val userData = bundleOf(Authenticator.KEY_AUTH_TOKEN_EXPIRY to bggCookieJar.authTokenExpiry.toString())
if (isRequestingNewAccount) {
try {
var success = accountManager.addAccountExplicitly(account, password, userData)
if (!success) {
Authenticator.removeAccounts(applicationContext)
success = accountManager.addAccountExplicitly(account, password, userData)
}
if (!success) {
val accounts = accountManager.getAccountsByType(Authenticator.ACCOUNT_TYPE)
when {
accounts.isEmpty() -> {
Timber.v("no account!")
binding.passwordContainer.error = getString(R.string.error_account_list_zero)
return
}
accounts.size != 1 -> {
Timber.w("multiple accounts!")
binding.passwordContainer.error = getString(R.string.error_account_list_multiple, Authenticator.ACCOUNT_TYPE)
return
}
else -> {
val existingAccount = accounts[0]
when {
existingAccount == null -> {
binding.passwordContainer.error = getString(R.string.error_account_list_zero)
return
}
existingAccount.name != account.name -> {
binding.passwordContainer.error =
getString(R.string.error_account_name_mismatch, existingAccount.name, account.name)
return
}
else -> {
accountManager.setPassword(account, password)
}
}
}
}
}
} catch (e: Exception) {
binding.passwordContainer.error = e.localizedMessage
return
}
} else {
accountManager.setPassword(account, password)
}
val extras = bundleOf(
AccountManager.KEY_ACCOUNT_NAME to username,
AccountManager.KEY_ACCOUNT_TYPE to Authenticator.ACCOUNT_TYPE
)
setResult(RESULT_OK, Intent().putExtras(extras))
accountAuthenticatorResponse?.let {
// send the result bundle back if set, otherwise send an error.
it.onResult(extras)
accountAuthenticatorResponse = null
}
preferences()[AccountPreferences.KEY_USERNAME] = username
finish()
}
companion object {
private const val KEY_USERNAME = "USERNAME"
fun createIntentBundle(context: Context, response: AccountAuthenticatorResponse?, accountName: String?): Bundle {
val intent = context.intentFor<LoginActivity>(
KEY_USERNAME to accountName,
AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE to response
)
return bundleOf(AccountManager.KEY_INTENT to intent)
}
}
}
| gpl-3.0 | 220a4c088fd8fba5381fffaa0d914116 | 38.633929 | 137 | 0.592701 | 5.735142 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/persistence/entity/CouponEntity.kt | 2 | 2373 | package org.wordpress.android.fluxc.persistence.entity
import androidx.room.Embedded
import androidx.room.Entity
import androidx.room.Index
import androidx.room.Relation
import androidx.room.TypeConverters
import org.wordpress.android.fluxc.persistence.converters.DiscountTypeConverter
import java.math.BigDecimal
@Entity(
tableName = "Coupons",
primaryKeys = ["id", "siteId"],
indices = [Index("id", "siteId")]
)
data class CouponEntity(
val id: Long,
val siteId: Long,
val code: String? = null,
val amount: BigDecimal? = null,
val dateCreated: String? = null,
val dateCreatedGmt: String? = null,
val dateModified: String? = null,
val dateModifiedGmt: String? = null,
@field:TypeConverters(DiscountTypeConverter::class) val discountType: DiscountType? = null,
val description: String? = null,
val dateExpires: String? = null,
val dateExpiresGmt: String? = null,
val usageCount: Int? = null,
val isForIndividualUse: Boolean? = null,
val usageLimit: Int? = null,
val usageLimitPerUser: Int? = null,
val limitUsageToXItems: Int? = null,
val isShippingFree: Boolean? = null,
val areSaleItemsExcluded: Boolean? = null,
val minimumAmount: BigDecimal? = null,
val maximumAmount: BigDecimal? = null,
val includedProductIds: List<Long>? = null,
val excludedProductIds: List<Long>? = null,
val includedCategoryIds: List<Long>? = null,
val excludedCategoryIds: List<Long>? = null
) {
sealed class DiscountType(open val value: String) {
object Percent : DiscountType("percent")
object FixedCart : DiscountType("fixed_cart")
object FixedProduct : DiscountType("fixed_product")
data class Custom(override val value: String) : DiscountType(value)
companion object {
fun fromString(value: String): DiscountType {
return when (value) {
Percent.value -> Percent
FixedProduct.value -> FixedProduct
FixedCart.value -> FixedCart
else -> Custom(value)
}
}
}
override fun toString() = value
}
}
data class CouponWithEmails(
@Embedded val coupon: CouponEntity,
@Relation(parentColumn = "id", entityColumn = "couponId")
val restrictedEmails: List<CouponEmailEntity>
)
| gpl-2.0 | 7bc310d08fcbe4909f2654b877012abf | 33.897059 | 95 | 0.663295 | 4.346154 | false | false | false | false |
faceofcat/Tesla-Powered-Thingies | src/main/kotlin/net/ndrei/teslapoweredthingies/machines/portabletank/SimpleTankBlock.kt | 1 | 13901 | package net.ndrei.teslapoweredthingies.machines.portabletank
import net.minecraft.block.state.BlockStateContainer
import net.minecraft.block.state.IBlockState
import net.minecraft.client.Minecraft
import net.minecraft.client.renderer.BufferBuilder
import net.minecraft.client.renderer.GlStateManager
import net.minecraft.client.renderer.Tessellator
import net.minecraft.client.renderer.block.model.BakedQuad
import net.minecraft.client.renderer.texture.TextureAtlasSprite
import net.minecraft.client.renderer.texture.TextureMap
import net.minecraft.client.renderer.vertex.DefaultVertexFormats
import net.minecraft.item.Item
import net.minecraft.item.ItemStack
import net.minecraft.tileentity.TileEntity
import net.minecraft.util.BlockRenderLayer
import net.minecraft.util.EnumFacing
import net.minecraft.util.ResourceLocation
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Vec3d
import net.minecraft.world.IBlockAccess
import net.minecraftforge.common.model.TRSRTransformation
import net.minecraftforge.common.property.ExtendedBlockState
import net.minecraftforge.common.property.IExtendedBlockState
import net.minecraftforge.common.util.Constants
import net.minecraftforge.fluids.Fluid
import net.minecraftforge.fluids.FluidStack
import net.minecraftforge.fml.relauncher.Side
import net.minecraftforge.fml.relauncher.SideOnly
import net.minecraftforge.registries.IForgeRegistry
import net.ndrei.teslacorelib.annotations.AutoRegisterBlock
import net.ndrei.teslacorelib.render.selfrendering.*
import net.ndrei.teslapoweredthingies.client.ThingiesTexture
import net.ndrei.teslapoweredthingies.machines.BaseThingyBlock
import net.ndrei.teslapoweredthingies.machines.portablemultitank.UnlistedFluidProperty
import org.lwjgl.opengl.GL11
/**
* Created by CF on 2017-07-16.
*/
@AutoRegisterBlock
@SelfRenderingBlock
object SimpleTankBlock
: BaseThingyBlock<SimpleTankEntity>("simple_tank", SimpleTankEntity::class.java), ISelfRenderingBlock {
lateinit var FLUID_PROP: UnlistedFluidProperty
override fun registerItem(registry: IForgeRegistry<Item>) {
registry.register(SimpleTankItem)
}
//#region Block Overrides
override fun createBlockState(): BlockStateContainer {
this.FLUID_PROP = UnlistedFluidProperty("fluid")
return ExtendedBlockState(this, arrayOf(FACING), arrayOf(this.FLUID_PROP))
}
override fun canRenderInLayer(state: IBlockState?, layer: BlockRenderLayer?): Boolean {
return /*layer == BlockRenderLayer.TRANSLUCENT ||*/ layer == BlockRenderLayer.SOLID || layer == BlockRenderLayer.CUTOUT
}
override fun isOpaqueCube(state: IBlockState?) = false
override fun isFullCube(state: IBlockState?) = false
override fun isTranslucent(state: IBlockState?) = true
override fun doesSideBlockRendering(state: IBlockState?, world: IBlockAccess?, pos: BlockPos?, face: EnumFacing?) = false
override fun getExtendedState(state: IBlockState, world: IBlockAccess, pos: BlockPos): IBlockState {
if (state is IExtendedBlockState) {
val te = world.getTileEntity(pos)
if (te is SimpleTankEntity) {
val f = te.getFluid()
return if (f != null) state.withProperty(FLUID_PROP, f) else state
}
}
return super.getExtendedState(state, world, pos)
}
//#endregion
@SideOnly(Side.CLIENT)
override fun getTextures(): List<ResourceLocation> {
return listOf(ThingiesTexture.SIMPLE_TANK_SIDE.resource)
}
@SideOnly(Side.CLIENT)
override fun getBakeries(layer: BlockRenderLayer?, state: IBlockState?, stack: ItemStack?, side: EnumFacing?, rand: Long, transform: TRSRTransformation): List<IBakery> {
val bakeries = mutableListOf<IBakery>()
// TeslaThingiesMod.logger.info("Building bakeries for '${layer?.toString() ?: "NO LAYER"}'.")
if ((layer == BlockRenderLayer.SOLID) || (layer == null)) {
bakeries.add(listOf(
RawCube(Vec3d(0.0, 0.0, 0.0), Vec3d(32.0, 2.0, 32.0), ThingiesTexture.SIMPLE_TANK_SIDE.sprite)
.addFace(EnumFacing.UP).uv(8.0f, 8.0f, 16.0f, 16.0f)
.addFace(EnumFacing.DOWN).uv(8.0f, 8.0f, 16.0f, 16.0f)
.addFace(EnumFacing.WEST).uv(0.0f, 0.0f, 8.0f, 0.5f)
.addFace(EnumFacing.NORTH).uv(0.0f, 0.0f, 8.0f, 0.5f)
.addFace(EnumFacing.EAST).uv(0.0f, 0.0f, 8.0f, 0.5f)
.addFace(EnumFacing.SOUTH).uv(0.0f, 0.0f, 8.0f, 0.5f),
RawCube(Vec3d(0.0, 30.0, 0.0), Vec3d(32.0, 32.0, 32.0), ThingiesTexture.SIMPLE_TANK_SIDE.sprite)
.addFace(EnumFacing.WEST).uv(0.0f, 0.0f, 8.0f, 0.5f)
.addFace(EnumFacing.NORTH).uv(0.0f, 0.0f, 8.0f, 0.5f)
.addFace(EnumFacing.EAST).uv(0.0f, 0.0f, 8.0f, 0.5f)
.addFace(EnumFacing.SOUTH).uv(0.0f, 0.0f, 8.0f, 0.5f)
.addFace(EnumFacing.UP).uv(8.0f, 0.0f, 16.0f, 8.0f)
.addFace(EnumFacing.DOWN).uv(8.0f, 8.0f, 16.0f, 16.0f)
).combine().static())
}
if ((layer == BlockRenderLayer.CUTOUT) || (layer == null)) {
bakeries.add(listOf(
RawCube(Vec3d(1.0, 2.0, 1.0), Vec3d(31.0, 30.0, 31.0), ThingiesTexture.SIMPLE_TANK_SIDE.sprite)
.dualSide()
.addFace(EnumFacing.SOUTH).uv(0.5f, 8.5f, 7.5f, 15f)
.addFace(EnumFacing.EAST).uv(0.5f, 8.5f, 7.5f, 15f)
.addFace(EnumFacing.NORTH).uv(0.5f, 8.5f, 7.5f, 15f)
.addFace(EnumFacing.WEST).uv(0.5f, 8.5f, 7.5f, 15f)
).combine().static())
}
if (/*(layer == BlockRenderLayer.TRANSLUCENT) || */(layer == null)) {
bakeries.add(
CachedBakery({ _state, _stack, _side, _vertexFormat, _transform ->
val info = [email protected](_state, _stack)
if (info != null) {
val resource = info.fluid.still
val sprite = (if (resource != null) Minecraft.getMinecraft().textureMapBlocks.getTextureExtry(resource.toString()) else null)
?: Minecraft.getMinecraft().textureMapBlocks.missingSprite
mutableListOf<BakedQuad>().also { list ->
RawCube(Vec3d(1.1, 2.1, 1.1), Vec3d(30.9, 2.0 + 28.0 * (info.amount.toDouble() / 64.0) - 0.1, 30.9), sprite)
.autoUV()
.addFace(EnumFacing.EAST).color(info.fluid.color)
.addFace(EnumFacing.SOUTH).color(info.fluid.color)
.addFace(EnumFacing.WEST).color(info.fluid.color)
.addFace(EnumFacing.NORTH).color(info.fluid.color)
.addFace(EnumFacing.UP).color(info.fluid.color)
.bake(list, _vertexFormat, _transform)
}
} else {
mutableListOf()
}
}).also { cache ->
cache.keyGetter = { _state, _stack, _ ->
val info = this.getFluidStackInfo(_state, _stack)
if (info == null) {
"no info"
}
else {
"${info.fluid.name}::${info.amount}"
}
}
}
)
}
return bakeries.toList()
}
private fun getFluidStackInfo(state: IBlockState?, stack: ItemStack?): FluidStackInfo? {
val extended = (state as? IExtendedBlockState)
if (extended != null) {
val fluid = extended.getValue(FLUID_PROP)
if ((fluid != null) && (fluid.fluid != null) && (fluid.amount > 0)) {
return FluidStackInfo(fluid.fluid, Math.round(fluid.amount.toFloat() / 93.75f))
}
}
if ((stack != null) && !stack.isEmpty && stack.hasTagCompound()) {
val nbt = stack.tagCompound
if ((nbt != null) && nbt.hasKey("tileentity", Constants.NBT.TAG_COMPOUND)) {
val teNBT = nbt.getCompoundTag("tileentity")
if (teNBT.hasKey("fluids", Constants.NBT.TAG_COMPOUND)) {
val flNBT = teNBT.getCompoundTag("fluids")
// fluids -> tanks -> (FluidName, Amount)
if (flNBT.hasKey("tanks", Constants.NBT.TAG_LIST)) {
val tNBT = flNBT.getTagList("tanks", Constants.NBT.TAG_COMPOUND)
if (tNBT.tagCount() > 0) {
val tank = tNBT.getCompoundTagAt(0)
val fluid = FluidStack.loadFluidStackFromNBT(tank)
if (fluid != null) {
return FluidStackInfo(fluid.fluid, Math.round(fluid.amount.toFloat() / 375f))
}
}
}
}
}
}
return null
}
class FluidStackInfo(val fluid: Fluid, val amount: Int)
@SideOnly(Side.CLIENT)
override fun renderTESR(proxy: TESRProxy, te: TileEntity, x: Double, y: Double, z: Double, partialTicks: Float, destroyStage: Int, alpha: Float) {
GlStateManager.enableBlend()
GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA)
proxy.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE)
val fluid = (te as? SimpleTankEntity)?.getFluid()
if ((fluid != null) && (fluid.fluid != null) && (fluid.amount > 0)) {
val amount = Math.round(fluid.amount.toFloat() / 375f) / 64.0f
this.drawFluid(fluid.fluid, amount)
}
GlStateManager.disableBlend()
GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f)
}
@SideOnly(Side.CLIENT)
private fun drawFluid(fluid: Fluid?, fluidPercent: Float) {
GlStateManager.pushMatrix()
GlStateManager.translate(1.1, 2.0, 1.1)
if ((fluidPercent > 0.0f) && (fluid != null)) {
if (fluidPercent > 0) {
val still = fluid.still
if (still != null) {
val height = 28 * fluidPercent
val color = fluid.color
GlStateManager.color((color shr 16 and 0xFF) / 255.0f, (color shr 8 and 0xFF) / 255.0f, (color and 0xFF) / 255.0f, (color ushr 24 and 0xFF) / 255.0f)
val stillSprite = Minecraft.getMinecraft().textureMapBlocks.getTextureExtry(still.toString())
?: Minecraft.getMinecraft().textureMapBlocks.missingSprite
if (stillSprite != null) {
this.drawSprite(
Vec3d(0.0, 28.0 - height, 0.0),
Vec3d(29.8, 28.0, 0.0),
stillSprite, false, true)
this.drawSprite(
Vec3d(0.0, 28.0 - height, 0.0),
Vec3d(0.0, 28.0, 29.8),
stillSprite, true, false)
this.drawSprite(
Vec3d(0.0, 28.0 - height, 29.8),
Vec3d(29.8, 28.0, 29.8),
stillSprite, true, false)
this.drawSprite(
Vec3d(29.8, 28.0 - height, 0.0),
Vec3d(29.8, 28.0, 29.8),
stillSprite, false, true)
this.drawSprite(
Vec3d(0.0, 28.0 - height, 29.8),
Vec3d(29.8, 28.0 - height, 0.0),
stillSprite)
}
}
}
}
GlStateManager.popMatrix()
}
@SideOnly(Side.CLIENT)
private fun drawSprite(start: Vec3d, end: Vec3d, sprite: TextureAtlasSprite, draw1: Boolean = true, draw2: Boolean = true) {
val buffer = Tessellator.getInstance().buffer
buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX)
val width = Math.abs(if (end.x == start.x) end.z - start.z else end.x - start.x)
val height = Math.abs(if (end.y == start.y) end.z - start.z else end.y - start.y)
val texW = sprite.maxU - sprite.minU
val texH = sprite.maxV - sprite.minV
val finalW = texW * width / 32.0
val finalH = texH * height / 32.0
this.drawTexture(buffer, start, end, sprite.minU.toDouble(), sprite.minV.toDouble(), sprite.minU + finalW, sprite.minV + finalH, draw1, draw2)
Tessellator.getInstance().draw()
}
@SideOnly(Side.CLIENT)
private fun drawTexture(buffer: BufferBuilder, start: Vec3d, end: Vec3d, minU: Double, minV: Double, maxU: Double, maxV: Double, draw1: Boolean = true, draw2: Boolean = true) {
if (draw1) {
buffer.pos(start.x, start.y, start.z).tex(minU, minV).endVertex()
buffer.pos(start.x, end.y, if (start.x == end.x) start.z else end.z).tex(minU, maxV).endVertex()
buffer.pos(end.x, end.y, end.z).tex(maxU, maxV).endVertex()
buffer.pos(end.x, start.y, if (start.x == end.x) end.z else start.z).tex(maxU, minV).endVertex()
}
if (draw2) {
buffer.pos(start.x, start.y, start.z).tex(minU, minV).endVertex()
buffer.pos(end.x, start.y, if (start.x == end.x) end.z else start.z).tex(maxU, minV).endVertex()
buffer.pos(end.x, end.y, end.z).tex(maxU, maxV).endVertex()
buffer.pos(start.x, end.y, if (start.x == end.x) start.z else end.z).tex(minU, maxV).endVertex()
}
}
} | mit | 51beb683f54fdb801bfae620194b24e6 | 47.778947 | 180 | 0.575858 | 3.963787 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/ui/views/viewer/ImageMediaView.kt | 1 | 4109 | package com.pr0gramm.app.ui.views.viewer
import android.annotation.SuppressLint
import android.view.View
import androidx.core.view.isVisible
import com.davemorrissey.labs.subscaleview.ImageSource
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView
import com.pr0gramm.app.R
import com.pr0gramm.app.databinding.PlayerKindImageBinding
import com.pr0gramm.app.util.ErrorFormatting
import com.pr0gramm.app.util.debugOnly
import com.pr0gramm.app.util.decoders.Decoders
import com.pr0gramm.app.util.decoders.PicassoDecoder
import com.pr0gramm.app.util.di.injector
import kotlin.math.max
@SuppressLint("ViewConstructor")
class ImageMediaView(config: MediaView.Config) : MediaView(config, R.layout.player_kind_image) {
private val capImageRatio = 1f / 64f
private val tag = "ImageMediaView" + System.identityHashCode(this)
private val views = PlayerKindImageBinding.bind(this)
init {
views.image.visibility = View.VISIBLE
views.image.alpha = 0f
views.image.isZoomEnabled = false
views.image.isQuickScaleEnabled = false
views.image.isPanEnabled = false
debugOnly {
views.image.setDebug(true)
}
// try not to use too much memory, even on big devices
views.image.setMaxTileSize(2048)
views.image.setBitmapDecoderFactory(PicassoDecoder.factory(tag, picasso))
views.image.setRegionDecoderFactory(Decoders.regionDecoderFactory(context.injector.instance()))
views.image.setOnImageEventListener(object : SubsamplingScaleImageView.DefaultOnImageEventListener() {
override fun onImageLoaded() {
hideBusyIndicator()
onMediaShown()
}
override fun onImageLoadError(error: Exception) {
hideBusyIndicator()
showErrorIndicator(error)
}
override fun onReady() {
applyScaling()
}
})
views.image.addOnLayoutChangeListener { v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
if (views.image.sWidth > 0 && views.image.sHeight > 0) {
applyScaling()
}
}
// addOnDetachListener {
// picasso.cancelTag(tag)
// views.image.recycle()
// views.image.setOnImageEventListener(null)
// views.image.removeFromParent()
// }
// start loading
val tiling = config.previewInfo?.let { it.width > 2000 || it.height > 2000 } ?: false
views.image.setImage(ImageSource.uri(effectiveUri).tiling(tiling))
showBusyIndicator()
}
internal fun applyScaling() {
val ratio = views.image.sWidth.toFloat() / views.image.sHeight.toFloat()
val ratioCapped = max(ratio, capImageRatio)
viewAspect = ratioCapped
val viewWidth = views.image.width.toFloat()
val viewHeight = views.image.height.toFloat()
val maxScale = viewWidth / views.image.sWidth
val minScale = viewHeight / views.image.sHeight
views.image.minScale = minScale
views.image.maxScale = maxScale
views.image.setMinimumScaleType(SubsamplingScaleImageView.SCALE_TYPE_START)
views.image.resetScaleAndCenter()
}
override fun onMediaShown() {
views.image.isVisible = true
if (views.image.alpha == 0f) {
views.image.animate().alpha(1f)
.setDuration(MediaView.ANIMATION_DURATION)
.withEndAction { super.onMediaShown() }
.start()
} else {
super.onMediaShown()
}
}
@SuppressLint("SetTextI18n")
internal fun showErrorIndicator(error: Exception) {
views.error.visibility = View.VISIBLE
views.error.alpha = 0f
views.error.animate().alpha(1f).start()
// set a more useful error message
views.error.text = context.getText(R.string.could_not_load_image).toString() +
"\n\n" + ErrorFormatting.getFormatter(error).getMessage(context, error)
}
}
| mit | a625fcfb56333231afd5e4603fd60cfb | 33.529412 | 116 | 0.65174 | 4.329821 | false | false | false | false |
JVMDeveloperID/kotlin-android-example | app/src/main/kotlin/com/gojek/sample/kotlin/views/home/HomePresenter.kt | 1 | 2315 | package com.gojek.sample.kotlin.views.home
import com.gojek.sample.kotlin.internal.data.local.RealmManagers
import com.gojek.sample.kotlin.internal.data.local.model.Contacts
import com.gojek.sample.kotlin.internal.data.local.realm.ContactsRealm
import com.gojek.sample.kotlin.internal.data.remote.Api
import com.gojek.sample.kotlin.internal.data.remote.response.ContactsResponse
import com.gojek.sample.kotlin.views.base.Presenter
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject
class HomePresenter @Inject constructor(private val api: Api) : Presenter<HomeView> {
var view: HomeView? = null
@Inject
lateinit var realmManagers: RealmManagers
override fun onAttach(view: HomeView) {
this.view = view
}
override fun onDetach() {
view = null
}
fun loadContacts() {
if (checkContacts() != 0) {
val contactsRealm: List<ContactsRealm> = realmManagers.getAllContacts()
val contacts: List<Contacts> = contactsRealm.map {
val id: Int? = it.id
val firstName: String = it.firstName
val lastName: String = it.lastName
val profilePic: String = it.profilePic
Contacts(id, firstName, lastName, profilePic)
}
view?.onShowContacts(contacts)
} else {
view?.onShowProgressBar()
api.getContacts().observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe({ setContactsResponse(it) }, Throwable::printStackTrace)
}
}
fun setContactsResponse(response: List<ContactsResponse>) {
val contacts: List<Contacts> = response.map {
val id: Int? = it.id
val firstName: String = it.firstName
val lastName: String = it.lastName
val profilePic: String = it.profilePic
Contacts(id, firstName, lastName, profilePic)
}
contacts.forEach { realmManagers.saveOrUpdateContacts(it) }
view?.onHideProgressBar()
view?.onShowContacts(contacts)
}
fun navigateDetailScreen(id: Int?) {
view?.onNavigateDetailScreen(id)
}
private fun checkContacts(): Int = realmManagers.getAllContacts().size
} | apache-2.0 | 266377b07829fd666b8ee249a8be1884 | 34.090909 | 167 | 0.670842 | 4.530333 | false | false | false | false |
mostley/handplotter | software/AndroidApp2/app/src/main/java/com/handplotter/shdev/handplotter/SessionActivity.kt | 1 | 8122 | package com.handplotter.shdev.handplotter
import android.content.Context
import android.content.Intent
import android.content.res.Configuration.ORIENTATION_PORTRAIT
import android.net.Uri
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.support.constraint.ConstraintLayout
import android.util.Log
import android.view.*
import android.widget.FrameLayout
import com.caverock.androidsvg.SVG
import com.caverock.androidsvg.SVGImageView
import org.opencv.android.CameraBridgeViewBase
import org.opencv.core.Mat
import org.opencv.android.LoaderCallbackInterface
import org.opencv.android.BaseLoaderCallback
import org.opencv.android.OpenCVLoader
import org.opencv.core.Core
import org.opencv.core.CvType
import org.opencv.imgproc.Imgproc
import org.opencv.aruco.Aruco
import org.opencv.aruco.Dictionary
class SessionActivity : AppCompatActivity(), CameraBridgeViewBase.CvCameraViewListener2 {
private var fullscreenContent: ConstraintLayout? = null
private val mHideHandler = Handler()
private val mHidePart2Runnable = Runnable {
// Delayed removal of status and navigation bar
// Note that some of these constants are new as of API 16 (Jelly Bean)
// and API 19 (KitKat). It is safe to use them, as they are inlined
// at compile-time and do nothing on earlier devices.
fullscreenContent!!.systemUiVisibility =
View.SYSTEM_UI_FLAG_LOW_PROFILE or
View.SYSTEM_UI_FLAG_FULLSCREEN or
View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
}
// Used for logging success or failure messages
private val TAG = "SessionActivity"
// Loads camera view of OpenCV for us to use. This lets us see using OpenCV
private var openCvCameraView: CameraBridgeViewBase? = null
// Used in Camera selection from menu (when implemented)
private val isJavaCamera = true
private val itemSwitchCamera: MenuItem? = null
// These variables are used (at the moment) to fix camera orientation from 270degree to 0degree
private var rgba: Mat? = null
private var rgbaF: Mat? = null
private var rgbaT: Mat? = null
private var markerIds: Mat? = null
private var dictionary: Dictionary? = null
private var corners: List<Mat> = ArrayList()
private val loaderCallback = object : BaseLoaderCallback(this) {
override fun onManagerConnected(status: Int) {
when (status) {
LoaderCallbackInterface.SUCCESS -> {
Log.i(TAG, "OpenCV loaded successfully")
openCvCameraView!!.enableView()
dictionary = Aruco.getPredefinedDictionary(Aruco.DICT_6X6_250);
markerIds = Mat()
}
else -> {
super.onManagerConnected(status)
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
Log.i(TAG, "called onCreate");
super.onCreate(savedInstanceState)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_session)
val imageUri = Uri.parse(intent.getStringExtra(INTENT_IMAGE_URI))
requireNotNull(imageUri) { "no imageUri provided in Intent extras" }
val pos_x = intent.getIntExtra(INTENT_DESIGN_POS_X, 0)
val pos_y = intent.getIntExtra(INTENT_DESIGN_POS_Y, 0)
val scale = intent.getFloatExtra(INTENT_DESIGN_SCALE, 1f)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
val inputStream = contentResolver.openInputStream(imageUri)
val svg = SVG.getFromInputStream(inputStream)
val imageView = SVGImageView(this)
imageView.setSVG(svg)
imageView.layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT)
val layoutContainer = findViewById<FrameLayout>(R.id.layoutContainer)
//layoutContainer!!.addView(imageView)
fullscreenContent = findViewById(R.id.fullscreen_content)
openCvCameraView = findViewById(R.id.cameraSurface);
openCvCameraView!!.visibility = SurfaceView.VISIBLE;
openCvCameraView!!.setCvCameraViewListener(this);
}
public override fun onPause() {
super.onPause()
if (openCvCameraView != null) {
openCvCameraView!!.disableView()
}
}
public override fun onResume() {
super.onResume()
if (!OpenCVLoader.initDebug()) {
Log.d(TAG, "Internal OpenCV library not found. Using OpenCV Manager for initialization")
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_0_0, this, loaderCallback)
} else {
Log.d(TAG, "OpenCV library found inside package. Using it!")
loaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS)
}
}
public override fun onDestroy() {
super.onDestroy()
if (openCvCameraView != null) {
openCvCameraView!!.disableView()
}
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
hide()
}
private fun hide() {
// Hide UI first
supportActionBar?.hide()
// Schedule a runnable to remove the status and navigation bar after a delay
mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY.toLong())
}
override fun onCameraViewStarted(width: Int, height: Int) {
rgba = Mat(height, width, CvType.CV_8UC4)
rgbaF = Mat(height, width, CvType.CV_8UC4)
rgbaT = Mat(width, width, CvType.CV_8UC4)
}
override fun onCameraViewStopped() {
rgba!!.release();
}
override fun onCameraFrame(inputFrame: CameraBridgeViewBase.CvCameraViewFrame?): Mat {
//rgba = inputFrame!!.rgba()
val inputImage: Mat = inputFrame!!.gray()
Aruco.detectMarkers(inputImage, dictionary, corners, markerIds)
Aruco.drawDetectedMarkers(inputImage, corners)
if (windowManager.defaultDisplay.rotation == Surface.ROTATION_0) {
Core.transpose(inputImage, rgbaT)
Imgproc.resize(rgbaT, rgbaF, inputImage.size(), 0.0, 0.0, 0)
Core.flip(rgbaF, inputImage, 1)
} else if (windowManager.defaultDisplay.rotation == Surface.ROTATION_270) {
Imgproc.resize(inputImage, rgbaF, inputImage.size(), 0.0, 0.0, 0)
Core.flip(rgbaF, inputImage, -1)
} else if (windowManager.defaultDisplay.rotation == Surface.ROTATION_90) {
Imgproc.resize(inputImage, rgbaF, inputImage.size(), 0.0, 0.0, 0)
Core.flip(rgbaF, inputImage, 1)
}
return inputImage;
}
companion object {
/**
* Some older devices needs a small delay between UI widget updates
* and a change of the status and navigation bar.
*/
private const val UI_ANIMATION_DELAY = 300
private const val INTENT_IMAGE_URI = "image_uri"
private const val INTENT_DESIGN_POS_X = "design_pos_x"
private const val INTENT_DESIGN_POS_Y = "design_pos_y"
private const val INTENT_DESIGN_SCALE = "design_scale"
fun newIntent(context: Context, image: Uri, pos_x: Int, pos_y: Int, scale: Float): Intent {
val intent = Intent(context, SessionActivity::class.java)
intent.putExtra(INTENT_IMAGE_URI, image.toString())
intent.putExtra(INTENT_DESIGN_POS_X, pos_x)
intent.putExtra(INTENT_DESIGN_POS_Y, pos_y)
intent.putExtra(INTENT_DESIGN_SCALE, scale)
return intent
}
}
}
| mit | 88d39505eef2714be896a8f9ee3bf77c | 35.953271 | 100 | 0.645161 | 4.522272 | false | false | false | false |
AoEiuV020/PaNovel | pager/src/main/java/cc/aoeiuv020/pager/Pager.kt | 1 | 6815 | package cc.aoeiuv020.pager
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.PointF
import android.graphics.Rect
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import cc.aoeiuv020.pager.animation.*
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.debug
import org.jetbrains.anko.verbose
/**
* 自定义翻页动画视图,
*
* 分成背景和前景两个部分,
*
* Created by AoEiuV020 on 2017.12.02-17:58:54.
*/
class Pager : View, PageAnimation.OnPageChangeListener, AnkoLogger {
constructor(context: Context)
: super(context)
constructor(context: Context, attrs: AttributeSet)
: super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int)
: super(context, attrs, defStyleAttr)
private var mAnim: PagerAnimation? = null
private val drawListener: PageAnimation.OnPageChangeListener = this
var actionListener: ActionListener? = null
private var direction = PagerDirection.NONE
private var centerRect = Rect(0, 0, 0, 0)
/**
* 背景色,同时设置成仿真翻页的背面主色,
*/
var bgColor: Int = 0xffffffff.toInt()
set(value) {
field = value
(mAnim as? SimulationPageAnim)?.setMainColor(value)
}
var drawer: IPagerDrawer = BlankPagerDrawer()
set(value) {
field = value
resetDrawer()
}
/**
* 前景的上下左右留白,
*/
var margins: IMargins = IMarginsImpl()
set(value) {
field = value
resetAnim()
resetDrawer()
}
var animMode: AnimMode = AnimMode.SIMULATION
set(value) {
field = value
resetAnim()
}
var animDurationMultiply: Float = 0.8f
set(value) {
field = value
mAnim?.setDurationMultiply(value)
}
var fullScreenClickNextPage: Boolean = false
/**
* 单击不翻页的中心大小,单位百分比,
*/
var centerPercent: Float = 0.5f
set(value) {
field = value
resetCenterRect(width, height)
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
resetDrawer()
resetAnim(w, h)
refresh()
resetCenterRect(w, h)
}
private fun resetCenterRect(w: Int, h: Int) {
val left = (w / 2 * (1 - centerPercent)).toInt()
val right = w - left
val top = (h / 2 * (1 - centerPercent)).toInt()
val bottom = h - top
centerRect = Rect(left, top, right, bottom)
}
override fun drawCurrent(backgroundCanvas: Canvas, nextCanvas: Canvas) {
backgroundCanvas.drawColor(bgColor)
drawer.drawCurrentPage(backgroundCanvas, nextCanvas)
}
override fun hasPrev(): Boolean {
debug { "prev" }
direction = PagerDirection.PREV
actionListener?.onPagePrev()
return drawer.scrollToPrev()
}
override fun hasNext(): Boolean {
debug { "next" }
direction = PagerDirection.NEXT
actionListener?.onPageNext()
return drawer.scrollToNext()
}
override fun pageCancel() {
debug { "cancel" }
when (direction) {
PagerDirection.NEXT -> drawer.scrollToPrev()
PagerDirection.PREV -> drawer.scrollToNext()
PagerDirection.NONE -> {
}
}
}
fun refresh() {
mAnim?.refresh()
?: debug { "anim == null" }
}
/**
* 如果视图没初始化就不重置动画,
*/
private fun resetAnim() {
if (width != 0 && height != 0) {
resetAnim(width, height)
}
}
private fun resetDrawer() {
if (width != 0 && height != 0) {
drawer.attach(this,
Size(width, height),
Size(width - Math.ceil((margins.left + margins.right) * width / 100.0).toInt(),
height - Math.ceil((margins.top + margins.bottom) * height / 100.0).toInt()
))
}
}
private fun resetAnim(w: Int, h: Int) {
val config = AnimationConfig(w, h, margins, this, drawListener, animDurationMultiply)
mAnim = when (animMode) {
AnimMode.SIMULATION -> SimulationPageAnim(config).apply { setMainColor(bgColor) }
AnimMode.COVER -> CoverPageAnim(config)
AnimMode.SLIDE -> SlidePageAnim(config)
AnimMode.NONE -> NonePageAnim(config)
AnimMode.SCROLL -> ScrollPageAnim(config)
}
}
override fun onDraw(canvas: Canvas) {
verbose { "onDraw" }
mAnim?.draw(canvas)
}
override fun computeScroll() {
mAnim?.scrollAnim()
}
private val startPoint = PointF()
private val sold = ViewConfiguration.get(context).scaledTouchSlop
private var isClick = false
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
isClick = true
startPoint.set(event.x, event.y)
}
MotionEvent.ACTION_MOVE -> {
if (isClick && (Math.abs(event.x - startPoint.x) > sold || Math.abs(event.y - startPoint.y) > sold)) {
isClick = false
}
if (isClick) {
return true
}
}
MotionEvent.ACTION_UP -> {
if (isClick) {
click(event.x, event.y)
isClick = false
return true
}
}
}
return mAnim?.onTouchEvent(event) ?: false
}
private fun click(x: Float, y: Float) {
debug {
"<$fullScreenClickNextPage, $x, $y>"
}
when {
centerRect.contains(x.toInt(), y.toInt()) -> // 如果点击中心部分,回调退出全屏,
actionListener?.onCenterClick()
!fullScreenClickNextPage && x < ((1 - (y / height)) * width) -> // 如果点击对角线左上,翻上页,
mAnim?.scrollPrev(x, y)
else -> // 否则翻下页,
mAnim?.scrollNext(x, y)
}
}
fun scrollNext() = mAnim?.scrollNext() ?: false
fun scrollPrev() = mAnim?.scrollPrev() ?: false
interface ActionListener {
fun onCenterClick()
/**
* 无论是否存在上一页都会调用这个方法,
*/
fun onPagePrev()
fun onPageNext()
}
} | gpl-3.0 | 4a4fcac651b90bc77e7985b0be2a1943 | 28.205357 | 118 | 0.557866 | 4.343293 | false | false | false | false |
dafi/photoshelf | core/src/main/java/com/ternaryop/photoshelf/lifecycle/Command.kt | 1 | 837 | package com.ternaryop.photoshelf.lifecycle
enum class Status {
SUCCESS,
ERROR,
PROGRESS
}
data class ProgressData(val step: Int, val itemCount: Int)
data class Command<out T>(
val status: Status,
val data: T? = null,
val error: Throwable? = null,
val progressData: ProgressData? = null
) {
companion object {
fun <T> success(data: T?) = Command(Status.SUCCESS, data)
fun <T> error(error: Throwable, data: T? = null) = Command(Status.ERROR, data, error = error)
fun <T> progress(progressData: ProgressData) = Command<T>(Status.PROGRESS, progressData = progressData)
suspend fun <T> execute(action: suspend () -> T) =
try {
success(action())
} catch (expected: Throwable) {
error<T>(expected)
}
}
}
| mit | f51e2d15ae40b080ec6e9cc349eeeb48 | 27.862069 | 111 | 0.600956 | 3.857143 | false | false | false | false |
wiltonlazary/kotlin-native | tools/benchmarksAnalyzer/src/main/kotlin/org/jetbrains/renders/Render.kt | 1 | 8299 | /*
* Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.renders
import org.jetbrains.analyzer.*
import org.jetbrains.report.*
import kotlin.math.abs
// Base class for printing report in different formats.
abstract class Render {
companion object {
fun getRenderByName(name: String) =
when (name) {
"text" -> TextRender()
"html" -> HTMLRender()
"teamcity" -> TeamCityStatisticsRender()
"statistics" -> StatisticsRender()
"metrics" -> MetricResultsRender()
else -> error("Unknown render $name")
}
}
abstract val name: String
abstract fun render(report: SummaryBenchmarksReport, onlyChanges: Boolean = false): String
// Print report using render.
fun print(report: SummaryBenchmarksReport, onlyChanges: Boolean = false, outputFile: String? = null) {
val content = render(report, onlyChanges)
outputFile?.let {
writeToFile(outputFile, content)
} ?: println(content)
}
protected fun formatValue(number: Double, isPercent: Boolean = false): String =
if (isPercent) number.format(2) + "%" else number.format()
}
// Report render to text format.
class TextRender: Render() {
override val name: String
get() = "text"
private val content = StringBuilder()
private val headerSeparator = "================="
private val wideColumnWidth = 50
private val standardColumnWidth = 25
private fun append(text: String = "") {
content.append("$text\n")
}
override fun render(report: SummaryBenchmarksReport, onlyChanges: Boolean): String {
renderEnvChanges(report.envChanges, "Environment")
renderEnvChanges(report.kotlinChanges, "Compiler")
renderStatusSummary(report)
renderStatusChangesDetails(report.getBenchmarksWithChangedStatus())
renderPerformanceSummary(report)
renderPerformanceDetails(report, onlyChanges)
return content.toString()
}
private fun printBucketInfo(bucket: Collection<Any>, name: String) {
if (!bucket.isEmpty()) {
append("$name: ${bucket.size}")
}
}
private fun <T> printStatusChangeInfo(bucket: List<FieldChange<T>>, name: String) {
if (!bucket.isEmpty()) {
append("$name:")
for (change in bucket) {
append(change.renderAsText())
}
}
}
fun renderEnvChanges(envChanges: List<FieldChange<String>>, bucketName: String) {
if (!envChanges.isEmpty()) {
append(ChangeReport(bucketName, envChanges).renderAsTextReport())
}
}
fun renderStatusChangesDetails(benchmarksWithChangedStatus: List<FieldChange<BenchmarkResult.Status>>) {
if (!benchmarksWithChangedStatus.isEmpty()) {
append("Changes in status")
append(headerSeparator)
printStatusChangeInfo(benchmarksWithChangedStatus
.filter { it.current == BenchmarkResult.Status.FAILED }, "New failures")
printStatusChangeInfo(benchmarksWithChangedStatus
.filter { it.current == BenchmarkResult.Status.PASSED }, "New passes")
append()
}
}
fun renderStatusSummary(report: SummaryBenchmarksReport) {
append("Status summary")
append(headerSeparator)
val failedBenchmarks = report.failedBenchmarks
val addedBenchmarks = report.addedBenchmarks
val removedBenchmarks = report.removedBenchmarks
if (failedBenchmarks.isEmpty()) {
append("All benchmarks passed!")
}
if (!failedBenchmarks.isEmpty() || !addedBenchmarks.isEmpty() || !removedBenchmarks.isEmpty()) {
printBucketInfo(failedBenchmarks, "Failed benchmarks")
printBucketInfo(addedBenchmarks, "Added benchmarks")
printBucketInfo(removedBenchmarks, "Removed benchmarks")
}
append("Total becnhmarks number: ${report.benchmarksNumber}")
append()
}
fun renderPerformanceSummary(report: SummaryBenchmarksReport) {
if (!report.regressions.isEmpty() || !report.improvements.isEmpty()) {
append("Performance summary")
append(headerSeparator)
if (!report.regressions.isEmpty()) {
append("Regressions: Maximum = ${formatValue(report.maximumRegression, true)}," +
" Geometric mean = ${formatValue(report.regressionsGeometricMean, true)}")
}
if (!report.improvements.isEmpty()) {
append("Improvements: Maximum = ${formatValue(report.maximumImprovement, true)}," +
" Geometric mean = ${formatValue(report.improvementsGeometricMean, true)}")
}
append()
}
}
private fun formatColumn(content:String, isWide: Boolean = false): String =
content.padEnd(if (isWide) wideColumnWidth else standardColumnWidth, ' ')
private fun printBenchmarksDetails(fullSet: Map<String, SummaryBenchmark>,
bucket: Map<String, ScoreChange>? = null) {
val placeholder = "-"
if (bucket != null) {
// There are changes in performance.
// Output changed benchmarks.
for ((name, change) in bucket) {
append(formatColumn(name, true) +
formatColumn(fullSet.getValue(name).first?.description ?: placeholder) +
formatColumn(fullSet.getValue(name).second?.description ?: placeholder) +
formatColumn(change.first.description + " %") +
formatColumn(change.second.description))
}
} else {
// Output all values without performance changes.
for ((name, value) in fullSet) {
append(formatColumn(name, true) +
formatColumn(value.first?.description ?: placeholder) +
formatColumn(value.second?.description ?: placeholder) +
formatColumn(placeholder) +
formatColumn(placeholder))
}
}
}
private fun printTableLineSeparator(tableWidth: Int) =
append("${"-".padEnd(tableWidth, '-')}")
private fun printPerformanceTableHeader(): Int {
val wideColumns = listOf(formatColumn("Benchmark", true))
val standardColumns = listOf(formatColumn("First score"),
formatColumn("Second score"),
formatColumn("Percent"),
formatColumn("Ratio"))
val tableWidth = wideColumnWidth * wideColumns.size + standardColumnWidth * standardColumns.size
append("${wideColumns.joinToString(separator = "")}${standardColumns.joinToString(separator = "")}")
printTableLineSeparator(tableWidth)
return tableWidth
}
fun renderPerformanceDetails(report: SummaryBenchmarksReport, onlyChanges: Boolean = false) {
append("Performance details")
append(headerSeparator)
if (onlyChanges) {
if (report.regressions.isEmpty() && report.improvements.isEmpty()) {
append("All becnhmarks are stable.")
}
}
val tableWidth = printPerformanceTableHeader()
// Print geometric mean.
val geoMeanChangeMap = report.geoMeanScoreChange?.
let { mapOf(report.geoMeanBenchmark.first!!.name to report.geoMeanScoreChange!!) }
printBenchmarksDetails(
mutableMapOf(report.geoMeanBenchmark.first!!.name to report.geoMeanBenchmark),
geoMeanChangeMap)
printTableLineSeparator(tableWidth)
printBenchmarksDetails(report.mergedReport, report.regressions)
printBenchmarksDetails(report.mergedReport, report.improvements)
if (!onlyChanges) {
// Print all remaining results.
printBenchmarksDetails(report.mergedReport.filter { it.key !in report.regressions.keys &&
it.key !in report.improvements.keys })
}
}
} | apache-2.0 | 86a37698db17c4053340628f499d93fc | 39.487805 | 108 | 0.616219 | 5.1804 | false | false | false | false |
nemerosa/ontrack | ontrack-model/src/main/java/net/nemerosa/ontrack/model/structure/ValidationRun.kt | 1 | 4427 | package net.nemerosa.ontrack.model.structure
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonView
import java.time.LocalDateTime
/**
* @property runOrder The run order is the order of run for the build. It starts with 1 for the first run.
* @property validationRunStatuses Must always contain at least one validation run status at creation time.
* @property data Data used for the link to an optional [ValidationDataType] and its data
*/
data class ValidationRun(
override val id: ID,
@JsonView(value = [ValidationRun::class, ValidationStampRunView::class])
val build: Build,
@JsonView(value = [ValidationRun::class, Build::class])
val validationStamp: ValidationStamp,
val runOrder: Int,
val data: ValidationRunData<*>?,
@JsonView(value = [ValidationRun::class, BranchBuildView::class, Build::class, ValidationStampRunView::class])
val validationRunStatuses: List<ValidationRunStatus>
) : RunnableEntity {
@JsonIgnore
override val runnableEntityType: RunnableEntityType = RunnableEntityType.validation_run
override val runMetricName: String
@JsonIgnore
get() = build.name
override val runMetricTags: Map<String, String>
@JsonIgnore
get() = mapOf(
"project" to validationStamp.branch.project.name,
"branch" to validationStamp.branch.name,
"validationStamp" to validationStamp.name,
"status" to lastStatusId
)
override val runTime: LocalDateTime
get() = signature.time
/**
* The validation run, as such, as no description, because it's managed at validation run status level.
*/
override val description: String? = null
/**
* Gets the name of the last status
*/
val lastStatusId: String =
if (validationRunStatuses.isEmpty()) {
""
} else {
validationRunStatuses.first().statusID.id
}
fun withData(data: ValidationRunData<*>?) =
ValidationRun(id, build, validationStamp, runOrder, data, validationRunStatuses)
fun add(status: ValidationRunStatus): ValidationRun = ValidationRun(
id,
build,
validationStamp,
runOrder,
data,
listOf(status) + validationRunStatuses
)
override val project: Project
get() = build.project
override val parent: ProjectEntity? get() = validationStamp
override val projectEntityType: ProjectEntityType = ProjectEntityType.VALIDATION_RUN
override val entityDisplayName: String
get() = "Validation run ${validationStamp.name}#${runOrder} for ${build.branch.project.name}/${build.branch.name}/${build.name}"
companion object {
@JvmStatic
fun of(build: Build, validationStamp: ValidationStamp, runOrder: Int, statuses: List<ValidationRunStatus>) =
ValidationRun(
ID.NONE,
build,
validationStamp,
runOrder,
data = null,
validationRunStatuses = statuses
)
@JvmStatic
fun of(
build: Build,
validationStamp: ValidationStamp,
runOrder: Int,
signature: Signature,
validationRunStatusID: ValidationRunStatusID,
description: String?
) = of(
build,
validationStamp,
runOrder,
listOf(
ValidationRunStatus(ID.NONE, signature, validationRunStatusID, description)
)
)
}
fun withId(id: ID) = ValidationRun(id, build, validationStamp, runOrder, data, validationRunStatuses)
@JsonProperty("passed")
val isPassed: Boolean = lastStatus.isPassed
/**
* The last status ("last" from a business point of view) is actually the first one in the list of statuses because
* statuses are sorted from the most recent one to the least recent one.
*/
val lastStatus: ValidationRunStatus
get() = validationRunStatuses.first()
override val signature: Signature
get() = lastStatus.signature
}
| mit | 875f94c272975a3ca0979e25a4637b7d | 33.858268 | 136 | 0.622318 | 5.418605 | false | false | false | false |
outlying/MpkTransit | creator/src/main/kotlin/com/antyzero/mpk/transit/creator/Application.kt | 1 | 2008 | package com.antyzero.mpk.transit.creator
import com.antyzero.mpk.transit.creator.model.CsvContainer
import com.antyzero.mpk.transit.database.MpkDatabase
import com.antyzero.mpk.transit.database.MpkDatabaseDownloader
import java.io.File
import java.util.concurrent.atomic.AtomicLong
fun main(args: Array<String>) {
val startTime = System.currentTimeMillis()
val totalSize: AtomicLong = AtomicLong()
val databasePath = MpkDatabaseDownloader().get()
val database = MpkDatabase(databasePath)
val creator: Creator = DatabaseCreator(database)
val targetDir = args.takeIf { !args.isEmpty() }?.get(0).let { File(it) } // File.createTempFile("something", "").parentFile
val csvPrinter = CsvPrinter(targetDir)
println("Creating files in ${csvPrinter.dir}\n")
csvPrinter.print(creator.agency(), "agency.txt").sumSize(totalSize).printResult()
csvPrinter.print(creator.routes(), "routes.txt").sumSize(totalSize).printResult()
csvPrinter.print(creator.stops(), "stops.txt").sumSize(totalSize).printResult()
println("\nOperation took ${(System.currentTimeMillis() - startTime).toFloat() / 1000} [s]")
println("Total file size: ${totalSize.toLong() / 1024} [Kb]")
}
private fun Pair<Boolean, File>.printResult() = apply {
println(if (first) "Created ${second.name}\t${second.absolutePath}" else "Failed ${second.name}")
}
private fun Pair<Boolean, File>.sumSize(total: AtomicLong) = apply {
total.addAndGet(second.takeIf { first }?.length() ?: 0)
}
private class CsvPrinter(val dir: File) {
init {
dir.mkdirs()
}
fun print(cvs: CsvContainer<*>, fileName: String): Pair<Boolean, File> {
val targetFile = File(dir, fileName)
targetFile.takeIf { it.exists() && it.isFile }?.delete()
targetFile.takeIf { it.createNewFile() }?.let {
it.printWriter().use {
it.print(cvs.toString())
}
return true to targetFile
}
return false to File("")
}
} | gpl-3.0 | 6c8aaabca0e99a23a2337e67322ce5cf | 34.245614 | 127 | 0.679283 | 3.992048 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-stash/src/test/java/net/nemerosa/ontrack/extension/stash/AbstractBitbucketTestSupport.kt | 1 | 1138 | package net.nemerosa.ontrack.extension.stash
import net.nemerosa.ontrack.extension.stash.model.StashConfiguration
import net.nemerosa.ontrack.extension.stash.service.StashConfigurationService
import net.nemerosa.ontrack.graphql.AbstractQLKTITJUnit4Support
import net.nemerosa.ontrack.model.security.GlobalSettings
import net.nemerosa.ontrack.test.TestUtils
import org.springframework.beans.factory.annotation.Autowired
abstract class AbstractBitbucketTestSupport : AbstractQLKTITJUnit4Support() {
@Autowired
private lateinit var stashConfigurationService: StashConfigurationService
fun bitbucketConfig(configurationName: String = TestUtils.uid("C")): StashConfiguration =
withDisabledConfigurationTest {
asUser().with(GlobalSettings::class.java).call {
stashConfigurationService.newConfiguration(
StashConfiguration(
name = configurationName,
url = "https://bitbucket.org",
user = null,
password = null,
)
)
}
}
} | mit | 3cedabdf78039afb0dca3cb1d3a7aa36 | 38.275862 | 93 | 0.680141 | 5.633663 | false | true | false | false |
material-components/material-components-android-examples | Owl/app/src/main/java/com/materialstudies/owl/util/ShapeAppearanceTransformation.kt | 1 | 3313 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.materialstudies.owl.util
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapShader
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RectF
import android.graphics.Shader.TileMode.CLAMP
import androidx.annotation.StyleRes
import androidx.core.graphics.applyCanvas
import androidx.core.graphics.createBitmap
import com.bumptech.glide.Glide
import com.bumptech.glide.load.Transformation
import com.bumptech.glide.load.engine.Resource
import com.bumptech.glide.load.resource.bitmap.BitmapResource
import com.google.android.material.shape.ShapeAppearanceModel
import com.google.android.material.shape.ShapeAppearancePathProvider
import java.security.MessageDigest
/**
* A Glide [Transformation] which applies a [ShapeAppearanceModel] to images.
*/
class ShapeAppearanceTransformation(
@StyleRes private val shapeAppearanceId: Int
) : Transformation<Bitmap> {
private var shapeAppearanceModel: ShapeAppearanceModel? = null
@SuppressLint("RestrictedApi")
override fun transform(
context: Context,
resource: Resource<Bitmap>,
outWidth: Int,
outHeight: Int
): Resource<Bitmap> {
val model = shapeAppearanceModel ?: ShapeAppearanceModel.builder(
context,
shapeAppearanceId,
0
).build()
.also { shapeAppearanceModel = it }
val bitmap = createBitmap(outWidth, outHeight)
bitmap.applyCanvas {
val path = Path().apply {
val bounds = RectF(0f, 0f, outWidth.toFloat(), outHeight.toFloat())
ShapeAppearancePathProvider().calculatePath(model, 1f, bounds, this)
}
val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
shader = BitmapShader(resource.get(), CLAMP, CLAMP)
}
drawPath(path, paint)
}
return BitmapResource(bitmap, Glide.get(context).bitmapPool)
}
override fun updateDiskCacheKey(messageDigest: MessageDigest) {
messageDigest.update(javaClass.canonicalName!!.toByteArray())
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ShapeAppearanceTransformation
if (shapeAppearanceId != other.shapeAppearanceId) return false
if (shapeAppearanceModel != other.shapeAppearanceModel) return false
return true
}
override fun hashCode(): Int {
var result = shapeAppearanceId
result = 31 * result + (shapeAppearanceModel?.hashCode() ?: 0)
return result
}
}
| apache-2.0 | 5a5964645e2d7149a359ebf350c49f62 | 33.510417 | 84 | 0.705403 | 4.739628 | false | false | false | false |
equeim/tremotesf-android | app/src/main/kotlin/org/equeim/tremotesf/ui/torrentpropertiesfragment/TrackersAdapter.kt | 1 | 11881 | /*
* Copyright (C) 2017-2022 Alexey Rochev <[email protected]>
*
* This file is part of Tremotesf.
*
* Tremotesf 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.
*
* Tremotesf 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 org.equeim.tremotesf.ui.torrentpropertiesfragment
import android.app.Dialog
import android.os.Bundle
import android.text.InputType
import android.text.format.DateUtils
import android.view.*
import android.widget.TextView
import androidx.appcompat.view.ActionMode
import androidx.recyclerview.widget.DiffUtil
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import org.equeim.libtremotesf.Tracker
import org.equeim.tremotesf.R
import org.equeim.tremotesf.common.AlphanumericComparator
import org.equeim.tremotesf.databinding.AddTrackersDialogBinding
import org.equeim.tremotesf.databinding.TrackerListItemBinding
import org.equeim.tremotesf.rpc.GlobalRpc
import org.equeim.tremotesf.torrentfile.rpc.Torrent
import org.equeim.tremotesf.ui.NavigationDialogFragment
import org.equeim.tremotesf.ui.SelectionTracker
import org.equeim.tremotesf.ui.navigate
import org.equeim.tremotesf.ui.utils.StateRestoringListAdapter
import org.equeim.tremotesf.ui.utils.bindingAdapterPositionOrNull
import org.equeim.tremotesf.ui.utils.createTextFieldDialog
data class TrackersAdapterItem(
val id: Int,
var announce: String,
var status: Tracker.Status,
var errorMessage: String,
var peers: Int,
private var nextUpdateTime: Long
) {
var nextUpdateEta = 0L
constructor(rpcTracker: Tracker) : this(
rpcTracker.id(),
rpcTracker.announce(),
rpcTracker.status(),
rpcTracker.errorMessage(),
rpcTracker.peers(),
rpcTracker.nextUpdateTime()
)
init {
updateNextUpdateEta()
}
fun updatedFrom(rpcTracker: Tracker): TrackersAdapterItem {
return copy(
announce = rpcTracker.announce(),
status = rpcTracker.status(),
errorMessage = rpcTracker.errorMessage(),
peers = rpcTracker.peers(),
nextUpdateTime = rpcTracker.nextUpdateTime()
)
}
fun updateNextUpdateEta() {
nextUpdateEta = if (nextUpdateTime > 0) {
val eta = nextUpdateTime - System.currentTimeMillis() / 1000
if (eta < 0) -1 else eta
} else {
-1
}
}
}
class TrackersAdapter(
private val fragment: TrackersFragment
) : StateRestoringListAdapter<TrackersAdapterItem, TrackersAdapter.ViewHolder>(Callback()) {
private var torrent: Torrent? = null
private val comparator = object : Comparator<TrackersAdapterItem> {
private val stringComparator = AlphanumericComparator()
override fun compare(o1: TrackersAdapterItem, o2: TrackersAdapterItem) =
stringComparator.compare(
o1.announce,
o2.announce
)
}
private val context = fragment.requireContext()
private val selectionTracker = SelectionTracker.createForIntKeys(
this,
true,
fragment,
::ActionModeCallback,
R.plurals.trackers_selected
) { getItem(it).id }
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
selectionTracker,
TrackerListItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.update()
fun update(torrent: Torrent?) {
if (torrent == null) {
if (this.torrent == null) {
return
}
this.torrent = null
submitList(null)
return
}
this.torrent = torrent
val trackers = currentList
if (!torrent.isChanged && !(trackers.isEmpty() && torrent.trackerSites.isNotEmpty())) {
trackers.forEach(TrackersAdapterItem::updateNextUpdateEta)
notifyItemRangeChanged(0, trackers.size)
return
}
val newTrackers = mutableListOf<TrackersAdapterItem>()
val rpcTrackers = torrent.trackers
for (rpcTracker: Tracker in rpcTrackers) {
val id = rpcTracker.id()
var tracker = trackers.find { it.id == id }
tracker = tracker?.updatedFrom(rpcTracker) ?: TrackersAdapterItem(rpcTracker)
newTrackers.add(tracker)
}
submitList(newTrackers.sortedWith(comparator)) {
selectionTracker.commitAdapterUpdate()
}
}
override fun allowStateRestoring(): Boolean {
return GlobalRpc.isConnected.value
}
override fun onStateRestored() {
selectionTracker.restoreInstanceState()
}
inner class ViewHolder(
selectionTracker: SelectionTracker<Int>,
val binding: TrackerListItemBinding
) : SelectionTracker.ViewHolder<Int>(selectionTracker, binding.root) {
override fun onClick(view: View) {
val position = bindingAdapterPositionOrNull ?: return
val tracker = getItem(position)
fragment.navigate(
TorrentPropertiesFragmentDirections.toEditTrackerDialog(
tracker.id,
tracker.announce
)
)
}
override fun update() {
super.update()
val tracker = bindingAdapterPositionOrNull?.let(::getItem) ?: return
with(binding) {
nameTextView.text = tracker.announce
statusTextView.text = when (tracker.status) {
Tracker.Status.Inactive -> context.getString(R.string.tracker_inactive)
Tracker.Status.Active -> context.getString(R.string.tracker_active)
Tracker.Status.Queued -> context.getString(R.string.tracker_queued)
Tracker.Status.Updating -> context.getString(R.string.tracker_updating)
else -> {
if (tracker.errorMessage.isEmpty()) {
context.getString(R.string.error)
} else {
context.getString(R.string.tracker_error, tracker.errorMessage)
}
}
}
if (tracker.status == Tracker.Status.Error) {
peersTextView.visibility = View.GONE
} else {
peersTextView.text = context.resources.getQuantityString(
R.plurals.peers_plural,
tracker.peers,
tracker.peers
)
peersTextView.visibility = View.VISIBLE
}
if (tracker.nextUpdateEta < 0) {
nextUpdateTextView.visibility = View.GONE
} else {
nextUpdateTextView.text = context.getString(
R.string.next_update,
DateUtils.formatElapsedTime(tracker.nextUpdateEta)
)
nextUpdateTextView.visibility = View.VISIBLE
}
}
}
}
private class Callback : DiffUtil.ItemCallback<TrackersAdapterItem>() {
override fun areItemsTheSame(
oldItem: TrackersAdapterItem,
newItem: TrackersAdapterItem
): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(
oldItem: TrackersAdapterItem,
newItem: TrackersAdapterItem
): Boolean {
return oldItem == newItem
}
}
private class ActionModeCallback(selectionTracker: SelectionTracker<Int>) :
SelectionTracker.ActionModeCallback<Int>(selectionTracker) {
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
mode.menuInflater.inflate(R.menu.trackers_context_menu, menu)
return true
}
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
if (super.onActionItemClicked(mode, item)) {
return true
}
val selectionTracker = this.selectionTracker ?: return false
if (item.itemId == R.id.remove) {
activity.navigate(
TorrentPropertiesFragmentDirections.toRemoveTrackerDialog(
selectionTracker.selectedKeys.toIntArray()
)
)
return true
}
return false
}
}
}
class EditTrackerDialogFragment : NavigationDialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val args = EditTrackerDialogFragmentArgs.fromBundle(requireArguments())
val addingTrackers = (args.trackerId == -1)
val onAccepted = { textField: TextView ->
val propertiesFragmentModel = TorrentPropertiesFragmentViewModel.get(navController)
val torrent = propertiesFragmentModel.torrent.value
if (torrent != null) {
textField.text?.let { text ->
if (addingTrackers) {
torrent.addTrackers(text.lines().filter(String::isNotEmpty))
} else {
torrent.setTracker(args.trackerId, text.toString())
}
}
}
}
if (addingTrackers) {
return createTextFieldDialog(
requireContext(),
R.string.add_trackers,
AddTrackersDialogBinding::inflate,
R.id.text_field,
R.id.text_field_layout,
getString(R.string.trackers_announce_urls),
InputType.TYPE_TEXT_VARIATION_URI,
args.announce,
null
) {
onAccepted(it.textField)
}
}
return createTextFieldDialog(
requireContext(),
R.string.edit_tracker,
getString(R.string.tracker_announce_url),
InputType.TYPE_TEXT_VARIATION_URI,
args.announce,
null
) {
onAccepted(it.textField)
}
}
}
class RemoveTrackerDialogFragment : NavigationDialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val args = RemoveTrackerDialogFragmentArgs.fromBundle(requireArguments())
return MaterialAlertDialogBuilder(requireContext())
.setMessage(
resources.getQuantityString(
R.plurals.remove_trackers_message,
args.ids.size,
args.ids.size
)
)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(R.string.remove) { _, _ ->
val propertiesFragmentModel = TorrentPropertiesFragmentViewModel.get(navController)
val torrent = propertiesFragmentModel.torrent.value
torrent?.removeTrackers(args.ids)
requiredActivity.actionMode?.finish()
}
.create()
}
}
| gpl-3.0 | 4170dfa9ac6d30800d85933da6c3cc00 | 33.944118 | 99 | 0.600791 | 5.40291 | false | false | false | false |
mockk/mockk | modules/mockk/src/commonMain/kotlin/io/mockk/impl/recording/states/RecordingState.kt | 1 | 6206 | package io.mockk.impl.recording.states
import io.mockk.Invocation
import io.mockk.Matcher
import io.mockk.MockKException
import io.mockk.RecordedCall
import io.mockk.impl.InternalPlatform
import io.mockk.impl.log.Logger
import io.mockk.impl.recording.CallRound
import io.mockk.impl.recording.CallRoundBuilder
import io.mockk.impl.recording.CommonCallRecorder
import kotlin.math.max
import kotlin.reflect.KClass
abstract class RecordingState(recorder: CommonCallRecorder) : CallRecordingState(recorder) {
val log = recorder.safeToString(Logger<RecordingState>())
private var callRoundBuilder: CallRoundBuilder? = null
private val callRounds = mutableListOf<CallRound>()
override fun round(round: Int, total: Int) {
val builder = callRoundBuilder
if (builder != null) {
callRounds.add(builder.build())
}
callRoundBuilder = recorder.factories.callRoundBuilder()
recorder.childHinter = recorder.factories.childHinter()
if (round == total) {
signMatchers()
workaroundBoxedNumbers()
mockPermanently()
}
}
private fun signMatchers() {
val detector = recorder.factories.signatureMatcherDetector()
detector.detect(callRounds)
recorder.calls.clear()
recorder.calls.addAll(detector.calls)
}
override fun <T : Any> matcher(matcher: Matcher<*>, cls: KClass<T>): T {
val signatureValue = recorder.signatureValueGenerator.signatureValue(
cls,
recorder.anyValueGenerator,
recorder.instantiator,
)
val packRef: Any = InternalPlatform.packRef(signatureValue)
?: error("null packRef for $cls signature $signatureValue")
builder().addMatcher(matcher, packRef)
return signatureValue
}
protected fun addWasNotCalled(list: List<Any>) {
builder().addWasNotCalled(list)
}
override fun call(invocation: Invocation): Any? {
val retType = recorder.childHinter.nextChildType { invocation.method.returnType }
var isTemporaryMock = false
val temporaryMock: () -> Any = {
isTemporaryMock = true
recorder.mockFactory.temporaryMock(retType)
}
val retValue = when {
invocation.method.isToString() -> recorder.stubRepo[invocation.self]?.toStr() ?: ""
retType in CollectionTypes -> temporaryMock()
else -> recorder.anyValueGenerator()
.anyValue(retType, invocation.method.returnTypeNullable, orInstantiateVia = temporaryMock)
}
if (retValue == null) {
isTemporaryMock = false
}
builder().addSignedCall(
retValue,
isTemporaryMock,
retType,
invocation
)
return retValue
}
private fun callIsNumberUnboxing(call: RecordedCall): Boolean {
val matcher = call.matcher
return matcher.self is Number &&
matcher.method.name.endsWith("Value") &&
matcher.method.paramTypes.isEmpty()
}
private fun workaroundBoxedNumbers() {
// issue #36
if (recorder.calls.size == 1) {
return
}
val callsWithoutCasts = recorder.calls.filterNot {
callIsNumberUnboxing(it)
}
if (callsWithoutCasts.size != recorder.calls.size) {
val callsWithCasts = recorder.calls.filter {
callIsNumberUnboxing(it)
}
log.debug { "Removed ${callsWithCasts.size} unboxing calls:\n${callsWithCasts.joinToString("\n")}" }
}
recorder.calls.clear()
recorder.calls.addAll(callsWithoutCasts)
}
fun mockPermanently() {
val mocker = recorder.factories.permanentMocker()
val resultCalls = mocker.mock(recorder.calls)
recorder.calls.clear()
recorder.calls.addAll(resultCalls)
}
override fun nCalls(): Int = callRoundBuilder?.signedCalls?.size ?: 0
override fun isLastCallReturnsNothing(): Boolean {
val lastCall = callRoundBuilder?.signedCalls?.lastOrNull()
?: return false
return lastCall.method.returnsNothing
}
/**
* Main idea is to have enough random information
* to create signature for the argument.
*
* Max 40 calls looks like reasonable compromise
*/
@Suppress("DEPRECATION_ERROR")
override fun estimateCallRounds(): Int {
val regularArguments = builder().signedCalls
.flatMap { it.args }
.filterNotNull()
.map(this::typeEstimation)
.maxOfOrNull { it } ?: 1
val varargArguments = builder().signedCalls
.mapNotNull {
if (it.method.varArgsArg != -1) {
it.method.paramTypes[it.method.varArgsArg]
} else {
null
}
}.map(this::varArgTypeEstimation)
.maxOfOrNull { it } ?: 1
return max(regularArguments, varargArguments)
}
private fun typeEstimation(it: Any): Int {
return when (it::class) {
Boolean::class -> 40
Byte::class -> 8
Char::class -> 4
Short::class -> 4
Int::class -> 2
Float::class -> 2
else -> 1
}
}
private fun varArgTypeEstimation(it: KClass<*>): Int {
return when (it) {
BooleanArray::class -> 40
ByteArray::class -> 8
CharArray::class -> 4
ShortArray::class -> 4
IntArray::class -> 2
FloatArray::class -> 2
else -> 1
}
}
override fun discardLastCallRound() {
callRoundBuilder = null
}
private fun builder(): CallRoundBuilder = callRoundBuilder
?: throw MockKException("Call builder is not initialized. Bad state")
private companion object {
private val CollectionTypes = listOf(
List::class,
Map::class,
Set::class,
ArrayList::class,
HashMap::class,
HashSet::class
)
}
}
| apache-2.0 | 3b18159e1a7510a318af426f7f545c3a | 29.126214 | 112 | 0.597647 | 4.905929 | false | false | false | false |
equeim/tremotesf-android | app/src/main/kotlin/org/equeim/tremotesf/ui/RemoveTorrentDialogFragment.kt | 1 | 3430 | /*
* Copyright (C) 2017-2022 Alexey Rochev <[email protected]>
*
* This file is part of Tremotesf.
*
* Tremotesf 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.
*
* Tremotesf 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 org.equeim.tremotesf.ui
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.NavDestination
import androidx.navigation.fragment.navArgs
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import kotlinx.coroutines.launch
import org.equeim.tremotesf.R
import org.equeim.tremotesf.databinding.RemoveTorrentsDialogBinding
import org.equeim.tremotesf.rpc.GlobalRpc
class RemoveTorrentDialogFragment : NavigationDialogFragment() {
private val args: RemoveTorrentDialogFragmentArgs by navArgs()
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = MaterialAlertDialogBuilder(requireContext())
val binding = RemoveTorrentsDialogBinding.inflate(LayoutInflater.from(builder.context))
lifecycleScope.launch {
binding.deleteFilesCheckBox.isChecked = Settings.deleteFiles.get()
}
return builder
.setMessage(
if (args.torrentIds.size == 1) getString(R.string.remove_torrent_message)
else resources.getQuantityString(
R.plurals.remove_torrents_message,
args.torrentIds.size,
args.torrentIds.size
)
)
.setView(binding.root)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(R.string.remove) { _, _ ->
GlobalRpc.nativeInstance.removeTorrents(
args.torrentIds,
binding.deleteFilesCheckBox.isChecked
)
activity?.actionMode?.finish()
if (args.popBackStack) {
val id =
(parentFragmentManager.primaryNavigationFragment as NavigationFragment).destinationId
val listener = object : NavController.OnDestinationChangedListener {
override fun onDestinationChanged(
controller: NavController,
destination: NavDestination,
arguments: Bundle?
) {
if (destination.id == id) {
navController.popBackStack()
controller.removeOnDestinationChangedListener(this)
}
}
}
navController.addOnDestinationChangedListener(listener)
}
}
.create()
}
} | gpl-3.0 | 0c34f7d35ab59afe82fd290300e1a991 | 40.337349 | 109 | 0.630029 | 5.568182 | false | false | false | false |
REBOOTERS/AndroidAnimationExercise | game/src/main/java/com/bird/GameFlabbyBird.kt | 1 | 11046 | package com.bird
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.SurfaceHolder
import android.view.SurfaceView
import com.bird.internal.*
import com.bird.internal.dp
import com.engineer.android.game.R
import java.util.*
class GameFlabbyBird @JvmOverloads constructor(context: Context?, attrs: AttributeSet? = null) :
SurfaceView(context, attrs), SurfaceHolder.Callback, Runnable {
var customBg = true
private val mHolder: SurfaceHolder = holder
private var mCanvas: Canvas? = null
private var t: Thread? = null
private var isRunning = false
private val mPaint: Paint
/**
* 当前View的尺寸
*/
private var mWidth = 0
private var mHeight = 0
private val mGamePanelRect = RectF()
private var mBg: Bitmap? = null
private var mBird: Bird? = null
private var mBirdBitmap: Bitmap? = null
private var mFloor: Floor? = null
private var mFloorBg: Bitmap? = null
private var mPipeTop: Bitmap? = null
private var mPipeBottom: Bitmap? = null
private var mPipeRect: RectF? = null
private val mPipeWidth: Int
private val mPipes: MutableList<Pipe> = ArrayList()
/**
* 分数
*/
private val mNums = intArrayOf(
R.drawable.n0, R.drawable.n1,
R.drawable.n2, R.drawable.n3, R.drawable.n4, R.drawable.n5,
R.drawable.n6, R.drawable.n7, R.drawable.n8, R.drawable.n9
)
private lateinit var mNumBitmap: Array<Bitmap?>
private var mGrade = 0
private var mRemovedPipe = 0
private var mSingleGradeWidth = 0
private var mSingleGradeHeight = 0
private var mSingleNumRectF: RectF? = null
private val mSpeed = 2.dp
/**
* 记录游戏的状态
*/
private var mStatus = GameStatus.WAITTING
/**
* 将上升的距离转化为px;这里多存储一个变量,变量在run中计算
*/
private val mBirdUpDis = TOUCH_UP_SIZE.dp
private var mTmpBirdDis = 0
/**
* 鸟自动下落的距离
*/
private val mAutoDownSpeed = 2.dp
/**
* 两个管道间距离
*/
private val PIPE_DIS_BETWEEN_TWO = 200.dp
/**
* 记录移动的距离,达到 PIPE_DIS_BETWEEN_TWO 则生成一个管道
*/
private var mTmpMoveDistance = 0
/**
* 记录需要移除的管道
*/
private val mNeedRemovePipe: MutableList<Pipe> = ArrayList()
/**
* 处理一些逻辑上的计算
*/
private fun logic() {
when (mStatus) {
GameStatus.RUNNING -> {
mGrade = 0
// 更新我们地板绘制的x坐标,地板移动
mFloor!!.x = mFloor!!.x - mSpeed
logicPipe()
// 默认下落,点击时瞬间上升
mTmpBirdDis += mAutoDownSpeed
mBird!!.y = mBird!!.y + mTmpBirdDis
// 计算分数
mGrade += mRemovedPipe
for (pipe in mPipes) {
if (pipe.x + mPipeWidth < mBird!!.x) {
mGrade++
}
}
checkGameOver()
}
GameStatus.STOP -> // 如果鸟还在空中,先让它掉下来
if (mBird!!.y < mFloor!!.y - mBird!!.width) {
mTmpBirdDis += mAutoDownSpeed
mBird!!.y = mBird!!.y + mTmpBirdDis
} else {
mStatus = GameStatus.WAITTING
mGrade = 0
initPos()
}
else -> {
}
}
}
/**
* 重置鸟的位置等数据
*/
private fun initPos() {
mPipes.clear()
//立即增加一个
mPipes.add(
Pipe(
width, height, mPipeTop!!,
mPipeBottom!!
)
)
mNeedRemovePipe.clear()
// 重置鸟的位置
// mBird.setY(mHeight * 2 / 3);
mBird!!.resetHeight()
// 重置下落速度
mTmpBirdDis = 0
mTmpMoveDistance = 0
mRemovedPipe = 0
}
private fun checkGameOver() {
// 如果触碰地板,gg
if (mBird!!.y > mFloor!!.y - mBird!!.height) {
mStatus = GameStatus.STOP
}
// 如果撞到管道
for (wall in mPipes) {
// 已经穿过的
if (wall.x + mPipeWidth < mBird!!.x) {
continue
}
if (wall.touchBird(mBird!!)) {
mStatus = GameStatus.STOP
break
}
}
}
private fun logicPipe() {
// 管道移动
for (pipe in mPipes) {
if (pipe.x < -mPipeWidth) {
mNeedRemovePipe.add(pipe)
mRemovedPipe++
continue
}
pipe.x = pipe.x - mSpeed
}
// 移除管道
mPipes.removeAll(mNeedRemovePipe)
mNeedRemovePipe.clear()
// Log.e("TAG", "现存管道数量:" + mPipes.size());
// 管道
mTmpMoveDistance += mSpeed
// 生成一个管道
if (mTmpMoveDistance >= PIPE_DIS_BETWEEN_TWO) {
val pipe = Pipe(
width, height,
mPipeTop!!, mPipeBottom!!
)
mPipes.add(pipe)
mTmpMoveDistance = 0
}
}
override fun onTouchEvent(event: MotionEvent): Boolean {
val action = event.action
if (action == MotionEvent.ACTION_DOWN) {
when (mStatus) {
GameStatus.WAITTING -> mStatus = GameStatus.RUNNING
GameStatus.RUNNING -> mTmpBirdDis = mBirdUpDis
else -> {}
}
}
return true
}
/**
* 初始化图片
*/
private fun initBitmaps() {
mBg = loadImageByResId(R.drawable.bg1)
mBirdBitmap = loadImageByResId(R.drawable.bird_0)
mFloorBg = loadImageByResId(R.drawable.floor_bg2)
mPipeTop = loadImageByResId(R.drawable.g2)
mPipeBottom = loadImageByResId(R.drawable.g1)
mNumBitmap = arrayOfNulls(mNums.size)
for (i in mNumBitmap.indices) {
mNumBitmap[i] = loadImageByResId(mNums[i])
}
}
override fun surfaceCreated(holder: SurfaceHolder) {
Log.e("TAG", "surfaceCreated")
// 开启线程
isRunning = true
t = Thread(this)
t!!.start()
}
override fun surfaceChanged(
holder: SurfaceHolder, format: Int, width: Int,
height: Int
) {
Log.e("TAG", "surfaceChanged")
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
Log.e("TAG", "surfaceDestroyed")
// 通知关闭线程
isRunning = false
}
override fun run() {
while (isRunning) {
val start = System.currentTimeMillis()
logic()
draw()
val end = System.currentTimeMillis()
try {
if (end - start < 50) {
Thread.sleep(50 - (end - start))
}
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
}
private fun draw() {
try {
// 获得canvas
mCanvas = mHolder.lockCanvas()
if (mCanvas != null) {
drawBg()
drawBird()
drawPipes()
drawFloor()
drawGrades()
}
} catch (e: Exception) {
} finally {
if (mCanvas != null) mHolder.unlockCanvasAndPost(mCanvas)
}
}
private fun drawFloor() {
mFloor!!.draw(mCanvas!!, mPaint)
}
/**
* 绘制背景
*/
private fun drawBg() {
if (customBg) {
mCanvas?.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)
} else {
mCanvas!!.drawBitmap(mBg!!, null, mGamePanelRect, null)
}
}
private fun drawBird() {
mBird!!.draw(mCanvas!!)
}
/**
* 绘制管道
*/
private fun drawPipes() {
for (pipe in mPipes) {
pipe.x = pipe.x - mSpeed
pipe.draw(mCanvas!!, mPipeRect!!)
}
}
/**
* 初始化尺寸相关
*/
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
mWidth = w
mHeight = h
mGamePanelRect[0f, 0f, w.toFloat()] = h.toFloat()
// 初始化mBird
mBird = Bird(mWidth, mHeight, mBirdBitmap!!)
// 初始化地板
mFloor = Floor(mWidth, mHeight, mFloorBg)
// 初始化管道范围
mPipeRect = RectF(0f, 0f, mPipeWidth.toFloat(), mHeight.toFloat())
val pipe = Pipe(w, h, mPipeTop!!, mPipeBottom!!)
mPipes.add(pipe)
// 初始化分数
mSingleGradeHeight = (h * RADIO_SINGLE_NUM_HEIGHT).toInt()
mSingleGradeWidth = (mSingleGradeHeight * 1.0f
/ mNumBitmap[0]!!.height * mNumBitmap[0]!!.width).toInt()
mSingleNumRectF = RectF(0f, 0f, mSingleGradeWidth.toFloat(), mSingleGradeHeight.toFloat())
}
/**
* 绘制分数
*/
private fun drawGrades() {
val grade = mGrade.toString()
mCanvas!!.saveLayer(0f, 0f, mWidth.toFloat(), mHeight.toFloat(), null)
mCanvas!!.translate(
(mWidth / 2 - grade.length * mSingleGradeWidth / 2).toFloat(),
1f / 8 * mHeight
)
// draw single num one by one
for (i in grade.indices) {
val numStr = grade.substring(i, i + 1)
val num = numStr.toInt()
mCanvas!!.drawBitmap(mNumBitmap[num]!!, null, mSingleNumRectF!!, null)
mCanvas!!.translate(mSingleGradeWidth.toFloat(), 0f)
}
mCanvas!!.restore()
}
/**
* 根据resId加载图片
*
* @param resId
* @return
*/
private fun loadImageByResId(resId: Int): Bitmap {
return BitmapFactory.decodeResource(resources, resId)
}
companion object {
/**
* 管道的宽度 60dp
*/
private const val PIPE_WIDTH = 60
private const val RADIO_SINGLE_NUM_HEIGHT = 1 / 15f
/**
* 触摸上升的距离,因为是上升,所以为负值
*/
private const val TOUCH_UP_SIZE = -16
}
init {
mHolder.addCallback(this)
setZOrderOnTop(true) // 设置画布 背景透明
mHolder.setFormat(PixelFormat.TRANSLUCENT)
// 设置可获得焦点
isFocusable = true
isFocusableInTouchMode = true
// 设置常亮
this.keepScreenOn = true
mPaint = Paint()
mPaint.isAntiAlias = true
mPaint.isDither = true
initBitmaps()
// 初始化速度
mPipeWidth = PIPE_WIDTH.dp
}
} | apache-2.0 | 84ea6c0003bd1dd55d984cca1c1872ad | 24.594595 | 98 | 0.519585 | 4.304132 | false | false | false | false |
Nunnery/MythicDrops | src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/items/strategies/AbstractDropStrategy.kt | 1 | 3654 | /*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2020 Richard Harrah
*
* 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.tealcube.minecraft.bukkit.mythicdrops.items.strategies
import com.tealcube.minecraft.bukkit.mythicdrops.api.items.strategies.DropStrategy
import com.tealcube.minecraft.bukkit.mythicdrops.api.settings.config.DropsOptions
import com.tealcube.minecraft.bukkit.mythicdrops.worldguard.WorldGuardFlags
import com.tealcube.minecraft.spigot.worldguard.adapters.lib.WorldGuardAdapters
import org.bukkit.Location
abstract class AbstractDropStrategy : DropStrategy {
protected fun getDropChances(dropsOptions: DropsOptions): StrategyDropChances {
val tieredItemChance = dropsOptions.tieredItemChance
val customItemChance = dropsOptions.customItemChance
val socketGemChance = dropsOptions.socketGemChance
val unidentifiedItemChance =
dropsOptions.unidentifiedItemChance
val identityTomeChance = dropsOptions.identityTomeChance
val socketExtenderChance = dropsOptions.socketExtenderChance
return StrategyDropChances(
tieredItemChance,
customItemChance,
socketGemChance,
unidentifiedItemChance,
identityTomeChance,
socketExtenderChance
)
}
protected fun getWorldGuardFlags(location: Location): StrategyWorldGuardFlags {
val tieredAllowedAtLocation =
WorldGuardAdapters.isFlagAllowAtLocation(location, WorldGuardFlags.mythicDropsTiered)
val customItemAllowedAtLocation =
WorldGuardAdapters.isFlagAllowAtLocation(location, WorldGuardFlags.mythicDropsCustom)
val socketGemAllowedAtLocation =
WorldGuardAdapters.isFlagAllowAtLocation(location, WorldGuardFlags.mythicDropsSocketGem)
val unidentifiedItemAllowedAtLocation =
WorldGuardAdapters.isFlagAllowAtLocation(location, WorldGuardFlags.mythicDropsUnidentifiedItem)
val identityTomeAllowedAtLocation =
WorldGuardAdapters.isFlagAllowAtLocation(location, WorldGuardFlags.mythicDropsIdentityTome)
val socketExtendersAllowedAtLocation =
WorldGuardAdapters.isFlagAllowAtLocation(location, WorldGuardFlags.mythicDropsSocketExtender)
return StrategyWorldGuardFlags(
tieredAllowedAtLocation,
customItemAllowedAtLocation,
socketGemAllowedAtLocation,
unidentifiedItemAllowedAtLocation,
identityTomeAllowedAtLocation,
socketExtendersAllowedAtLocation
)
}
}
| mit | 6dc961d62b5d1f4187a02b10570a37b7 | 49.054795 | 107 | 0.760536 | 5.553191 | false | false | false | false |
jk1/youtrack-idea-plugin | src/main/kotlin/com/github/jk1/ytplugin/ui/YouTrackPluginIcons.kt | 1 | 1138 | package com.github.jk1.ytplugin.ui
import com.intellij.openapi.util.IconLoader
object YouTrackPluginIcons {
val YOUTRACK = IconLoader.getIcon("/icons/youtrack_16.png", YouTrackPluginIcons::class.java) // 16x16
val YOUTRACK_TOOL_WINDOW = IconLoader.getIcon("/icons/youTrack.svg", YouTrackPluginIcons::class.java) // 13x13
val YOUTRACK_ISSUE_MARKER = IconLoader.getIcon("/icons/speedSearchPrompt.png", YouTrackPluginIcons::class.java) // 13x13
val YOUTRACK_MANUAL_ADD_TIME_TRACKER = IconLoader.getIcon("/icons/add_workitem_manually.png", YouTrackPluginIcons::class.java) // 16x16
val YOUTRACK_PAUSE_TIME_TRACKER = IconLoader.getIcon("/icons/time_tracker_pause.png", YouTrackPluginIcons::class.java) // 16x16
val YOUTRACK_STOP_TIME_TRACKER = IconLoader.getIcon("/icons/time_tracker_stop.png", YouTrackPluginIcons::class.java) // 16x16
val YOUTRACK_POST_FROM_TIME_TRACKER = IconLoader.getIcon("/icons/time_tracker_post.png", YouTrackPluginIcons::class.java) // 16x16
val YOUTRACK_RESET_TIME_TRACKER = IconLoader.getIcon("/icons/time_tracker_reset.png", YouTrackPluginIcons::class.java) // 16x16
}
| apache-2.0 | 58f7b065a74ee58da7b40a0760d8e31e | 65.941176 | 140 | 0.761863 | 3.80602 | false | false | false | false |
Undin/intellij-rust | profiler/src/main/kotlin/org/rust/profiler/dtrace/RsDTraceProfilerProcess.kt | 2 | 4165 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.profiler.dtrace
import com.intellij.openapi.progress.PerformInBackgroundOption
import com.intellij.openapi.project.Project
import com.intellij.profiler.DummyCallTreeBuilder
import com.intellij.profiler.api.*
import com.intellij.profiler.clion.dtrace.DTraceProfilerSettings
import com.intellij.profiler.dtrace.DTraceProfilerProcessBase
import com.intellij.profiler.dtrace.FullDumpParser
import com.intellij.profiler.dtrace.SimpleProfilerSettingsState
import com.intellij.profiler.dtrace.cpuProfilerScript
import com.intellij.profiler.model.NativeCall
import com.intellij.profiler.model.NativeThread
import com.intellij.profiler.sudo.SudoProcessHandler
import com.intellij.profiler.ui.NativeCallStackElementRenderer
import com.intellij.util.xmlb.XmlSerializer
import org.jetbrains.concurrency.Promise
import org.rust.lang.utils.RsDemangler
import org.rust.profiler.RsCachingStackElementReader
@Suppress("UnstableApiUsage")
class RsDTraceProfilerProcess private constructor(
project: Project,
targetProcess: AttachableTargetProcess,
attachedTimestamp: Long,
dtraceProcessHandler: SudoProcessHandler
) : DTraceProfilerProcessBase(project, targetProcess, attachedTimestamp, dtraceProcessHandler) {
// We can't use [com.intellij.profiler.clion.ProfilerUtilsKt.CPP_PROFILER_HELP_TOPIC] directly
// because it has `internal` modifier
override val helpId: String = "procedures.profiler"
override fun createDumpParser(): FullDumpParser<BaseCallStackElement> {
val cachingStackElementReader = RsCachingStackElementReader.getInstance(project)
return FullDumpParser(
{ NativeThread(it, "thread with id $it") },
cachingStackElementReader::parseStackElement
)
}
override fun createDumpWriter(data: NewCallTreeOnlyProfilerData): ProfilerDumpWriter =
CollapsedProfilerDumpWriter(data.builder, targetProcess.fullName, attachedTimestamp, { it.fullName() }, { it.name })
override fun createProfilerData(builder: DummyCallTreeBuilder<BaseCallStackElement>): NewCallTreeOnlyProfilerData =
NewCallTreeOnlyProfilerData(builder, NativeCallStackElementRenderer.INSTANCE)
override fun postProcessData(builder: DummyCallTreeBuilder<BaseCallStackElement>): DummyCallTreeBuilder<BaseCallStackElement> {
builder.mapTreeElements {
if (it !is RsDTraceNavigatableNativeCall) return@mapTreeElements it
val library = it.fullName().substringBeforeLast('`')
val fullName = it.fullName().substringAfterLast('`')
val demangledName = RsDemangler.tryDemangle(fullName)?.format(skipHash = true) ?: return@mapTreeElements it
val path = demangledName.substringBeforeLast("::")
val method = demangledName.substringAfterLast("::")
val nativeCall = NativeCall(library, path, method)
RsDTraceNavigatableNativeCall(nativeCall)
}
return super.postProcessData(builder)
}
companion object {
fun attach(
targetProcess: AttachableTargetProcess,
backgroundOption: PerformInBackgroundOption,
timeoutInMilliseconds: Int,
project: Project
): Promise<RsDTraceProfilerProcess> {
val settings = DTraceProfilerSettings.instance.state
// WARNING: Do not use such solution for other needs!
// We want to always use -xmangled option because DTrace cannot demangle Rust symbols correctly
val element = XmlSerializer.serialize(settings)
val settingsCopy = XmlSerializer.deserialize(element, SimpleProfilerSettingsState::class.java)
settingsCopy.defaultCmdArgs.add("-xmangled")
return attachBase(
targetProcess,
backgroundOption,
settingsCopy.cpuProfilerScript(),
timeoutInMilliseconds,
project
) { handler, _ -> RsDTraceProfilerProcess(project, targetProcess, System.currentTimeMillis(), handler) }
}
}
}
| mit | e3dfe3f8dbaba7f2b86f09dac3e89188 | 44.769231 | 131 | 0.737575 | 5.012034 | false | false | false | false |
michael71/LanbahnPanel | app/src/main/java/de/blankedv/lanbahnpanel/model/LanbahnSXPair.kt | 1 | 2360 | package de.blankedv.lanbahnpanel.model
/**
* is used for mapping of lanbahn addresses to SX addresses
*
* NEEDED for "SX Style" panels with selectrix addresses in xml-config
*
* @author mblank
*/
class LanbahnSXPair {
var lbAddr: Int = 0 // lanbahn address
var sxAddr: Int = 0 // sx Address
var sxBit: Int = 0 // (first) sx bit (1..8) (== lowest bit value
// example sxBit = 5, nBit=2
// bit5=1 ==> value = 1
// bit6=1 ==> value = 2
// bit5 and bit6 =set => Value = 3
var nBit: Int = 0 // number of bits used 1 ...4
val isValid: Boolean
get() = if (lbAddr != INVALID_INT &&
sxAddr != INVALID_INT &&
sxBit >= 1 &&
sxBit <= 8) {
true
} else {
false
}
internal constructor() {
lbAddr = INVALID_INT
sxAddr = INVALID_INT
sxBit = 1
nBit = 1
}
internal constructor(l: Int, s: Int, b: Int, n: Int) {
lbAddr = l
sxAddr = s
sxBit = b
nBit = n
}
internal constructor(l: Int, s: Int, b: Int) {
lbAddr = l
if ((l == INVALID_INT) and (s != INVALID_INT) and (b != INVALID_INT)) {
// only sx address given, but lanbahn can be calculated out of sxadr and sxbit
lbAddr = s * 10 + b // s=98, b=7 ==> l=987
}
sxAddr = s
sxBit = b
nBit = 1
}
/**
* calculate lanbahn value from the SX data byte
* use only relevant bits sxBit ... sxBit+(nBit-1)
* @param d
* @return
*/
/* fun getLBValueFromSXByte(d: Int): Int {
var v = 0
for (i in sxBit until sxBit + nBit) {
if (SXUtils.isSet(d, i) !== 0) {
v = v + (1 shl i - sxBit)
}
}
//if (sxAddr == 70) {
//System.out.println("lbaddr="+lbAddr+ " sxaddr="+sxAddr+ " sxBit="+sxBit+" nBit="+nBit+" v="+v);
//}
return v
} */
override fun toString(): String {
val sb = StringBuilder()
sb.append("lbAddr=")
sb.append(lbAddr)
sb.append(" sxAddr=")
sb.append(sxAddr)
for (i in nBit downTo 1) {
sb.append(" bit=")
sb.append(sxBit + (i - 1))
}
return sb.toString()
}
} | gpl-3.0 | e7aab1cc705fb42afa1670002aae45f5 | 25.52809 | 108 | 0.477966 | 3.734177 | false | false | false | false |
yzbzz/beautifullife | app/src/main/java/com/ddu/ui/fragment/study/ui/ShapeAdvancedFragment.kt | 2 | 2490 | package com.ddu.ui.fragment.study.ui
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.TextView
import com.ddu.R
import com.ddu.icore.ui.fragment.DefaultFragment
import com.ddu.icore.ui.help.ShapeInjectHelper
import com.iannotation.IElement
import kotlinx.android.synthetic.main.fragment_ui_shape_advanced.*
/**
* Created by yzbzz on 16/4/14.
*/
@IElement("UI")
class ShapeAdvancedFragment : DefaultFragment() {
override fun getLayoutId(): Int {
return R.layout.fragment_ui_shape_advanced
}
override fun initView() {
btn_start.setOnClickListener {
ll_items.removeAllViews()
val count = Integer.parseInt(et_count.text.toString())
val resId = R.layout.fragment_ui_common_textview
for (i in 0 until count) {
val linearLayout = layoutInflater.inflate(resId, null) as TextView
val shapeInjectHelper = ShapeInjectHelper(linearLayout)
if (i == 0) {
shapeInjectHelper.shapeType(ShapeInjectHelper.SEGMENT)
shapeInjectHelper.shapeDirection(ShapeInjectHelper.DIRECTION_TOP)
shapeInjectHelper.radius(5f)
}
if (i == count - 1) {
shapeInjectHelper.shapeType(ShapeInjectHelper.SEGMENT)
shapeInjectHelper.shapeDirection(ShapeInjectHelper.DIRECTION_BOTTOM)
shapeInjectHelper.radius(5f)
}
shapeInjectHelper.setBackground()
linearLayout.setOnClickListener(object : View.OnClickListener {
var isCheck = true
override fun onClick(v: View) {
if (isCheck) {
linearLayout.setBackgroundColor(Color.RED)
} else {
linearLayout.setBackgroundColor(Color.WHITE)
}
isCheck = !isCheck
}
})
ll_items.addView(linearLayout)
}
}
}
companion object {
fun newInstance(taskId: String): ShapeAdvancedFragment {
val arguments = Bundle()
arguments.putString(DefaultFragment.ARGUMENT_TASK_ID, taskId)
val fragment = ShapeAdvancedFragment()
fragment.arguments = arguments
return fragment
}
}
}
| apache-2.0 | e72bca934c5d62ac4c802304f72a6210 | 33.583333 | 88 | 0.581928 | 5.366379 | false | false | false | false |
klazuka/intellij-elm | src/main/kotlin/org/elm/ide/inspections/import/AddImportFix.kt | 1 | 8416 | package org.elm.ide.inspections.import
import com.intellij.codeInsight.intention.PriorityAction.Priority
import com.intellij.codeInsight.navigation.NavigationUtil
import com.intellij.ide.DataManager
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.psi.PsiElement
import com.intellij.ui.ColoredListCellRenderer
import com.intellij.ui.SimpleTextAttributes
import com.intellij.util.text.EditDistance
import org.elm.ide.inspections.NamedQuickFix
import org.elm.lang.core.imports.ImportAdder.Import
import org.elm.lang.core.imports.ImportAdder.addImport
import org.elm.lang.core.lookup.ElmLookup
import org.elm.lang.core.psi.ElmExposableTag
import org.elm.lang.core.psi.ElmFile
import org.elm.lang.core.psi.ElmPsiElement
import org.elm.lang.core.psi.elements.*
import org.elm.lang.core.psi.parentOfType
import org.elm.lang.core.resolve.ElmReferenceElement
import org.elm.lang.core.resolve.reference.ElmReference
import org.elm.lang.core.resolve.reference.QualifiedReference
import org.elm.openapiext.isUnitTestMode
import org.elm.openapiext.runWriteCommandAction
import org.jetbrains.annotations.TestOnly
import javax.swing.JList
interface ImportPickerUI {
fun choose(candidates: List<Import>, callback: (Import) -> Unit)
}
private var MOCK: ImportPickerUI? = null
@TestOnly
fun withMockImportPickerUI(mockUi: ImportPickerUI, action: () -> Unit) {
MOCK = mockUi
try {
action()
} finally {
MOCK = null
}
}
class AddImportFix : NamedQuickFix("Import", Priority.HIGH) {
data class Context(
val refName: String,
val candidates: List<Import>,
val isQualified: Boolean
)
companion object {
fun findApplicableContext(psiElement: PsiElement): Context? {
val element = psiElement as? ElmPsiElement ?: return null
if (element.parentOfType<ElmImportClause>() != null) return null
val refElement = element.parentOfType<ElmReferenceElement>(strict = false) ?: return null
val ref = refElement.reference
// we can't import the function we're annotating
if (refElement is ElmTypeAnnotation) return null
val typeAllowed = element is ElmTypeRef
val name = refElement.referenceName
val candidates = ElmLookup.findByName<ElmExposableTag>(name, refElement.elmFile)
.filter {
val isType = it is ElmTypeDeclaration || it is ElmTypeAliasDeclaration
typeAllowed == isType
}
.mapNotNull { fromExposableElement(it, ref) }
.sortedWith(referenceComparator(ref))
if (candidates.isEmpty())
return null
return Context(name, candidates, ref is QualifiedReference)
}
private fun referenceComparator(ref: ElmReference): Comparator<Import> {
val qualifier = (ref as? QualifiedReference)?.qualifierPrefix
val comparator = compareBy<Import, String?>(nullsFirst()) { it.moduleAlias }
return when {
// With no qualifier, just sort lexicographically
qualifier.isNullOrBlank() -> comparator.thenBy { it.moduleName }
else -> comparator
// Sort by modules containing the qualifier exactly
.thenByDescending { qualifier in it.moduleName }
// Next sort by the case-insensitive edit distance
.thenBy { EditDistance.levenshtein(qualifier, it.moduleName, /*caseSensitive=*/false) }
// Finally sort by case-sensitive edit distance, so exact case matches sort higher
.thenBy { EditDistance.levenshtein(qualifier, it.moduleName, /*caseSensitive=*/true) }
}
}
}
override fun applyFix(element: PsiElement, project: Project) {
if (element !is ElmPsiElement) return
val file = element.elmFile
val context = findApplicableContext(element) ?: return
when (context.candidates.size) {
0 -> error("should not happen: must be at least one candidate")
1 -> {
val candidate = context.candidates.first()
// Normally we would just directly perform the import here without prompting,
// but if it's an alias-based import, we should show the user some UI so that
// they know what they're getting into. See https://github.com/klazuka/intellij-elm/issues/309
when {
candidate.moduleAlias != null -> promptToSelectCandidate(project, context, file)
else -> project.runWriteCommandAction {
addImport(candidate, file, context.isQualified)
}
}
}
else -> promptToSelectCandidate(project, context, file)
}
}
private fun promptToSelectCandidate(project: Project, context: Context, file: ElmFile) {
require(context.candidates.isNotEmpty())
DataManager.getInstance().dataContextFromFocusAsync.onSuccess { dataContext ->
val picker = if (isUnitTestMode) {
MOCK ?: error("You must set mock UI via `withMockImportPickerUI`")
} else {
RealImportPickerUI(dataContext, context.refName, project)
}
picker.choose(context.candidates) { candidate ->
project.runWriteCommandAction {
addImport(candidate, file, context.isQualified)
}
}
}
}
}
private class RealImportPickerUI(
private val dataContext: DataContext,
private val refName: String,
private val project: Project
) : ImportPickerUI {
override fun choose(candidates: List<Import>, callback: (Import) -> Unit) {
val popup = JBPopupFactory.getInstance().createPopupChooserBuilder(candidates)
.setTitle("Import '$refName' from module:")
.setItemChosenCallback { callback(it) }
.setNamerForFiltering { it.moduleName }
.setRenderer(CandidateRenderer())
.createPopup()
NavigationUtil.hidePopupIfDumbModeStarts(popup, project)
popup.showInBestPositionFor(dataContext)
}
}
private class CandidateRenderer : ColoredListCellRenderer<Import>() {
override fun customizeCellRenderer(list: JList<out Import>, value: Import, index: Int, selected: Boolean, hasFocus: Boolean) {
// TODO set the background color based on project vs tests vs library
append(value.moduleName)
if (value.moduleAlias != null) {
val attr = when {
selected -> SimpleTextAttributes.REGULAR_ATTRIBUTES
else -> SimpleTextAttributes.GRAYED_ATTRIBUTES
}
append(" as ${value.moduleAlias}", attr)
}
}
}
/**
* Returns a candidate if the element is exposed by its containing module
*/
private fun fromExposableElement(element: ElmExposableTag, ref: ElmReference): Import? {
val moduleDecl = element.elmFile.getModuleDecl() ?: return null
val exposingList = moduleDecl.exposingList ?: return null
if (!exposingList.exposes(element))
return null
val nameToBeExposed = when (element) {
is ElmUnionVariant -> {
val typeName = element.parentOfType<ElmTypeDeclaration>()!!.name
"$typeName(..)"
}
is ElmInfixDeclaration ->
"(${element.name})"
else ->
element.name
}
val alias = inferModuleAlias(ref, moduleDecl)
if (alias != null && alias.contains('.')) {
// invalid candidate because the alias would violate Elm syntax
return null
}
return Import(
moduleName = moduleDecl.name,
moduleAlias = alias,
nameToBeExposed = nameToBeExposed
)
}
/**
* Attempt to infer an alias to be used when importing this module.
*/
private fun inferModuleAlias(ref: ElmReference, moduleDecl: ElmModuleDeclaration): String? =
if (ref is QualifiedReference && ref.qualifierPrefix != moduleDecl.name)
ref.qualifierPrefix
else
null
| mit | 5ea369d1294bafed1505278f520c7c7a | 38.886256 | 130 | 0.643298 | 5.036505 | false | false | false | false |
klazuka/intellij-elm | src/main/kotlin/org/elm/ide/components/ElmFormatOnFileSaveComponent.kt | 1 | 2344 | package org.elm.ide.components
import com.intellij.AppTopics
import com.intellij.notification.NotificationType
import com.intellij.openapi.editor.Document
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileDocumentManagerListener
import com.intellij.openapi.project.Project
import org.elm.ide.notifications.showBalloon
import org.elm.lang.core.psi.isElmFile
import org.elm.workspace.commandLineTools.ElmFormatCLI
import org.elm.workspace.commandLineTools.ElmFormatCLI.ElmFormatResult
import org.elm.workspace.elmSettings
import org.elm.workspace.elmToolchain
import org.elm.workspace.elmWorkspace
class ElmFormatOnFileSaveComponent(val project: Project) {
init {
with(project.messageBus.connect()) {
subscribe(
AppTopics.FILE_DOCUMENT_SYNC,
object : FileDocumentManagerListener {
override fun beforeDocumentSaving(document: Document) {
if (!project.elmSettings.toolchain.isElmFormatOnSaveEnabled) return
val vFile = FileDocumentManager.getInstance().getFile(document) ?: return
if (!vFile.isElmFile) return
val elmVersion = ElmFormatCLI.getElmVersion(project, vFile) ?: return
val elmFormat = project.elmToolchain.elmFormatCLI ?: return
val result = elmFormat.formatDocumentAndSetText(project, document, elmVersion, addToUndoStack = false)
when (result) {
is ElmFormatResult.BadSyntax ->
project.showBalloon(result.msg, NotificationType.WARNING)
is ElmFormatResult.FailedToStart ->
project.showBalloon(result.msg, NotificationType.ERROR,
"Configure" to { project.elmWorkspace.showConfigureToolchainUI() }
)
is ElmFormatResult.UnknownFailure ->
project.showBalloon(result.msg, NotificationType.ERROR)
is ElmFormatResult.Success ->
return
}
}
}
)
}
}
} | mit | 11d32393395ee63bc77ecc965630318e | 44.096154 | 126 | 0.607082 | 5.567696 | false | false | false | false |
codebutler/odyssey | retrograde-app-tv/src/main/java/com/codebutler/retrograde/app/feature/onboarding/OnboardingFragment.kt | 1 | 1899 | /*
* OnboardingFragment.kt
*
* Copyright (C) 2017 Retrograde Project
*
* 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.codebutler.retrograde.app.feature.onboarding
import androidx.leanback.app.OnboardingSupportFragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.codebutler.retrograde.R
class OnboardingFragment : OnboardingSupportFragment() {
override fun getPageTitle(pageIndex: Int): String = getString(R.string.onboarding_title)
override fun getPageDescription(pageIndex: Int): String = getString(R.string.onboarding_description)
override fun onCreateForegroundView(inflater: LayoutInflater, container: ViewGroup): View? = null
override fun onCreateBackgroundView(inflater: LayoutInflater, container: ViewGroup): View {
val bgView = View(activity)
bgView.setBackgroundColor(resources.getColor(R.color.colorPrimaryLight, activity!!.theme))
return bgView
}
override fun getPageCount() = 1
override fun onCreateContentView(inflater: LayoutInflater, container: ViewGroup): View = View(activity)
override fun onFinishFragment() {
(activity as Listener).onOnboardingComplete()
}
interface Listener {
fun onOnboardingComplete()
}
}
| gpl-3.0 | a771347349e3d2bbead281060a69ddcc | 34.830189 | 107 | 0.754081 | 4.620438 | false | false | false | false |
veyndan/reddit-client | app/src/main/java/com/veyndan/paper/reddit/post/Flair.kt | 2 | 1771 | package com.veyndan.paper.reddit.post
import android.content.Context
import android.graphics.drawable.Drawable
import android.support.annotation.ColorInt
import android.support.v4.content.ContextCompat
import com.veyndan.paper.reddit.R
sealed class Flair(@ColorInt val backgroundColor: Int, val text: String?,
val icon: Drawable? = null, val searchQuery: String? = null) {
init {
check(backgroundColor != 0) { "backgroundColor must be set" }
}
fun searchable(): Boolean {
return searchQuery != null
}
data class Stickied(val context: Context) : Flair(
ContextCompat.getColor(context, R.color.post_flair_locked),
context.getString(R.string.post_locked),
ContextCompat.getDrawable(context, R.drawable.ic_lock_outline_white_12sp))
data class Locked(val context: Context) : Flair(
ContextCompat.getColor(context, R.color.post_flair_locked),
context.getString(R.string.post_locked),
ContextCompat.getDrawable(context, R.drawable.ic_lock_outline_white_12sp))
data class Nsfw(val context: Context) : Flair(
ContextCompat.getColor(context, R.color.post_flair_nsfw),
context.getString(R.string.post_nsfw),
searchQuery = "nsfw:yes")
data class Link(val context: Context, val text1: String?) : Flair(
ContextCompat.getColor(context, R.color.post_flair_link),
text1,
searchQuery = "flair:'$text1'")
data class Gilded(val context: Context, val gildedCount: Int) : Flair(
ContextCompat.getColor(context, R.color.post_flair_gilded),
gildedCount.toString(),
ContextCompat.getDrawable(context, R.drawable.ic_star_white_12sp))
}
| mit | a46e147c41b05f6c06c70e0737752fc3 | 39.25 | 86 | 0.671372 | 4.128205 | false | false | false | false |
EventFahrplan/EventFahrplan | app/src/test/java/nerd/tuxmobil/fahrplan/congress/schedule/ScrollAmountCalculatorTest.kt | 1 | 5106 | package nerd.tuxmobil.fahrplan.congress.schedule
import com.google.common.truth.Truth.assertThat
import info.metadude.android.eventfahrplan.commons.temporal.Moment
import nerd.tuxmobil.fahrplan.congress.NoLogging
import nerd.tuxmobil.fahrplan.congress.dataconverters.toStartsAtMoment
import nerd.tuxmobil.fahrplan.congress.models.DateInfo
import nerd.tuxmobil.fahrplan.congress.models.DateInfos
import nerd.tuxmobil.fahrplan.congress.models.RoomData
import nerd.tuxmobil.fahrplan.congress.models.ScheduleData
import nerd.tuxmobil.fahrplan.congress.models.Session
import org.junit.Test
import org.threeten.bp.ZoneOffset
class ScrollAmountCalculatorTest {
private companion object {
const val BOX_HEIGHT = 34 // Pixel 2 portrait mode
const val COLUMN_INDEX = 0
}
@Test
fun `calculateScrollAmount returns 0 if room index preceeds the valid column indices`() {
val session = createFirstSession()
val scrollAmount = calculateScrollAmount(
session = session,
nowMoment = session.toStartsAtMoment(),
currentDayIndex = session.day,
columnIndex = -1
)
assertThat(scrollAmount).isEqualTo(0)
}
@Test
fun `calculateScrollAmount returns 0 if room index exceeds the valid column indices`() {
val session = createFirstSession()
val scrollAmount = calculateScrollAmount(
session = session,
nowMoment = session.toStartsAtMoment(),
currentDayIndex = session.day,
columnIndex = COLUMN_INDEX + 1
)
assertThat(scrollAmount).isEqualTo(0)
}
@Test
fun `calculateScrollAmount returns 0 if conference has not started but it will today`() {
val session = createFirstSession()
val scrollAmount = calculateScrollAmount(
session = session,
nowMoment = session.toStartsAtMoment().minusMinutes(1),
currentDayIndex = session.day
)
assertThat(scrollAmount).isEqualTo(0)
}
@Test
fun `calculateScrollAmount returns 0 if conference starts now`() {
val session = createFirstSession()
val scrollAmount = calculateScrollAmount(
session = session,
nowMoment = session.toStartsAtMoment(),
currentDayIndex = session.day
)
assertThat(scrollAmount).isEqualTo(0)
}
@Test
fun `calculateScrollAmount returns 0 if first session is almost done`() {
val session = createFirstSession()
val scrollAmount = calculateScrollAmount(
session = session,
nowMoment = Moment.ofEpochMilli(session.endsAtDateUtc).minusMinutes(1),
currentDayIndex = session.day
)
assertThat(scrollAmount).isEqualTo(0)
}
@Test
fun `calculateScrollAmount returns end of session if first session is done`() {
val session = createFirstSession()
val scrollAmount = calculateScrollAmount(
session = session,
nowMoment = Moment.ofEpochMilli(session.endsAtDateUtc),
currentDayIndex = session.day
)
assertThat(scrollAmount).isEqualTo(408)
}
@Test
fun `calculateScrollAmount returns 408 for a session crossing the intra-day limit`() {
val session = createLateSession()
val scrollAmount = calculateScrollAmount(
session = session,
nowMoment = Moment.ofEpochMilli(session.endsAtDateUtc),
currentDayIndex = session.day
)
assertThat(scrollAmount).isEqualTo(408)
}
private fun calculateScrollAmount(
session: Session,
nowMoment: Moment,
currentDayIndex: Int,
columnIndex: Int = COLUMN_INDEX
): Int {
val sessions = listOf(session)
val roomData = RoomData(roomName = session.room, sessions = sessions)
val scheduleData = ScheduleData(dayIndex = session.day, roomDataList = listOf(roomData))
val conference = Conference.ofSessions(sessions)
val dateInfo = DateInfo(dayIndex = session.day, date = Moment.parseDate(session.date))
val dateInfos = DateInfos().apply { add(dateInfo) }
return ScrollAmountCalculator(NoLogging).calculateScrollAmount(conference, dateInfos, scheduleData, nowMoment, currentDayIndex, BOX_HEIGHT, columnIndex)
}
private fun createFirstSession() = createBaseSession("s1",
Moment.ofEpochMilli(1582963200000L) // February 29, 2020 08:00:00 AM GMT
)
private fun createLateSession() = createBaseSession("s2",
Moment.ofEpochMilli(1583019000000L) // February 29, 2020 11:30:00 PM GMT
)
private fun createBaseSession(sessionId: String, moment: Moment) = Session(sessionId).apply {
day = 0
date = moment.toZonedDateTime(ZoneOffset.UTC).toLocalDate().toString()
dateUTC = moment.toMilliseconds()
startTime = moment.minuteOfDay
duration = 60
room = "Main hall"
}
}
| apache-2.0 | b26cc53ede4e2798981fbeb9e8d57cf3 | 37.390977 | 160 | 0.659029 | 5.285714 | false | true | false | false |
Notifique/Notifique | notifique/src/main/java/com/nathanrassi/notifique/NotifiqueApplication.kt | 1 | 1358 | package com.nathanrassi.notifique
import android.app.Application
import dagger.android.DispatchingAndroidInjector
import dagger.android.HasAndroidInjector
import javax.inject.Inject
class NotifiqueApplication : Application(), HasAndroidInjector {
@Inject internal lateinit var androidInjector: DispatchingAndroidInjector<Any>
@Inject internal lateinit var crashReporter: CrashReporter
override fun onCreate() {
if (BuildConfig.FLAVOR == "internal") {
// TODO: Android R seems to have issues here.
/*StrictMode.setThreadPolicy(
ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.penaltyDeath()
.build()
)*/
/*StrictMode.setVmPolicy(
VmPolicy.Builder()
.detectAll()
.penaltyLog()
.penaltyDeath()
.build()
)*/
}
createAppComponent()
.inject(this)
val defaultHandler = Thread.getDefaultUncaughtExceptionHandler()!!
Thread.setDefaultUncaughtExceptionHandler { thread, e ->
var cause: Throwable = e
var forward = cause.cause
while (forward != null) {
cause = forward
forward = forward.cause
}
crashReporter.report(cause)
defaultHandler.uncaughtException(thread, e)
}
super.onCreate()
}
override fun androidInjector() = androidInjector
}
| apache-2.0 | 73ecd9b09d810f44c871193b3307bd92 | 27.291667 | 80 | 0.662739 | 5.183206 | false | false | false | false |
takke/DataStats | app/src/main/java/jp/takke/datastats/BootReceiver.kt | 1 | 1152 | package jp.takke.datastats
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.preference.PreferenceManager
import jp.takke.util.MyLog
class BootReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
MyLog.i("BootReceiver.onReceive")
if (Intent.ACTION_BOOT_COMPLETED == intent.action) {
// 端末起動時の処理
// 自動起動の確認
val pref = PreferenceManager.getDefaultSharedPreferences(context)
val startOnBoot = pref.getBoolean(C.PREF_KEY_START_ON_BOOT, true)
MyLog.i("start on boot[" + (if (startOnBoot) "YES" else "NO") + "]")
if (startOnBoot) {
// サービス起動
val serviceIntent = Intent(context, LayerService::class.java)
if (Build.VERSION.SDK_INT >= 26) {
context.startForegroundService(serviceIntent)
} else {
context.startService(serviceIntent)
}
}
}
}
}
| apache-2.0 | fe0f920b813bee0666c494e5b8371a21 | 29 | 80 | 0.607207 | 4.530612 | false | false | false | false |
Gnar-Team/Gnar-bot | src/main/kotlin/xyz/gnarbot/gnar/commands/settings/IgnoreCommand.kt | 1 | 4476 | package xyz.gnarbot.gnar.commands.settings
import net.dv8tion.jda.api.Permission
import net.dv8tion.jda.api.entities.IMentionable
import net.dv8tion.jda.api.entities.Member
import net.dv8tion.jda.api.entities.Role
import net.dv8tion.jda.api.entities.TextChannel
import xyz.gnarbot.gnar.commands.BotInfo
import xyz.gnarbot.gnar.commands.Category
import xyz.gnarbot.gnar.commands.Command
import xyz.gnarbot.gnar.commands.Context
import xyz.gnarbot.gnar.commands.template.CommandTemplate
import xyz.gnarbot.gnar.commands.template.annotations.Description
@Command(
aliases = ["ignore"],
usage = "(user|channel|role|list) [?entity]",
description = "Make the bot ignore certain users, channels or roles."
)
@BotInfo(
id = 53,
category = Category.SETTINGS,
permissions = [Permission.MANAGE_SERVER]
)
class IgnoreCommand : CommandTemplate() {
@Description("Ignore/unignore users.")
fun user(context: Context, member: Member) {
if (!context.member.canInteract(member)) {
context.send().error("You can not interact with this user.").queue()
return
}
context.data.ignored.users.let {
if (it.contains(member.user.id)) {
it.remove(member.user.id)
context.send().info("No longer ignoring user ${member.asMention}.").queue()
} else {
it.add(member.user.id)
context.send().info("Ignored user ${member.asMention}.").queue()
}
}
context.data.save()
}
@Description("Ignore/unignore a channel.")
fun channel(context: Context, channel: TextChannel) {
context.data.ignored.channels.let {
if (it.contains(channel.id)) {
it.remove(channel.id)
context.send().info("No longer ignoring channel ${channel.asMention}.").queue()
} else {
it.add(channel.id)
context.send().info("Ignored channel ${channel.asMention}.").queue()
}
}
context.data.save()
}
@Description("Ignore/unignore a role.")
fun role(context: Context, role: Role) {
if (role == context.guild.publicRole) {
context.send().error("You can't ignore the public role!").queue()
return
}
context.data.ignored.roles.let {
if (it.contains(role.id)) {
it.remove(role.id)
context.send().info("No longer ignoring role ${role.asMention}.").queue()
} else {
it.add(role.id)
context.send().info("Ignored role ${role.asMention}.").queue()
}
}
context.data.save()
}
@Description("List ignored entities.")
fun list(context: Context) {
context.send().embed("Ignored Entities") {
field("Users") {
buildString {
context.data.ignored.users.let {
if (it.isEmpty()) {
append("None of the users are ignored.")
}
it.mapNotNull(context.guild::getMemberById)
.map(IMentionable::getAsMention)
.forEach { append("• ").append(it).append('\n') }
}
}
}
field("Channel") {
buildString {
context.data.ignored.channels.let {
if (it.isEmpty()) {
append("None of the channels are ignored.")
}
it.mapNotNull(context.guild::getTextChannelById)
.map(IMentionable::getAsMention)
.forEach { append("• ").append(it).append('\n') }
}
}
}
field("Roles") {
buildString {
context.data.ignored.roles.let {
if (it.isEmpty()) {
append("None of the roles are ignored.")
}
it.mapNotNull(context.guild::getRoleById)
.map(IMentionable::getAsMention)
.forEach { append("• ").append(it).append('\n') }
}
}
}
}.action().queue()
}
} | mit | af5fcfe7d884a0ca0c7fce52faa173b6 | 33.929688 | 95 | 0.511857 | 4.730159 | false | false | false | false |
anlun/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/highlight/HaskellColorsAndFontsPage.kt | 1 | 4802 | package org.jetbrains.haskell.highlight
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.fileTypes.SyntaxHighlighter
import com.intellij.openapi.options.colors.AttributesDescriptor
import com.intellij.openapi.options.colors.ColorDescriptor
import com.intellij.openapi.options.colors.ColorSettingsPage
import org.jetbrains.annotations.NonNls
import org.jetbrains.haskell.icons.HaskellIcons
import javax.swing.*
import java.util.HashMap
public class HaskellColorsAndFontsPage : ColorSettingsPage {
override fun getDisplayName(): String {
return "Haskell"
}
override fun getIcon(): Icon? {
return HaskellIcons.HASKELL
}
override fun getAttributeDescriptors(): Array<AttributesDescriptor> {
return ATTRS
}
override fun getColorDescriptors(): Array<ColorDescriptor> {
return arrayOf()
}
override fun getHighlighter(): SyntaxHighlighter {
return HaskellHighlighter()
}
NonNls
override fun getDemoText(): String {
return "<keyword>module</keyword> <cons>Main</cons> <keyword>where</keyword>\n" +
"<pragma>{-# LANGUAGE CPP #-}</pragma>\n" +
"<comment>-- Comment</comment>\n" +
"\n" +
"<keyword>class</keyword> <class>YesNo a</class> <keyword>where</keyword>\n" +
" <sig>yesno</sig> <dcolon>::</dcolon> <type>a -> Bool</type>\n" +
"\n" +
"\n" + "<keyword>data</keyword> <type>Maybe a</type> <equal>=</equal> <cons>Nothing</cons> | <cons>Just</cons> <type>a</type>\n" +
"\n" + "<sig>main</sig> <dcolon>::</dcolon> <type>IO ()</type>\n" +
"<id>main</id> = <keyword>do</keyword>\n" +
" <id>putStrLn</id> <string>\"Hello\"</string> <operator>++</operator> <string>\" world!!\"</string>\n" +
"<id>t</id> <equal>=</equal> <number>5</number>\n" +
"<par>(</par><id>t</id><par>)</par>\n" +
"<curly>{}</curly>\n" +
"<brackets>[]</brackets>\n"
}
override fun getAdditionalHighlightingTagToDescriptorMap(): Map<String, TextAttributesKey>? {
val map = HashMap<String, TextAttributesKey>()
map.put("brackets", HaskellHighlighter.HASKELL_BRACKETS)
map.put("class", HaskellHighlighter.HASKELL_CLASS)
map.put("curly", HaskellHighlighter.HASKELL_CURLY)
map.put("cons", HaskellHighlighter.HASKELL_CONSTRUCTOR)
map.put("comment", HaskellHighlighter.HASKELL_COMMENT)
map.put("dcolon", HaskellHighlighter.HASKELL_DOUBLE_COLON)
map.put("equal", HaskellHighlighter.HASKELL_EQUAL)
map.put("id", HaskellHighlighter.HASKELL_IDENTIFIER)
map.put("keyword", HaskellHighlighter.HASKELL_KEYWORD)
map.put("number", HaskellHighlighter.HASKELL_NUMBER)
map.put("operator", HaskellHighlighter.HASKELL_OPERATOR)
map.put("par", HaskellHighlighter.HASKELL_PARENTHESIS)
map.put("pragma", HaskellHighlighter.HASKELL_PRAGMA)
map.put("sig", HaskellHighlighter.HASKELL_SIGNATURE)
map.put("string", HaskellHighlighter.HASKELL_STRING_LITERAL)
map.put("type", HaskellHighlighter.HASKELL_TYPE)
return map
}
companion object {
private val ATTRS = arrayOf(AttributesDescriptor("Brackets", HaskellHighlighter.HASKELL_BRACKETS),
AttributesDescriptor("Class", HaskellHighlighter.HASKELL_CLASS),
AttributesDescriptor("Comment", HaskellHighlighter.HASKELL_COMMENT),
AttributesDescriptor("Curly brackets", HaskellHighlighter.HASKELL_CURLY),
AttributesDescriptor("Constructor or Type", HaskellHighlighter.HASKELL_CONSTRUCTOR),
AttributesDescriptor("Double color", HaskellHighlighter.HASKELL_DOUBLE_COLON),
AttributesDescriptor("Equal", HaskellHighlighter.HASKELL_EQUAL),
AttributesDescriptor("Identifier", HaskellHighlighter.HASKELL_IDENTIFIER),
AttributesDescriptor("Keyword", HaskellHighlighter.HASKELL_KEYWORD),
AttributesDescriptor("Number", HaskellHighlighter.HASKELL_NUMBER),
AttributesDescriptor("Operator", HaskellHighlighter.HASKELL_OPERATOR),
AttributesDescriptor("Parenthesis", HaskellHighlighter.HASKELL_PARENTHESIS),
AttributesDescriptor("Pragma", HaskellHighlighter.HASKELL_PRAGMA),
AttributesDescriptor("Signature", HaskellHighlighter.HASKELL_SIGNATURE),
AttributesDescriptor("String", HaskellHighlighter.HASKELL_STRING_LITERAL),
AttributesDescriptor("Type", HaskellHighlighter.HASKELL_TYPE))
}
}
| apache-2.0 | 58334000794a0d8d286bf40e422aa083 | 49.020833 | 146 | 0.661599 | 4.91002 | false | false | false | false |
TCA-Team/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/ui/studyroom/StudyRoomsFragment.kt | 1 | 3913 | package de.tum.`in`.tumcampusapp.component.ui.studyroom
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Spinner
import android.widget.TextView
import de.tum.`in`.tumcampusapp.R
import de.tum.`in`.tumcampusapp.component.other.generic.fragment.FragmentForAccessingTumCabe
import de.tum.`in`.tumcampusapp.component.ui.studyroom.model.StudyRoomGroup
import kotlinx.android.synthetic.main.fragment_study_rooms.pager
import kotlinx.android.synthetic.main.fragment_study_rooms.spinner
import kotlinx.android.synthetic.main.fragment_study_rooms.spinnerContainer
import org.jetbrains.anko.support.v4.runOnUiThread
class StudyRoomsFragment : FragmentForAccessingTumCabe<List<StudyRoomGroup>>(
R.layout.fragment_study_rooms,
R.string.study_rooms
), AdapterView.OnItemSelectedListener {
private val sectionsPagerAdapter by lazy { StudyRoomsPagerAdapter(requireFragmentManager()) }
private val studyRoomGroupManager by lazy { StudyRoomGroupManager(requireContext()) }
private var groups = emptyList<StudyRoomGroup>()
private var groupId: Int = -1
// Drop-down navigation
private val studyRoomGroupsSpinner: Spinner
get() {
val groupAdapter = object : ArrayAdapter<StudyRoomGroup>(
requireContext(),
android.R.layout.simple_spinner_dropdown_item,
android.R.id.text1,
groups
) {
val inflater = LayoutInflater.from(context)
override fun getDropDownView(pos: Int, ignored: View?, parent: ViewGroup): View {
val v = inflater.inflate(android.R.layout.simple_spinner_dropdown_item, parent, false)
val studyRoomGroup = getItem(pos) ?: return v
val nameTextView = v.findViewById<TextView>(android.R.id.text1)
nameTextView.text = studyRoomGroup.name
return v
}
}
groupAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
return spinner.apply {
adapter = groupAdapter
onItemSelectedListener = this@StudyRoomsFragment
}
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
groupId = groups[position].id
changeViewPagerAdapter(groupId)
}
override fun onNothingSelected(adapterView: AdapterView<*>?) = Unit
override fun onStart() {
super.onStart()
loadStudyRooms()
}
override fun onRefresh() {
loadStudyRooms()
}
/**
* Change the group ID of the view pager, carefully unsetting the adapter while updating
*/
private fun changeViewPagerAdapter(selectedRoomGroupId: Int) {
pager.adapter = null
sectionsPagerAdapter.setStudyRoomGroupId(selectedRoomGroupId)
pager.adapter = sectionsPagerAdapter
}
private fun loadStudyRooms() {
fetch(apiClient.studyRoomGroups)
}
override fun onDownloadSuccessful(response: List<StudyRoomGroup>) {
studyRoomGroupManager.updateDatabase(response) {
runOnUiThread {
groups = response
displayStudyRooms()
}
}
}
private fun displayStudyRooms() {
selectCurrentSpinnerItem()
spinnerContainer.visibility = View.VISIBLE
showLoadingEnded()
}
private fun selectCurrentSpinnerItem() {
groups.forEachIndexed { i, (id) ->
if (groupId == -1 || groupId == id) {
groupId = id
studyRoomGroupsSpinner.setSelection(i)
return
}
}
}
companion object {
fun newInstance() = StudyRoomsFragment()
}
}
| gpl-3.0 | 7d79443715c7c398852a6d6229f650b5 | 33.628319 | 106 | 0.657807 | 5.062096 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/lang-xpm/main/uk/co/reecedunn/intellij/plugin/xpm/module/path/impl/XpmReverseDomainNameModulePath.kt | 1 | 3103 | /*
* Copyright (C) 2019 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.xpm.module.path.impl
import com.intellij.openapi.project.Project
import com.intellij.util.text.nullize
import uk.co.reecedunn.intellij.plugin.xdm.types.XdmUriContext
import uk.co.reecedunn.intellij.plugin.xdm.types.XsAnyUriValue
import uk.co.reecedunn.intellij.plugin.xpm.module.path.XpmModulePathFactory
object XpmReverseDomainNameModulePath : XpmModulePathFactory {
private val SPECIAL_CHARACTERS = "[^\\w.-/]".toRegex()
private fun createUri(project: Project, path: String, uri: XsAnyUriValue): XpmModuleLocationPath? {
val parts = path.substringAfter("://").nullize()?.split('/') ?: return null
val rdn = parts[0].split('.').reversed()
val rest = parts.drop(1).map { it.replace('.', '/') }
return when {
rest.isEmpty() -> createRelative(project, "${rdn.joinToString("/")}/", uri)
else -> createRelative(project, listOf(rdn, rest).flatten().joinToString("/"), uri)
}
}
private fun createUrn(project: Project, path: String, uri: XsAnyUriValue): XpmModuleLocationPath? {
return createRelative(project, path.replace(':', '/'), uri)
}
private fun createRelative(project: Project, path: String, uri: XsAnyUriValue): XpmModuleLocationPath? = when {
path.isEmpty() -> null
path.endsWith('/') -> {
XpmModuleLocationPath(project, "${path.replace(SPECIAL_CHARACTERS, "-")}index", uri.moduleTypes, null)
}
else -> XpmModuleLocationPath(project, path.replace(SPECIAL_CHARACTERS, "-"), uri.moduleTypes, null)
}
override fun create(project: Project, uri: XsAnyUriValue): XpmModuleLocationPath? = when (uri.context) {
XdmUriContext.Namespace, XdmUriContext.TargetNamespace, XdmUriContext.NamespaceDeclaration -> {
val path = uri.data
when {
path.startsWith("java:") /* Java paths are not converted by BaseX. */ -> null
path.startsWith("xmldb:exist://") /* Ignore eXist-db database paths. */ -> null
path.startsWith("file://") /* Keep file URLs intact. */ -> {
XpmModuleLocationPath(project, path, uri.moduleTypes, null)
}
path.contains("://") /* BaseX */ -> createUri(project, path, uri)
path.contains(":") /* BaseX */ -> createUrn(project, path, uri)
else /* BaseX */ -> createRelative(project, path, uri)
}
}
else -> null
}
}
| apache-2.0 | 340e29fe6a76f372ea3eb1994e34bd52 | 46.738462 | 115 | 0.65195 | 4.439199 | false | false | false | false |
HabitRPG/habitica-android | shared/src/commonMain/kotlin/com/habitrpg/shared/habitica/models/AvatarOutfit.kt | 1 | 744 | package com.habitrpg.shared.habitica.models
interface AvatarOutfit {
var armor: String
var back: String
var body: String
var head: String
var shield: String
var weapon: String
var eyeWear: String
var headAccessory: String
fun isAvailable(outfit: String): Boolean {
return outfit.isNotBlank() && !outfit.endsWith("base_0")
}
fun updateWith(newOutfit: AvatarOutfit) {
this.armor = newOutfit.armor
this.back = newOutfit.back
this.body = newOutfit.body
this.eyeWear = newOutfit.eyeWear
this.head = newOutfit.head
this.headAccessory = newOutfit.headAccessory
this.shield = newOutfit.shield
this.weapon = newOutfit.weapon
}
}
| gpl-3.0 | 09f811602636c401c1fbb0dba10c9a16 | 25.571429 | 64 | 0.658602 | 4.350877 | false | false | false | false |
pkleimann/livingdoc | livingdoc-converters/src/main/kotlin/org/livingdoc/converters/number/AbstractNumberConverter.kt | 3 | 2708 | package org.livingdoc.converters.number
import java.lang.reflect.AnnotatedElement
import java.math.BigDecimal
import java.text.DecimalFormat
import java.text.ParseException
import java.util.*
import org.livingdoc.api.conversion.ConversionException
import org.livingdoc.api.conversion.Language
import org.livingdoc.api.conversion.TypeConverter
import org.livingdoc.converters.exceptions.NumberRangeException
abstract class AbstractNumberConverter<T : Number> : TypeConverter<T> {
abstract val lowerBound: T?
abstract val upperBound: T?
@Throws(ConversionException::class)
override fun convert(value: String, element: AnnotatedElement?, documentClass: Class<*>?): T {
val locale = getLocale(element)
val format = getFormat(locale)
val number = parse(format, value)
assertThatNumberIsWithinRangeBoundaries(number)
return convertToTarget(number)
}
private fun getFormat(locale: Locale): DecimalFormat {
val format = DecimalFormat.getNumberInstance(locale) as DecimalFormat
format.isParseBigDecimal = true
return format
}
private fun getLocale(element: AnnotatedElement?): Locale {
val customLocale = element
?.getAnnotation(Language::class.java)
?.value
?.let { Locale.forLanguageTag(it) }
return customLocale ?: Locale.getDefault(Locale.Category.FORMAT)
}
private fun parse(format: DecimalFormat, value: String): BigDecimal {
try {
val processedValue = preProcess(value)
val trimmedValue = processedValue.trim()
return format.parse(trimmedValue) as BigDecimal
} catch (e: ParseException) {
throw ConversionException("not a number value: '$value'", e)
}
}
private fun preProcess(value: String): String {
// Fix for Java's DecimalFormat parser:
// - only when parsing BigDecimal targets
// - BigDecimal values containing "E+" will be cut of at the "+"
// - this can be prevented by pre-emotively replacing "E+" with "E"
return value.replaceFirst("E+", "E", true)
}
private fun assertThatNumberIsWithinRangeBoundaries(number: BigDecimal) {
val belowLowerBound = if (lowerBound != null) number < bigDecimalOf(lowerBound) else false
val aboveUpperBound = if (upperBound != null) number > bigDecimalOf(upperBound) else false
if (belowLowerBound || aboveUpperBound) {
throw NumberRangeException(number, lowerBound, upperBound)
}
}
private fun bigDecimalOf(value: T?) = BigDecimal(value!!.toString())
protected abstract fun convertToTarget(number: BigDecimal): T
}
| apache-2.0 | 5e2d7249fc54ea954f8bc7274a2165b7 | 37.685714 | 98 | 0.690916 | 4.870504 | false | false | false | false |
robfletcher/orca | keiko-core/src/main/kotlin/com/netflix/spinnaker/q/NoopQueue.kt | 4 | 2196 | /*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.q
import com.netflix.spinnaker.q.metrics.EventPublisher
import com.netflix.spinnaker.q.metrics.MonitorableQueue
import com.netflix.spinnaker.q.metrics.NoopEventPublisher
import com.netflix.spinnaker.q.metrics.QueueState
import java.time.Duration
import java.time.temporal.TemporalAmount
import org.slf4j.LoggerFactory
/**
* A Noop queue to be used when no Queue bean is found (e.g. when Queue is disabled)
*/
class NoopQueue : MonitorableQueue {
override val publisher: EventPublisher = NoopEventPublisher()
private val log = LoggerFactory.getLogger(this.javaClass)
init {
log.warn(
"${this.javaClass.simpleName} was created - all queue operations will be NOOP'd. " +
"This is OK if the queue was intended to be disabled"
)
}
override val ackTimeout: TemporalAmount
get() = Duration.ofMinutes(1)
override val canPollMany: Boolean
get() = false
override val deadMessageHandlers: List<DeadMessageCallback>
get() = emptyList()
override fun ensure(message: Message, delay: TemporalAmount) {
}
override fun poll(callback: QueueCallback) {
}
override fun poll(maxMessages: Int, callback: QueueCallback) {
}
override fun push(message: Message, delay: TemporalAmount) {
log.warn(
"A message ({}) was pushed onto the NoopQueue - this is probably not the intent",
message
)
}
override fun reschedule(message: Message, delay: TemporalAmount) {
}
override fun containsMessage(predicate: (Message) -> Boolean) = false
override fun readState(): QueueState = QueueState(0, 0, 0)
}
| apache-2.0 | 34fc784e1677aa6c8fdeab8f3bd48089 | 30.826087 | 90 | 0.734062 | 4.135593 | false | false | false | false |
apollostack/apollo-android | apollo-runtime-kotlin/src/appleMain/kotlin/com/apollographql/apollo3/network/http/NSURLSessionEngine.kt | 1 | 7617 | package com.apollographql.apollo3.network.http
import com.apollographql.apollo3.exception.ApolloException
import com.apollographql.apollo3.exception.ApolloHttpException
import com.apollographql.apollo3.exception.ApolloNetworkException
import com.apollographql.apollo3.network.toNSData
import kotlinx.cinterop.COpaquePointer
import kotlinx.cinterop.StableRef
import kotlinx.cinterop.asStableRef
import kotlinx.cinterop.convert
import kotlinx.cinterop.staticCFunction
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.suspendCancellableCoroutine
import okio.Buffer
import okio.IOException
import okio.toByteString
import platform.Foundation.NSData
import platform.Foundation.NSError
import platform.Foundation.NSHTTPURLResponse
import platform.Foundation.NSMutableURLRequest
import platform.Foundation.NSThread
import platform.Foundation.NSURL
import platform.Foundation.NSURLRequest
import platform.Foundation.NSURLRequestReloadIgnoringCacheData
import platform.Foundation.NSURLResponse
import platform.Foundation.NSURLSession
import platform.Foundation.NSURLSessionConfiguration
import platform.Foundation.NSURLSessionDataTask
import platform.Foundation.dataTaskWithRequest
import platform.Foundation.setHTTPBody
import platform.Foundation.setHTTPMethod
import platform.Foundation.setValue
import platform.darwin.dispatch_async_f
import platform.darwin.dispatch_get_main_queue
import kotlin.coroutines.Continuation
import kotlin.coroutines.resume
import kotlin.native.concurrent.freeze
typealias UrlSessionDataTaskCompletionHandler = (NSData?, NSURLResponse?, NSError?) -> Unit
fun interface DataTaskFactory {
fun dataTask(request: NSURLRequest, completionHandler: UrlSessionDataTaskCompletionHandler): NSURLSessionDataTask
}
@ExperimentalCoroutinesApi
actual class DefaultHttpEngine(
private val dataTaskFactory: DataTaskFactory,
private val connectTimeoutMillis: Long = 60_000,
) : HttpEngine {
actual constructor(
connectTimeoutMillis: Long,
readTimeoutMillis: Long,
) : this(
dataTaskFactory = DefaultDataTaskFactory(readTimeoutMillis),
connectTimeoutMillis = connectTimeoutMillis,
)
private class DefaultDataTaskFactory(readTimeoutMillis: Long) : DataTaskFactory {
private val nsurlSession = NSURLSession.sessionWithConfiguration(NSURLSessionConfiguration.defaultSessionConfiguration().apply {
timeoutIntervalForRequest = readTimeoutMillis.toDouble() / 1000
})
override fun dataTask(request: NSURLRequest, completionHandler: UrlSessionDataTaskCompletionHandler): NSURLSessionDataTask {
return nsurlSession.dataTaskWithRequest(request, completionHandler)
}
}
@Suppress("UNCHECKED_CAST")
override suspend fun <R> execute(request: HttpRequest, block: (HttpResponse) -> R): R {
assert(NSThread.isMainThread())
request.freeze()
val result = suspendCancellableCoroutine<Result<R>> { continuation ->
val continuationRef = StableRef.create(continuation).asCPointer()
val delegate = { httpData: NSData?, nsUrlResponse: NSURLResponse?, error: NSError? ->
initRuntimeIfNeeded()
parse(
data = httpData,
httpResponse = nsUrlResponse as? NSHTTPURLResponse,
error = error,
block = block
).dispatchOnMain(continuationRef)
}
val nsMutableURLRequest = NSMutableURLRequest.requestWithURL(
URL = NSURL(string = request.url)
).apply {
setTimeoutInterval(connectTimeoutMillis.toDouble() / 1000)
request.headers.forEach {
setValue(it.value, forHTTPHeaderField = it.key)
}
if (request.method == HttpMethod.Get) {
setHTTPMethod("GET")
} else {
setHTTPMethod("POST")
if (request.body != null) {
setValue(request.body.contentType, forHTTPHeaderField = "Content-Type")
if (request.body.contentLength >= 0) {
setValue(request.body.contentLength.toString(), forHTTPHeaderField = "Content-Length")
}
val body = Buffer().apply { request.body.writeTo(this) }.readByteArray().toNSData()
setHTTPBody(body)
}
}
setCachePolicy(NSURLRequestReloadIgnoringCacheData)
}
dataTaskFactory.dataTask(nsMutableURLRequest.freeze(), delegate.freeze())
.also { task ->
continuation.invokeOnCancellation {
task.cancel()
}
}
.resume()
}
when (result) {
is Result.Success -> {
return result.response
}
is Result.Failure -> {
throw result.cause
}
}
}
private fun <R> parse(
data: NSData?,
httpResponse: NSHTTPURLResponse?,
error: NSError?,
block: (HttpResponse) -> R
): Result<R> {
if (error != null) {
return Result.Failure(
cause = ApolloNetworkException(
message = "Failed to execute GraphQL http network request",
cause = IOException(error.localizedDescription)
)
)
}
if (httpResponse == null) {
return Result.Failure(
cause = ApolloNetworkException("Failed to parse GraphQL http network response: EOF")
)
}
val httpHeaders = httpResponse.allHeaderFields
.map { (key, value) -> key.toString() to value.toString() }
.toMap()
val statusCode = httpResponse.statusCode.toInt()
/**
* data can be empty if there is no body.
* In that case, trying to create a ByteString later on fails
* So fail early instead
*/
if (data == null || data.length.toInt() == 0) {
return Result.Failure(
cause = ApolloHttpException(
statusCode = httpResponse.statusCode.toInt(),
headers = httpHeaders,
message = "Failed to parse GraphQL http network response: EOF"
)
)
}
/**
* block can fail so wrap everything
*/
val result = kotlin.runCatching {
block(
HttpResponse(
statusCode = statusCode,
headers = httpHeaders,
body = Buffer().write(data.toByteString()))
)
}
return if (result.isSuccess) {
Result.Success(result.getOrNull()!!)
} else {
Result.Failure(wrapThrowableIfNeeded(result.exceptionOrNull()!!))
}
}
sealed class Result<R> {
class Success<R>(val response: R) : Result<R>()
class Failure<R>(val cause: ApolloException) : Result<R>()
}
@Suppress("NAME_SHADOWING")
private fun <R> Result<R>.dispatchOnMain(continuationPtr: COpaquePointer) {
if (NSThread.isMainThread()) {
dispatch(continuationPtr)
} else {
val continuationWithResultRef = StableRef.create((continuationPtr to this).freeze())
dispatch_async_f(
queue = dispatch_get_main_queue(),
context = continuationWithResultRef.asCPointer(),
work = staticCFunction { ptr ->
val continuationWithResultRef = ptr!!.asStableRef<Pair<COpaquePointer, Result<R>>>()
val (continuationPtr, result) = continuationWithResultRef.get()
continuationWithResultRef.dispose()
result.dispatch(continuationPtr)
}
)
}
}
}
@Suppress("NAME_SHADOWING")
@ExperimentalCoroutinesApi
internal fun <R> DefaultHttpEngine.Result<R>.dispatch(continuationPtr: COpaquePointer) {
val continuationRef = continuationPtr.asStableRef<Continuation<DefaultHttpEngine.Result<R>>>()
val continuation = continuationRef.get()
continuationRef.dispose()
continuation.resume(this)
}
| mit | 5f184dcf2ca1a2edb9ec6b7fb8d9b4aa | 32.117391 | 132 | 0.693711 | 4.833122 | false | false | false | false |
Heiner1/AndroidAPS | wear/src/main/java/info/nightscout/androidaps/tile/source/TempTargetSource.kt | 1 | 3949 | package info.nightscout.androidaps.tile.source
import android.content.Context
import android.content.res.Resources
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interaction.actions.BackgroundActionActivity
import info.nightscout.androidaps.interaction.actions.TempTargetActivity
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.sharedPreferences.SP
import info.nightscout.shared.weardata.EventData
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class TempTargetSource @Inject constructor(context: Context, sp: SP, aapsLogger: AAPSLogger) : StaticTileSource(context, sp, aapsLogger) {
override val preferencePrefix = "tile_tempt_"
override fun getActions(resources: Resources): List<StaticAction> {
val message = resources.getString(R.string.action_tempt_confirmation)
return listOf(
StaticAction(
settingName = "activity",
buttonText = resources.getString(R.string.temp_target_activity),
iconRes = R.drawable.ic_target_activity,
activityClass = BackgroundActionActivity::class.java.name,
message = message,
// actionString = "temptarget false 90 8.0 8.0",
// actionString = "temptarget preset activity",
action = EventData.ActionTempTargetPreCheck(EventData.ActionTempTargetPreCheck.TempTargetCommand.PRESET_ACTIVITY)
),
StaticAction(
settingName = "eating_soon",
buttonText = resources.getString(R.string.temp_target_eating_soon),
iconRes = R.drawable.ic_target_eatingsoon,
activityClass = BackgroundActionActivity::class.java.name,
message = message,
// actionString = "temptarget false 45 4.5 4.5",
// actionString = "temptarget preset eating",
action = EventData.ActionTempTargetPreCheck(EventData.ActionTempTargetPreCheck.TempTargetCommand.PRESET_EATING)
),
StaticAction(
settingName = "hypo",
buttonText = resources.getString(R.string.temp_target_hypo),
iconRes = R.drawable.ic_target_hypo,
activityClass = BackgroundActionActivity::class.java.name,
message = message,
// actionString = "temptarget false 45 7.0 7.0",
// actionString = "temptarget preset hypo",
action = EventData.ActionTempTargetPreCheck(EventData.ActionTempTargetPreCheck.TempTargetCommand.PRESET_HYPO)
),
StaticAction(
settingName = "manual",
buttonText = resources.getString(R.string.temp_target_manual),
iconRes = R.drawable.ic_target_manual,
activityClass = TempTargetActivity::class.java.name,
action = null
),
StaticAction(
settingName = "cancel",
buttonText = resources.getString(R.string.generic_cancel),
iconRes = R.drawable.ic_target_cancel,
activityClass = BackgroundActionActivity::class.java.name,
message = message,
//actionString = "temptarget cancel",
action = EventData.ActionTempTargetPreCheck(EventData.ActionTempTargetPreCheck.TempTargetCommand.CANCEL)
)
)
}
override fun getResourceReferences(resources: Resources): List<Int> {
return getActions(resources).map { it.iconRes }
}
override fun getDefaultConfig(): Map<String, String> {
return mapOf(
"tile_tempt_1" to "activity",
"tile_tempt_2" to "eating_soon",
"tile_tempt_3" to "hypo",
"tile_tempt_4" to "manual"
)
}
}
| agpl-3.0 | 8f4422e493ad2e3a3b8da001184a0a5e | 45.578313 | 138 | 0.620157 | 5.12192 | false | false | false | false |
Unpublished/AmazeFileManager | app/src/main/java/com/amaze/filemanager/ui/fragments/preference_fragments/QuickAccessPref.kt | 2 | 2802 | /*
* Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager 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.amaze.filemanager.ui.fragments.preference_fragments
import android.content.SharedPreferences
import android.os.Bundle
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.PreferenceManager
import androidx.preference.SwitchPreference
import com.amaze.filemanager.R
import com.amaze.filemanager.utils.TinyDB
import java.util.*
/** @author Emmanuel on 17/4/2017, at 23:17.
*/
class QuickAccessPref : PreferenceFragmentCompat(), Preference.OnPreferenceClickListener {
companion object {
const val KEY = "quick access array"
val KEYS = arrayOf(
"fastaccess", "recent", "image", "video", "audio", "documents", "apks"
)
val DEFAULT = arrayOf(true, true, true, true, true, true, true)
private var prefPos: Map<String, Int> = HashMap()
init {
prefPos = KEYS.withIndex().associate {
Pair(it.value, it.index)
}
}
}
private var preferences: SharedPreferences? = null
private var currentValue: Array<Boolean>? = null
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.fastaccess_prefs)
preferences = PreferenceManager.getDefaultSharedPreferences(activity)
currentValue = TinyDB.getBooleanArray(preferences!!, KEY, DEFAULT)
for (i in 0 until preferenceScreen.preferenceCount) {
preferenceScreen.getPreference(i).onPreferenceClickListener = this
}
}
override fun onPreferenceClick(preference: Preference): Boolean {
currentValue!![prefPos[preference.key]!!] = (preference as SwitchPreference).isChecked
TinyDB.putBooleanArray(preferences!!, KEY, currentValue!!)
return true
}
}
| gpl-3.0 | 1e4f7a1333fa061155794ae3e8ebb334 | 38.464789 | 107 | 0.716631 | 4.66223 | false | false | false | false |
realm/realm-java | realm-transformer/src/main/kotlin/io/realm/analytics/ComputerIdentifierGenerator.kt | 1 | 3714 | /*
* Copyright 2021 Realm 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 io.realm.analytics
import io.realm.transformer.Utils
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException
import java.net.NetworkInterface
import java.net.SocketException
import java.security.NoSuchAlgorithmException
import java.util.*
/**
* Generate a unique identifier for a computer. The method being used depends on the platform:
* - OS X: Mac address of en0
* - Windows: BIOS identifier
* - Linux: Machine ID provided by the OS
*/
class ComputerIdentifierGenerator {
companion object {
private const val UNKNOWN = "unknown"
private val OS: String = System.getProperty("os.name").toLowerCase()
private val isWindows: Boolean = OS.contains("win")
private val isMac: Boolean = OS.contains("mac")
private val isLinux: Boolean = OS.contains("inux")
fun get(): String {
return try {
when {
isWindows -> getWindowsIdentifier()
isMac -> getMacOsIdentifier()
isLinux -> getLinuxMacAddress()
else -> UNKNOWN
}
} catch (e: Exception) {
UNKNOWN
}
}
@Throws(FileNotFoundException::class, NoSuchAlgorithmException::class)
private fun getLinuxMacAddress(): String {
var machineId = File("/var/lib/dbus/machine-id")
if (!machineId.exists()) {
machineId = File("/etc/machine-id")
}
if (!machineId.exists()) {
return UNKNOWN
}
var scanner: Scanner? = null
return try {
scanner = Scanner(machineId)
val id = scanner.useDelimiter("\\A").next()
Utils.hexStringify(Utils.sha256Hash(id.toByteArray()))
} finally {
scanner?.close()
}
}
@Throws(SocketException::class, NoSuchAlgorithmException::class)
private fun getMacOsIdentifier(): String {
val networkInterface = NetworkInterface.getByName("en0")
val hardwareAddress = networkInterface.hardwareAddress
return Utils.hexStringify(Utils.sha256Hash(hardwareAddress))
}
@Throws(IOException::class, NoSuchAlgorithmException::class)
private fun getWindowsIdentifier(): String {
val runtime = Runtime.getRuntime()
val process = runtime.exec(arrayOf("wmic", "csproduct", "get", "UUID"))
var result: String? = null
val `is` = process.inputStream
val sc = Scanner(process.inputStream)
try {
while (sc.hasNext()) {
val next = sc.next()
if (next.contains("UUID")) {
result = sc.next().trim { it <= ' ' }
break
}
}
} finally {
`is`.close()
}
return if (result == null) UNKNOWN else Utils.hexStringify(Utils.sha256Hash(result.toByteArray()))
}
}
} | apache-2.0 | a7e6ba43fb4ce5f3d39c8e9d4116ecb6 | 35.782178 | 110 | 0.585622 | 4.925729 | false | false | false | false |
kareez/yekan | vertx-lang-kotlin/src/main/kotlin/io/vertx/kotlin/core/MultiMap.kt | 2 | 1260 | package io.vertx.kotlin.core
import io.vertx.kotlin.core.internal.Delegator
/**
*/
class MultiMap(override val delegate: io.vertx.core.MultiMap) : Delegator<io.vertx.core.MultiMap>, Iterable<Map.Entry<String, String>> {
fun get(name: String): String = delegate.get(name)
fun getAll(name: String): List<String> = delegate.getAll(name)
fun contains(name: String): Boolean = delegate.contains(name)
fun isEmpty(): Boolean = delegate.isEmpty()
fun names(): Set<String> = delegate.names()
fun add(name: String, value: String): MultiMap {
delegate.add(name, value)
return this
}
fun addAll(map: MultiMap): MultiMap {
delegate.addAll(map.delegate)
return this
}
fun set(name: String, value: String): MultiMap {
delegate.set(name, value)
return this
}
fun setAll(map: MultiMap): MultiMap {
delegate.setAll(map.delegate)
return this
}
fun remove(name: String): MultiMap {
delegate.remove(name)
return this
}
fun clear(): MultiMap {
delegate.clear()
return this
}
fun size(): Int = delegate.size()
override fun iterator(): Iterator<Map.Entry<String, String>> = delegate.iterator()
}
| apache-2.0 | ca26c7bfaf91af9f87efee442a4b2bc2 | 23.705882 | 136 | 0.634921 | 4 | false | false | false | false |
Kaljurand/K6nele | app/src/main/java/ee/ioc/phon/android/speak/model/CallerInfo.kt | 1 | 662 | package ee.ioc.phon.android.speak.model
import android.content.ComponentName
import android.os.Bundle
import android.view.inputmethod.EditorInfo
// TODO: preserve the full component name
class CallerInfo {
val extras: Bundle?
val editorInfo: EditorInfo?
val packageName: String?
constructor(extras: Bundle, editorInfo: EditorInfo, packageName: String) {
this.extras = extras
this.editorInfo = editorInfo
this.packageName = packageName
}
constructor(extras: Bundle, componentName: ComponentName?) {
this.extras = extras
editorInfo = null
packageName = componentName?.packageName
}
} | apache-2.0 | 580d55ed2c8ab65da0b6f654678d1bf7 | 25.52 | 78 | 0.70997 | 4.797101 | false | false | false | false |
KotlinNLP/SimpleDNN | src/test/kotlin/core/layers/recurrent/ran/RANLayerStructureUtils.kt | 1 | 3706 | /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package core.layers.recurrent.ran
import com.kotlinnlp.simplednn.core.functionalities.activations.Tanh
import com.kotlinnlp.simplednn.core.arrays.AugmentedArray
import com.kotlinnlp.simplednn.core.layers.LayerType
import com.kotlinnlp.simplednn.core.layers.models.recurrent.LayersWindow
import com.kotlinnlp.simplednn.core.layers.models.recurrent.ran.RANLayerParameters
import com.kotlinnlp.simplednn.core.layers.models.recurrent.ran.RANLayer
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory
import com.kotlinnlp.simplednn.simplemath.ndarray.Shape
/**
*
*/
internal object RANLayerStructureUtils {
/**
*
*/
fun buildLayer(layersWindow: LayersWindow): RANLayer<DenseNDArray> = RANLayer(
inputArray = AugmentedArray(DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.8, -0.9, -0.9, 1.0))),
inputType = LayerType.Input.Dense,
outputArray = AugmentedArray(DenseNDArrayFactory.emptyArray(Shape(5))),
params = buildParams(),
activationFunction = Tanh,
layersWindow = layersWindow,
dropout = 0.0
)
/**
*
*/
fun buildParams() = RANLayerParameters(inputSize = 4, outputSize = 5).apply {
inputGate.weights.values.assignValues(
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.5, 0.6, -0.8, -0.6),
doubleArrayOf(0.7, -0.4, 0.1, -0.8),
doubleArrayOf(0.7, -0.7, 0.3, 0.5),
doubleArrayOf(0.8, -0.9, 0.0, -0.1),
doubleArrayOf(0.4, 1.0, -0.7, 0.8)
)))
forgetGate.weights.values.assignValues(
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.1, 0.4, -1.0, 0.4),
doubleArrayOf(0.7, -0.2, 0.1, 0.0),
doubleArrayOf(0.7, 0.8, -0.5, -0.3),
doubleArrayOf(-0.9, 0.9, -0.3, -0.3),
doubleArrayOf(-0.7, 0.6, -0.6, -0.8)
)))
candidate.weights.values.assignValues(
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(-1.0, 0.2, 0.0, 0.2),
doubleArrayOf(-0.7, 0.7, -0.3, -0.3),
doubleArrayOf(0.3, -0.6, 0.0, 0.7),
doubleArrayOf(-1.0, -0.6, 0.9, 0.8),
doubleArrayOf(0.5, 0.8, -0.9, -0.8)
)))
inputGate.biases.values.assignValues(DenseNDArrayFactory.arrayOf(doubleArrayOf(0.4, 0.0, -0.3, 0.8, -0.4)))
forgetGate.biases.values.assignValues(DenseNDArrayFactory.arrayOf(doubleArrayOf(0.9, 0.2, -0.9, 0.2, -0.9)))
candidate.biases.values.assignValues(DenseNDArrayFactory.arrayOf(doubleArrayOf(0.2, 0.0, -0.9, 0.7, -0.3)))
inputGate.recurrentWeights.values.assignValues(
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.0, 0.8, 0.8, -1.0, -0.7),
doubleArrayOf(-0.7, -0.8, 0.2, -0.7, 0.7),
doubleArrayOf(-0.9, 0.9, 0.7, -0.5, 0.5),
doubleArrayOf(0.0, -0.1, 0.5, -0.2, -0.8),
doubleArrayOf(-0.6, 0.6, 0.8, -0.1, -0.3)
)))
forgetGate.recurrentWeights.values.assignValues(
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.1, -0.6, -1.0, -0.1, -0.4),
doubleArrayOf(0.5, -0.9, 0.0, 0.8, 0.3),
doubleArrayOf(-0.3, -0.9, 0.3, 1.0, -0.2),
doubleArrayOf(0.7, 0.2, 0.3, -0.4, -0.6),
doubleArrayOf(-0.2, 0.5, -0.2, -0.9, 0.4)
)))
}
/**
*
*/
fun getOutputGold() = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.57, 0.75, -0.15, 1.64, 0.45))
}
| mpl-2.0 | 18a080ce4269245a2d6f8435001ac677 | 36.816327 | 112 | 0.638964 | 3.15942 | false | false | false | false |
mdaniel/intellij-community | platform/platform-impl/src/com/intellij/ide/startup/impl/StartupManagerImpl.kt | 1 | 20165 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("OVERRIDE_DEPRECATION")
package com.intellij.ide.startup.impl
import com.intellij.diagnostic.*
import com.intellij.diagnostic.opentelemetry.TraceManager
import com.intellij.diagnostic.telemetry.useWithScope
import com.intellij.ide.IdeEventQueue
import com.intellij.ide.lightEdit.LightEdit
import com.intellij.ide.lightEdit.LightEditCompatible
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.plugins.cl.PluginAwareClassLoader
import com.intellij.ide.startup.StartupManagerEx
import com.intellij.idea.processExtensions
import com.intellij.openapi.application.*
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.ExtensionPointListener
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl
import com.intellij.openapi.progress.*
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbAwareRunnable
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.impl.isCorePlugin
import com.intellij.openapi.startup.InitProjectActivity
import com.intellij.openapi.startup.ProjectPostStartupActivity
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.util.registry.Registry
import com.intellij.serviceContainer.AlreadyDisposedException
import com.intellij.util.ModalityUiUtil
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.api.common.Attributes
import io.opentelemetry.api.trace.Span
import io.opentelemetry.context.Context
import io.opentelemetry.extension.kotlin.asContextElement
import kotlinx.coroutines.*
import org.intellij.lang.annotations.MagicConstant
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
import org.jetbrains.annotations.VisibleForTesting
import java.awt.event.InvocationEvent
import java.util.*
import java.util.concurrent.CancellationException
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReference
import kotlin.coroutines.coroutineContext
private val LOG = logger<StartupManagerImpl>()
private val tracer by lazy { TraceManager.getTracer("startupManager") }
/**
* Acts as [StartupActivity.POST_STARTUP_ACTIVITY], but executed with 5 seconds delay after project opening.
*/
private val BACKGROUND_POST_STARTUP_ACTIVITY = ExtensionPointName<StartupActivity>("com.intellij.backgroundPostStartupActivity")
private val EDT_WARN_THRESHOLD_IN_NANO = TimeUnit.MILLISECONDS.toNanos(100)
private const val DUMB_AWARE_PASSED = 1
private const val ALL_PASSED = 2
@ApiStatus.Internal
open class StartupManagerImpl(private val project: Project) : StartupManagerEx() {
companion object {
@VisibleForTesting
fun addActivityEpListener(project: Project) {
StartupActivity.POST_STARTUP_ACTIVITY.addExtensionPointListener(object : ExtensionPointListener<StartupActivity?> {
override fun extensionAdded(activity: StartupActivity, descriptor: PluginDescriptor) {
if (project is LightEditCompatible && activity !is LightEditCompatible) {
return
}
val startupManager = getInstance(project) as StartupManagerImpl
val pluginId = descriptor.pluginId
@Suppress("SSBasedInspection")
if (activity is DumbAware) {
project.coroutineScope.launch {
if (activity is ProjectPostStartupActivity) {
activity.execute(project)
}
else {
startupManager.runActivityAndMeasureDuration(activity, pluginId)
}
}
}
else {
DumbService.getInstance(project).unsafeRunWhenSmart {
startupManager.runActivityAndMeasureDuration(activity, pluginId)
}
}
}
}, project)
}
}
private val lock = Any()
private val initProjectStartupActivities = ArrayDeque<Runnable>()
private val postStartupActivities = ArrayDeque<Runnable>()
@MagicConstant(intValues = [0, DUMB_AWARE_PASSED.toLong(), ALL_PASSED.toLong()])
@Volatile
private var postStartupActivitiesPassed = 0
private val allActivitiesPassed = CompletableDeferred<Any?>()
@Volatile
private var isInitProjectActivitiesPassed = false
private fun checkNonDefaultProject() {
LOG.assertTrue(!project.isDefault, "Please don't register startup activities for the default project: they won't ever be run")
}
override fun registerStartupActivity(runnable: Runnable) {
checkNonDefaultProject()
LOG.assertTrue(!isInitProjectActivitiesPassed, "Registering startup activity that will never be run")
synchronized(lock) {
initProjectStartupActivities.add(runnable)
}
}
override fun registerPostStartupActivity(runnable: Runnable) {
Span.current().addEvent("register startup activity", Attributes.of(AttributeKey.stringKey("runnable"), runnable.toString()))
@Suppress("SSBasedInspection")
if (runnable is DumbAware) {
runAfterOpened(runnable)
}
else {
LOG.error("Activities registered via registerPostStartupActivity must be dumb-aware: $runnable")
}
}
private fun checkThatPostActivitiesNotPassed() {
if (postStartupActivityPassed()) {
LOG.error("Registering post-startup activity that will never be run (" +
" disposed=${project.isDisposed}" +
", open=${project.isOpen}" +
", passed=$isInitProjectActivitiesPassed"
+ ")")
}
}
override fun startupActivityPassed() = isInitProjectActivitiesPassed
override fun postStartupActivityPassed(): Boolean {
return when (postStartupActivitiesPassed) {
ALL_PASSED -> true
-1 -> throw RuntimeException("Aborted; check the log for a reason")
else -> false
}
}
override fun getAllActivitiesPassedFuture() = allActivitiesPassed
suspend fun initProject(indicator: ProgressIndicator?) {
// see https://github.com/JetBrains/intellij-community/blob/master/platform/service-container/overview.md#startup-activity
LOG.assertTrue(!isInitProjectActivitiesPassed)
runActivity("project startup") {
tracer.spanBuilder("run init project activities").useWithScope {
runInitProjectActivities(indicator)
isInitProjectActivitiesPassed = true
}
}
}
suspend fun runStartupActivities() {
// opened on startup
StartUpMeasurer.compareAndSetCurrentState(LoadingState.COMPONENTS_LOADED, LoadingState.PROJECT_OPENED)
// opened from the welcome screen
StartUpMeasurer.compareAndSetCurrentState(LoadingState.APP_STARTED, LoadingState.PROJECT_OPENED)
coroutineContext.ensureActive()
val app = ApplicationManager.getApplication()
if (app.isUnitTestMode && !app.isDispatchThread) {
runPostStartupActivities(async = false)
}
else {
// doesn't block project opening
project.coroutineScope.launch {
runPostStartupActivities(async = true)
}
if (app.isUnitTestMode) {
LOG.assertTrue(app.isDispatchThread)
waitAndProcessInvocationEventsInIdeEventQueue(this)
}
}
}
private suspend fun runInitProjectActivities(indicator: ProgressIndicator?) {
runActivities(initProjectStartupActivities)
val app = ApplicationManager.getApplication()
val extensionPoint = (app.extensionArea as ExtensionsAreaImpl).getExtensionPoint<StartupActivity>("com.intellij.startupActivity")
// do not create extension if not allow-listed
for (adapter in extensionPoint.sortedAdapters) {
coroutineContext.ensureActive()
val pluginId = adapter.pluginDescriptor.pluginId
if (!isCorePlugin(adapter.pluginDescriptor) && pluginId.idString != "com.jetbrains.performancePlugin") {
LOG.error("Only bundled plugin can define ${extensionPoint.name}: ${adapter.pluginDescriptor}")
continue
}
val activity = adapter.createInstance<InitProjectActivity>(project) ?: continue
indicator?.pushState()
val startTime = StartUpMeasurer.getCurrentTime()
try {
tracer.spanBuilder("run activity")
.setAttribute(AttributeKey.stringKey("class"), activity.javaClass.name)
.setAttribute(AttributeKey.stringKey("plugin"), pluginId.idString)
.useWithScope {
if (project !is LightEditCompatible || activity is LightEditCompatible) {
activity.run(project)
}
}
}
finally {
indicator?.popState()
}
addCompletedActivity(startTime = startTime, runnableClass = activity.javaClass, pluginId = pluginId)
}
}
// Must be executed in a pooled thread outside of project loading modal task. The only exclusion - test mode.
private suspend fun runPostStartupActivities(async: Boolean) {
try {
LOG.assertTrue(isInitProjectActivitiesPassed)
val snapshot = PerformanceWatcher.takeSnapshot()
// strictly speaking, the activity is not sequential, because sub-activities are performed in different threads
// (depending on dumb-awareness), but because there is no other concurrent phase, we measure it as a sequential activity
// to put it on the timeline and make clear what's going at the end (avoiding the last "unknown" phase)
val dumbAwareActivity = StartUpMeasurer.startActivity(StartUpMeasurer.Activities.PROJECT_DUMB_POST_START_UP_ACTIVITIES)
val edtActivity = AtomicReference<Activity?>()
val uiFreezeWarned = AtomicBoolean()
val counter = AtomicInteger()
val dumbService = DumbService.getInstance(project)
val isProjectLightEditCompatible = project is LightEditCompatible
val traceContext = Context.current()
StartupActivity.POST_STARTUP_ACTIVITY.processExtensions { activity, pluginDescriptor ->
if (isProjectLightEditCompatible && activity !is LightEditCompatible) {
return@processExtensions
}
if (activity is ProjectPostStartupActivity) {
val pluginId = pluginDescriptor.pluginId
if (async) {
project.coroutineScope.launch {
val startTime = StartUpMeasurer.getCurrentTime()
val span = tracer.spanBuilder("run activity")
.setAttribute(AttributeKey.stringKey("class"), activity.javaClass.name)
.setAttribute(AttributeKey.stringKey("plugin"), pluginId.idString)
.startSpan()
withContext(traceContext.with(span).asContextElement()) {
activity.execute(project)
}
addCompletedActivity(startTime = startTime, runnableClass = activity.javaClass, pluginId = pluginId)
}
}
else {
activity.execute(project)
}
return@processExtensions
}
@Suppress("SSBasedInspection")
if (activity is DumbAware) {
dumbService.runWithWaitForSmartModeDisabled().use {
runActivityAndMeasureDuration(activity, pluginDescriptor.pluginId)
}
return@processExtensions
}
else {
if (edtActivity.get() == null) {
edtActivity.set(StartUpMeasurer.startActivity("project post-startup edt activities"))
}
// DumbService.unsafeRunWhenSmart throws an assertion in LightEdit mode, see LightEditDumbService.unsafeRunWhenSmart
if (!isProjectLightEditCompatible) {
counter.incrementAndGet()
dumbService.unsafeRunWhenSmart {
traceContext.makeCurrent()
val duration = runActivityAndMeasureDuration(activity, pluginDescriptor.pluginId)
if (duration > EDT_WARN_THRESHOLD_IN_NANO) {
reportUiFreeze(uiFreezeWarned)
}
dumbUnawarePostActivitiesPassed(edtActivity, counter.decrementAndGet())
}
}
}
}
dumbUnawarePostActivitiesPassed(edtActivity, counter.get())
runPostStartupActivitiesRegisteredDynamically()
dumbAwareActivity.end()
snapshot.logResponsivenessSinceCreation("Post-startup activities under progress")
coroutineContext.ensureActive()
if (!ApplicationManager.getApplication().isUnitTestMode) {
scheduleBackgroundPostStartupActivities()
addActivityEpListener(project)
}
}
catch (e: CancellationException) {
throw e
}
catch (e: Throwable) {
if (ApplicationManager.getApplication().isUnitTestMode) {
postStartupActivitiesPassed = -1
}
else {
throw e
}
}
}
private fun runActivityAndMeasureDuration(activity: StartupActivity, pluginId: PluginId): Long {
val startTime = StartUpMeasurer.getCurrentTime()
try {
tracer.spanBuilder("run activity")
.setAttribute(AttributeKey.stringKey("class"), activity.javaClass.name)
.setAttribute(AttributeKey.stringKey("plugin"), pluginId.idString)
.useWithScope {
if (project !is LightEditCompatible || activity is LightEditCompatible) {
activity.runActivity(project)
}
}
}
catch (e: Throwable) {
if (e is ControlFlowException || e is CancellationException) {
throw e
}
LOG.error(e)
}
return addCompletedActivity(startTime = startTime, runnableClass = activity.javaClass, pluginId = pluginId)
}
private suspend fun runPostStartupActivitiesRegisteredDynamically() {
tracer.spanBuilder("run post-startup dynamically registered activities").useWithScope {
runActivities(postStartupActivities, activityName = "project post-startup")
}
postStartupActivitiesPassed = DUMB_AWARE_PASSED
postStartupActivitiesPassed = ALL_PASSED
allActivitiesPassed.complete(value = null)
}
private suspend fun runActivities(activities: Deque<Runnable>, activityName: String? = null) {
synchronized(lock) {
if (activities.isEmpty()) {
return
}
}
val activity = activityName?.let {
StartUpMeasurer.startActivity(it)
}
while (true) {
coroutineContext.ensureActive()
val runnable = synchronized(lock, activities::pollFirst) ?: break
val startTime = StartUpMeasurer.getCurrentTime()
val runnableClass = runnable.javaClass
val pluginId = (runnableClass.classLoader as? PluginAwareClassLoader)?.pluginId ?: PluginManagerCore.CORE_ID
try {
tracer.spanBuilder("run activity")
.setAttribute(AttributeKey.stringKey("class"), runnableClass.name)
.setAttribute(AttributeKey.stringKey("plugin"), pluginId.idString)
.useWithScope {
runnable.run()
}
}
catch (e: CancellationException) {
throw e
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
LOG.error(e)
}
addCompletedActivity(startTime = startTime, runnableClass = runnableClass, pluginId = pluginId)
}
activity?.end()
}
private fun scheduleBackgroundPostStartupActivities() {
project.coroutineScope.launch {
delay(Registry.intValue("ide.background.post.startup.activity.delay", 5_000).toLong())
// read action - dynamic plugin loading executed as a write action
// readActionBlocking because maybe called several times, but addExtensionPointListener must be added only once
readActionBlocking {
BACKGROUND_POST_STARTUP_ACTIVITY.addExtensionPointListener(
object : ExtensionPointListener<StartupActivity> {
override fun extensionAdded(extension: StartupActivity, pluginDescriptor: PluginDescriptor) {
project.coroutineScope.runBackgroundPostStartupActivities(listOf(extension))
}
}, project)
BACKGROUND_POST_STARTUP_ACTIVITY.extensionList
}
if (!isActive) {
return@launch
}
runBackgroundPostStartupActivities(readAction { BACKGROUND_POST_STARTUP_ACTIVITY.extensionList })
}
}
private fun CoroutineScope.runBackgroundPostStartupActivities(activities: List<StartupActivity>) {
for (activity in activities) {
try {
if (project !is LightEditCompatible || activity is LightEditCompatible) {
if (activity is ProjectPostStartupActivity) {
launch {
activity.execute(project)
}
}
else {
activity.runActivity(project)
}
}
}
catch (e: CancellationException) {
throw e
}
catch (e: AlreadyDisposedException) {
coroutineContext.ensureActive()
}
catch (e: Throwable) {
if (e is ControlFlowException) {
throw e
}
LOG.error(e)
}
}
}
override fun runWhenProjectIsInitialized(action: Runnable) {
if (DumbService.isDumbAware(action)) {
runAfterOpened { ModalityUiUtil.invokeLaterIfNeeded(ModalityState.NON_MODAL, project.disposed, action) }
}
else if (!LightEdit.owns(project)) {
runAfterOpened { DumbService.getInstance(project).unsafeRunWhenSmart(action) }
}
}
override fun runAfterOpened(runnable: Runnable) {
checkNonDefaultProject()
if (postStartupActivitiesPassed < DUMB_AWARE_PASSED) {
synchronized(lock) {
if (postStartupActivitiesPassed < DUMB_AWARE_PASSED) {
postStartupActivities.add(runnable)
return
}
}
}
runnable.run()
}
@TestOnly
@Synchronized
fun prepareForNextTest() {
synchronized(lock) {
initProjectStartupActivities.clear()
postStartupActivities.clear()
}
}
@TestOnly
@Synchronized
fun checkCleared() {
try {
synchronized(lock) {
assert(initProjectStartupActivities.isEmpty()) { "Activities: $initProjectStartupActivities" }
assert(postStartupActivities.isEmpty()) { "DumbAware Post Activities: $postStartupActivities" }
}
}
finally {
prepareForNextTest()
}
}
}
private fun addCompletedActivity(startTime: Long, runnableClass: Class<*>, pluginId: PluginId): Long {
return StartUpMeasurer.addCompletedActivity(
startTime,
runnableClass,
ActivityCategory.POST_STARTUP_ACTIVITY,
pluginId.idString,
StartUpMeasurer.MEASURE_THRESHOLD,
)
}
private fun dumbUnawarePostActivitiesPassed(edtActivity: AtomicReference<Activity?>, count: Int) {
if (count == 0) {
edtActivity.getAndSet(null)?.end()
}
}
private fun reportUiFreeze(uiFreezeWarned: AtomicBoolean) {
val app = ApplicationManager.getApplication()
if (!app.isUnitTestMode && app.isDispatchThread && uiFreezeWarned.compareAndSet(false, true)) {
LOG.info("Some post-startup activities freeze UI for noticeable time. " +
"Please consider making them DumbAware to run them in background under modal progress," +
" or just making them faster to speed up project opening.")
}
}
// allow `invokeAndWait` inside startup activities
private suspend fun waitAndProcessInvocationEventsInIdeEventQueue(startupManager: StartupManagerImpl) {
ApplicationManager.getApplication().assertIsDispatchThread()
val eventQueue = IdeEventQueue.getInstance()
if (startupManager.postStartupActivityPassed()) {
withContext(Dispatchers.EDT) {
}
}
else {
// make sure eventQueue.nextEvent will unblock
startupManager.runAfterOpened(DumbAwareRunnable { ApplicationManager.getApplication().invokeLater { } })
}
while (true) {
val event = eventQueue.nextEvent
if (event is InvocationEvent) {
eventQueue.dispatchEvent(event)
}
if (startupManager.postStartupActivityPassed() && eventQueue.peekEvent() == null) {
break
}
}
} | apache-2.0 | aeafe71c5533d4b0e9efd9f097f884a8 | 36.275416 | 133 | 0.706571 | 5.312171 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/test-framework/test/org/jetbrains/kotlin/idea/test/KotlinLightCodeInsightFixtureTestCase.kt | 1 | 23050 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.test
import com.intellij.application.options.CodeStyle
import com.intellij.codeInsight.daemon.impl.EditorTracker
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionManagerEx
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.actionSystem.impl.SimpleDataContext
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.actionSystem.CaretSpecificDataContext
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.editor.ex.util.EditorUtil
import com.intellij.openapi.externalSystem.service.project.ProjectDataManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess
import com.intellij.pom.java.LanguageLevel
import com.intellij.psi.PsiClassOwner
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiJavaFile
import com.intellij.psi.PsiManager
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.psi.codeStyle.CodeStyleSettingsManager
import com.intellij.psi.search.FileTypeIndex
import com.intellij.psi.search.ProjectScope
import com.intellij.testFramework.IdeaTestUtil
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.LoggedErrorProcessor
import com.intellij.testFramework.RunAll
import com.intellij.testFramework.common.runAll
import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture
import com.intellij.util.ThrowableRunnable
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.config.ApiVersion
import org.jetbrains.kotlin.config.CompilerSettings
import org.jetbrains.kotlin.config.CompilerSettings.Companion.DEFAULT_ADDITIONAL_ARGUMENTS
import org.jetbrains.kotlin.config.JvmTarget
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.base.facet.hasKotlinFacet
import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinCommonCompilerArgumentsHolder
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinCompilerSettings
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout
import org.jetbrains.kotlin.idea.facet.KotlinFacet
import org.jetbrains.kotlin.idea.facet.configureFacet
import org.jetbrains.kotlin.idea.facet.getOrCreateFacet
import org.jetbrains.kotlin.idea.facet.removeKotlinFacet
import org.jetbrains.kotlin.idea.formatter.KotlinLanguageCodeStyleSettingsProvider
import org.jetbrains.kotlin.idea.formatter.KotlinStyleGuideCodeStyle
import org.jetbrains.kotlin.idea.inspections.UnusedSymbolInspection
import org.jetbrains.kotlin.idea.test.CompilerTestDirectives.API_VERSION_DIRECTIVE
import org.jetbrains.kotlin.idea.test.CompilerTestDirectives.COMPILER_ARGUMENTS_DIRECTIVE
import org.jetbrains.kotlin.idea.test.CompilerTestDirectives.JVM_TARGET_DIRECTIVE
import org.jetbrains.kotlin.idea.test.CompilerTestDirectives.LANGUAGE_VERSION_DIRECTIVE
import org.jetbrains.kotlin.idea.test.util.slashedPath
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.test.KotlinRoot
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlin.utils.rethrow
import java.io.File
import java.io.IOException
import java.nio.file.Path
import kotlin.test.assertEquals
abstract class KotlinLightCodeInsightFixtureTestCase : KotlinLightCodeInsightFixtureTestCaseBase() {
private val exceptions = ArrayList<Throwable>()
protected open val captureExceptions = false
protected fun dataFile(fileName: String): File = File(testDataDirectory, fileName)
protected fun dataFile(): File = dataFile(fileName())
protected fun dataFilePath(): Path = dataFile().toPath()
protected fun dataFilePath(fileName: String = fileName()): String = dataFile(fileName).toString()
protected open fun fileName(): String = KotlinTestUtils.getTestDataFileName(this::class.java, this.name) ?: (getTestName(false) + ".kt")
@Deprecated("Migrate to 'testDataDirectory'.", ReplaceWith("testDataDirectory"))
final override fun getTestDataPath(): String = testDataDirectory.slashedPath
open val testDataDirectory: File by lazy {
File(TestMetadataUtil.getTestDataPath(javaClass))
}
override fun setUp() {
super.setUp()
enableKotlinOfficialCodeStyle(project)
if (!isFirPlugin) {
// We do it here to avoid possible initialization problems
// UnusedSymbolInspection() calls IDEA UnusedDeclarationInspection() in static initializer,
// which in turn registers some extensions provoking "modifications aren't allowed during highlighting"
// when done lazily
UnusedSymbolInspection()
}
VfsRootAccess.allowRootAccess(myFixture.testRootDisposable, KotlinRoot.DIR.path)
EditorTracker.getInstance(project)
invalidateLibraryCache(project)
}
override fun runBare(testRunnable: ThrowableRunnable<Throwable>) {
if (captureExceptions) {
LoggedErrorProcessor.executeWith<RuntimeException>(object : LoggedErrorProcessor() {
override fun processError(category: String, message: String, details: Array<out String>, t: Throwable?): Set<Action> {
exceptions.addIfNotNull(t)
return super.processError(category, message, details, t)
}
}) {
super.runBare(testRunnable)
}
}
else {
super.runBare(testRunnable)
}
}
override fun tearDown() {
runAll(
{ runCatching { project }.getOrNull()?.let { disableKotlinOfficialCodeStyle(it) } },
{ super.tearDown() },
)
if (exceptions.isNotEmpty()) {
exceptions.forEach { it.printStackTrace() }
throw AssertionError("Exceptions in other threads happened")
}
}
override fun getProjectDescriptor(): LightProjectDescriptor = getProjectDescriptorFromFileDirective()
protected fun getProjectDescriptorFromAnnotation(): LightProjectDescriptor {
val testMethod = this::class.java.getDeclaredMethod(name)
return when (testMethod.getAnnotation(ProjectDescriptorKind::class.java)?.value) {
JDK_AND_MULTIPLATFORM_STDLIB_WITH_SOURCES -> KotlinJdkAndMultiplatformStdlibDescriptor.JDK_AND_MULTIPLATFORM_STDLIB_WITH_SOURCES
KOTLIN_JVM_WITH_STDLIB_SOURCES -> ProjectDescriptorWithStdlibSources.INSTANCE
KOTLIN_JAVASCRIPT -> KotlinStdJSProjectDescriptor
KOTLIN_JVM_WITH_STDLIB_SOURCES_WITH_ADDITIONAL_JS -> {
KotlinMultiModuleProjectDescriptor(
KOTLIN_JVM_WITH_STDLIB_SOURCES_WITH_ADDITIONAL_JS,
mainModuleDescriptor = ProjectDescriptorWithStdlibSources.INSTANCE,
additionalModuleDescriptor = KotlinStdJSProjectDescriptor
)
}
KOTLIN_JAVASCRIPT_WITH_ADDITIONAL_JVM_WITH_STDLIB -> {
KotlinMultiModuleProjectDescriptor(
KOTLIN_JAVASCRIPT_WITH_ADDITIONAL_JVM_WITH_STDLIB,
mainModuleDescriptor = KotlinStdJSProjectDescriptor,
additionalModuleDescriptor = ProjectDescriptorWithStdlibSources.INSTANCE
)
}
else -> throw IllegalStateException("Unknown value for project descriptor kind")
}
}
protected fun getProjectDescriptorFromTestName(): LightProjectDescriptor {
val testName = StringUtil.toLowerCase(getTestName(false))
return when {
testName.endsWith("runtime") -> KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
testName.endsWith("stdlib") -> ProjectDescriptorWithStdlibSources.INSTANCE
else -> KotlinLightProjectDescriptor.INSTANCE
}
}
protected fun getProjectDescriptorFromFileDirective(): LightProjectDescriptor {
val file = mainFile()
if (!file.exists()) {
return KotlinLightProjectDescriptor.INSTANCE
}
try {
val fileText = FileUtil.loadFile(file, true)
val withLibraryDirective = InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, "WITH_LIBRARY:")
val minJavaVersion = InTextDirectivesUtils.findStringWithPrefixes(fileText, "MIN_JAVA_VERSION:")?.toInt()
if (minJavaVersion != null && !(InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME") ||
InTextDirectivesUtils.isDirectiveDefined(fileText, "WITH_STDLIB"))
) {
error("MIN_JAVA_VERSION so far is supported for RUNTIME/WITH_STDLIB only")
}
return when {
withLibraryDirective.isNotEmpty() ->
SdkAndMockLibraryProjectDescriptor(IDEA_TEST_DATA_DIR.resolve(withLibraryDirective[0]).path, true)
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_SOURCES") ->
ProjectDescriptorWithStdlibSources.INSTANCE
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITHOUT_SOURCES") ->
ProjectDescriptorWithStdlibSources.INSTANCE_NO_SOURCES
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_KOTLIN_TEST") ->
KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_WITH_KOTLIN_TEST
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_FULL_JDK") ->
KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_FULL_JDK
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_JDK_10") ->
KotlinWithJdkAndRuntimeLightProjectDescriptor.getInstance(LanguageLevel.JDK_10)
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_REFLECT") ->
KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_WITH_REFLECT
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_SCRIPT_RUNTIME") ->
KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_WITH_SCRIPT_RUNTIME
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_STDLIB_JDK8") ->
KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_WITH_STDLIB_JDK8
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME") ||
InTextDirectivesUtils.isDirectiveDefined(fileText, "WITH_STDLIB") ->
if (minJavaVersion != null) {
object : KotlinWithJdkAndRuntimeLightProjectDescriptor(INSTANCE.libraryFiles, INSTANCE.librarySourceFiles) {
val sdkValue by lazy { sdk(minJavaVersion) }
override fun getSdk(): Sdk = sdkValue
}
} else {
KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
}
InTextDirectivesUtils.isDirectiveDefined(fileText, "JS") ->
KotlinStdJSProjectDescriptor
InTextDirectivesUtils.isDirectiveDefined(fileText, "ENABLE_MULTIPLATFORM") ->
KotlinProjectDescriptorWithFacet.KOTLIN_STABLE_WITH_MULTIPLATFORM
else -> getDefaultProjectDescriptor()
}
} catch (e: IOException) {
throw rethrow(e)
}
}
protected open fun mainFile() = File(testDataDirectory, fileName())
private fun sdk(javaVersion: Int): Sdk = when (javaVersion) {
6 -> IdeaTestUtil.getMockJdk16()
8 -> IdeaTestUtil.getMockJdk18()
9 -> IdeaTestUtil.getMockJdk9()
11 -> {
if (SystemInfo.isJavaVersionAtLeast(javaVersion, 0, 0)) {
PluginTestCaseBase.fullJdk()
} else {
error("JAVA_HOME have to point at least to JDK 11")
}
}
else -> error("Unsupported JDK version $javaVersion")
}
protected open fun getDefaultProjectDescriptor(): KotlinLightProjectDescriptor = KotlinLightProjectDescriptor.INSTANCE
protected fun performNotWriteEditorAction(actionId: String): Boolean {
val dataContext = (myFixture.editor as EditorEx).dataContext
val managerEx = ActionManagerEx.getInstanceEx()
val action = managerEx.getAction(actionId)
val event = AnActionEvent(null, dataContext, ActionPlaces.UNKNOWN, Presentation(), managerEx, 0)
if (ActionUtil.lastUpdateAndCheckDumb(action, event, false)) {
ActionUtil.performActionDumbAwareWithCallbacks(action, event)
return true
}
return false
}
fun JavaCodeInsightTestFixture.configureByFile(file: File): PsiFile {
val relativePath = file.toRelativeString(testDataDirectory)
return configureByFile(relativePath)
}
fun JavaCodeInsightTestFixture.configureByFiles(vararg file: File): List<PsiFile> {
val relativePaths = file.map { it.toRelativeString(testDataDirectory) }.toTypedArray()
return configureByFiles(*relativePaths).toList()
}
fun JavaCodeInsightTestFixture.checkResultByFile(file: File) {
val relativePath = file.toRelativeString(testDataDirectory)
checkResultByFile(relativePath)
}
}
object CompilerTestDirectives {
const val LANGUAGE_VERSION_DIRECTIVE = "LANGUAGE_VERSION:"
const val API_VERSION_DIRECTIVE = "API_VERSION:"
const val JVM_TARGET_DIRECTIVE = "JVM_TARGET:"
const val COMPILER_ARGUMENTS_DIRECTIVE = "COMPILER_ARGUMENTS:"
val ALL_COMPILER_TEST_DIRECTIVES = listOf(LANGUAGE_VERSION_DIRECTIVE, JVM_TARGET_DIRECTIVE, COMPILER_ARGUMENTS_DIRECTIVE)
}
fun <T> withCustomCompilerOptions(fileText: String, project: Project, module: Module, body: () -> T): T {
val removeFacet = !module.hasKotlinFacet()
val configured = configureCompilerOptions(fileText, project, module)
try {
return body()
} finally {
if (configured) {
rollbackCompilerOptions(project, module, removeFacet)
}
}
}
private fun configureCompilerOptions(fileText: String, project: Project, module: Module): Boolean {
val rawLanguageVersion = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// $LANGUAGE_VERSION_DIRECTIVE ")
val rawApiVersion = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// $API_VERSION_DIRECTIVE ")
val jvmTarget = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// $JVM_TARGET_DIRECTIVE ")
// We can have several such directives in quickFixMultiFile tests
// TODO: refactor such tests or add sophisticated check for the directive
val options = InTextDirectivesUtils.findListWithPrefixes(fileText, "// $COMPILER_ARGUMENTS_DIRECTIVE ").firstOrNull()
val languageVersion = rawLanguageVersion?.let { LanguageVersion.fromVersionString(rawLanguageVersion) }
val apiVersion = rawApiVersion?.let { ApiVersion.parse(rawApiVersion) }
if (languageVersion != null || apiVersion != null || jvmTarget != null || options != null) {
configureLanguageAndApiVersion(
project, module,
languageVersion ?: KotlinPluginLayout.standaloneCompilerVersion.languageVersion,
apiVersion
)
val facetSettings = KotlinFacet.get(module)!!.configuration.settings
if (jvmTarget != null) {
val compilerArguments = facetSettings.compilerArguments
require(compilerArguments is K2JVMCompilerArguments) { "Attempt to specify `$JVM_TARGET_DIRECTIVE` for non-JVM test" }
compilerArguments.jvmTarget = jvmTarget
}
if (options != null) {
val compilerSettings = facetSettings.compilerSettings ?: CompilerSettings().also {
facetSettings.compilerSettings = it
}
compilerSettings.additionalArguments = options
facetSettings.updateMergedArguments()
KotlinCompilerSettings.getInstance(project).update { this.additionalArguments = options }
}
return true
}
return false
}
fun configureRegistryAndRun(fileText: String, body: () -> Unit) {
val registers = InTextDirectivesUtils.findListWithPrefixes(fileText, "// REGISTRY:")
.map { it.split(' ') }
.map { Registry.get(it.first()) to it.last() }
try {
for ((register, value) in registers) {
register.setValue(value)
}
body()
} finally {
for ((register, _) in registers) {
register.resetToDefault()
}
}
}
fun configureCodeStyleAndRun(
project: Project,
configurator: (CodeStyleSettings) -> Unit = { },
body: () -> Unit
) {
val testSettings = CodeStyle.createTestSettings(CodeStyle.getSettings(project))
CodeStyle.doWithTemporarySettings(project, testSettings, Runnable {
configurator(testSettings)
body()
})
}
fun enableKotlinOfficialCodeStyle(project: Project) {
val settings = CodeStyleSettingsManager.getInstance(project).createTemporarySettings()
KotlinStyleGuideCodeStyle.apply(settings)
CodeStyle.setTemporarySettings(project, settings)
}
fun disableKotlinOfficialCodeStyle(project: Project) {
CodeStyle.dropTemporarySettings(project)
}
fun resetCodeStyle(project: Project) {
val provider = KotlinLanguageCodeStyleSettingsProvider()
CodeStyle.getSettings(project).apply {
removeCommonSettings(provider)
removeCustomSettings(provider)
clearCodeStyleSettings()
}
}
fun runAll(
vararg actions: ThrowableRunnable<Throwable>,
suppressedExceptions: List<Throwable> = emptyList()
) = RunAll(actions.toList()).run(suppressedExceptions)
private fun rollbackCompilerOptions(project: Project, module: Module, removeFacet: Boolean) {
KotlinCompilerSettings.getInstance(project).update { this.additionalArguments = DEFAULT_ADDITIONAL_ARGUMENTS }
val bundledKotlinVersion = KotlinPluginLayout.standaloneCompilerVersion
KotlinCommonCompilerArgumentsHolder.getInstance(project).update {
this.languageVersion = bundledKotlinVersion.languageVersion.versionString
}
if (removeFacet) {
module.removeKotlinFacet(ProjectDataManager.getInstance().createModifiableModelsProvider(project), commitModel = true)
return
}
configureLanguageAndApiVersion(
project,
module,
bundledKotlinVersion.languageVersion,
bundledKotlinVersion.apiVersion
)
val facetSettings = KotlinFacet.get(module)!!.configuration.settings
(facetSettings.compilerArguments as? K2JVMCompilerArguments)?.jvmTarget = JvmTarget.DEFAULT.description
val compilerSettings = facetSettings.compilerSettings ?: CompilerSettings().also {
facetSettings.compilerSettings = it
}
compilerSettings.additionalArguments = DEFAULT_ADDITIONAL_ARGUMENTS
facetSettings.updateMergedArguments()
}
fun withCustomLanguageAndApiVersion(
project: Project,
module: Module,
languageVersion: LanguageVersion,
apiVersion: ApiVersion?,
body: () -> Unit
) {
val removeFacet = !module.hasKotlinFacet()
configureLanguageAndApiVersion(project, module, languageVersion, apiVersion)
try {
body()
} finally {
val bundledCompilerVersion = KotlinPluginLayout.standaloneCompilerVersion
if (removeFacet) {
KotlinCommonCompilerArgumentsHolder.getInstance(project)
.update { this.languageVersion = bundledCompilerVersion.languageVersion.versionString }
module.removeKotlinFacet(ProjectDataManager.getInstance().createModifiableModelsProvider(project), commitModel = true)
} else {
configureLanguageAndApiVersion(
project,
module,
bundledCompilerVersion.languageVersion,
bundledCompilerVersion.apiVersion
)
}
}
}
private fun configureLanguageAndApiVersion(
project: Project,
module: Module,
languageVersion: LanguageVersion,
apiVersion: ApiVersion?
) {
WriteAction.run<Throwable> {
val modelsProvider = ProjectDataManager.getInstance().createModifiableModelsProvider(project)
val facet = module.getOrCreateFacet(modelsProvider, useProjectSettings = false)
val compilerArguments = facet.configuration.settings.compilerArguments
if (compilerArguments != null) {
compilerArguments.apiVersion = null
}
facet.configureFacet(IdeKotlinVersion.fromLanguageVersion(languageVersion), null, modelsProvider, emptySet())
if (apiVersion != null) {
facet.configuration.settings.apiLevel = LanguageVersion.fromVersionString(apiVersion.versionString)
}
KotlinCommonCompilerArgumentsHolder.getInstance(project).update { this.languageVersion = languageVersion.versionString }
modelsProvider.commit()
}
}
fun Project.allKotlinFiles(): List<KtFile> {
val virtualFiles = FileTypeIndex.getFiles(KotlinFileType.INSTANCE, ProjectScope.getProjectScope(this))
return virtualFiles
.map { PsiManager.getInstance(this).findFile(it) }
.filterIsInstance<KtFile>()
}
fun Project.allJavaFiles(): List<PsiJavaFile> {
val virtualFiles = FileTypeIndex.getFiles(JavaFileType.INSTANCE, ProjectScope.getProjectScope(this))
return virtualFiles
.map { PsiManager.getInstance(this).findFile(it) }
.filterIsInstance<PsiJavaFile>()
}
fun Project.findFileWithCaret(): PsiClassOwner {
return (allKotlinFiles() + allJavaFiles()).single {
"<caret>" in VfsUtilCore.loadText(it.virtualFile) && !it.virtualFile.name.endsWith(".after")
}
}
fun createTextEditorBasedDataContext(
project: Project,
editor: Editor,
caret: Caret,
additionalSteps: SimpleDataContext.Builder.() -> SimpleDataContext.Builder = { this },
): DataContext {
val parentContext = CaretSpecificDataContext.create(EditorUtil.getEditorDataContext(editor), caret)
assertEquals(project, parentContext.getData(CommonDataKeys.PROJECT));
assertEquals(editor, parentContext.getData(CommonDataKeys.EDITOR));
return SimpleDataContext.builder()
.additionalSteps()
.setParent(parentContext)
.build()
}
| apache-2.0 | 5c6a0099c93aa3d2bb1a9bb0b581d5fb | 42.003731 | 140 | 0.71718 | 5.562259 | false | true | false | false |
google/accompanist | insets-ui/src/main/java/com/google/accompanist/insets/ui/TopAppBar.kt | 1 | 3377 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.accompanist.insets.ui
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.padding
import androidx.compose.material.AppBarDefaults
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.TopAppBar
import androidx.compose.material.contentColorFor
import androidx.compose.material.primarySurface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
/**
* A wrapper around [TopAppBar] which supports the setting of [contentPadding] to add
* internal padding. This is especially useful in conjunction with insets.
*
* For an edge-to-edge layout, typically you would use the
* [com.google.accompanist.insets.WindowInsets.systemBars] insets like so below:
*
* @sample com.google.accompanist.sample.insets.TopAppBar_Insets
*/
@Composable
fun TopAppBar(
title: @Composable () -> Unit,
modifier: Modifier = Modifier,
contentPadding: PaddingValues = PaddingValues(0.dp),
navigationIcon: @Composable (() -> Unit)? = null,
actions: @Composable RowScope.() -> Unit = {},
backgroundColor: Color = MaterialTheme.colors.primarySurface,
contentColor: Color = contentColorFor(backgroundColor),
elevation: Dp = AppBarDefaults.TopAppBarElevation,
) {
TopAppBarSurface(
modifier = modifier,
backgroundColor = backgroundColor,
contentColor = contentColor,
elevation = elevation
) {
TopAppBarContent(
title = title,
navigationIcon = navigationIcon,
actions = actions,
modifier = Modifier.padding(contentPadding)
)
}
}
@Composable
fun TopAppBarSurface(
modifier: Modifier = Modifier,
backgroundColor: Color = MaterialTheme.colors.primarySurface,
contentColor: Color = contentColorFor(backgroundColor),
elevation: Dp = AppBarDefaults.TopAppBarElevation,
content: @Composable () -> Unit,
) {
Surface(
color = backgroundColor,
contentColor = contentColor,
elevation = elevation,
modifier = modifier,
content = content
)
}
@Composable
fun TopAppBarContent(
title: @Composable () -> Unit,
modifier: Modifier = Modifier,
navigationIcon: @Composable (() -> Unit)? = null,
actions: @Composable RowScope.() -> Unit = {},
) {
TopAppBar(
title = title,
navigationIcon = navigationIcon,
actions = actions,
backgroundColor = Color.Transparent,
elevation = 0.dp,
modifier = modifier
)
}
| apache-2.0 | dc2b0bc739fd67e489a526cf11342549 | 32.435644 | 85 | 0.716316 | 4.670816 | false | false | false | false |
Philip-Trettner/GlmKt | GlmKt/src/glm/vec/Byte/MutableByteVec4.kt | 1 | 51547 | package glm
data class MutableByteVec4(var x: Byte, var y: Byte, var z: Byte, var w: Byte) {
// Initializes each element by evaluating init from 0 until 3
constructor(init: (Int) -> Byte) : this(init(0), init(1), init(2), init(3))
operator fun get(idx: Int): Byte = when (idx) {
0 -> x
1 -> y
2 -> z
3 -> w
else -> throw IndexOutOfBoundsException("index $idx is out of bounds")
}
operator fun set(idx: Int, value: Byte) = when (idx) {
0 -> x = value
1 -> y = value
2 -> z = value
3 -> w = value
else -> throw IndexOutOfBoundsException("index $idx is out of bounds")
}
// Operators
operator fun inc(): MutableByteVec4 = MutableByteVec4(x.inc(), y.inc(), z.inc(), w.inc())
operator fun dec(): MutableByteVec4 = MutableByteVec4(x.dec(), y.dec(), z.dec(), w.dec())
operator fun unaryPlus(): MutableIntVec4 = MutableIntVec4(+x, +y, +z, +w)
operator fun unaryMinus(): MutableIntVec4 = MutableIntVec4(-x, -y, -z, -w)
operator fun plus(rhs: MutableByteVec4): MutableIntVec4 = MutableIntVec4(x + rhs.x, y + rhs.y, z + rhs.z, w + rhs.w)
operator fun minus(rhs: MutableByteVec4): MutableIntVec4 = MutableIntVec4(x - rhs.x, y - rhs.y, z - rhs.z, w - rhs.w)
operator fun times(rhs: MutableByteVec4): MutableIntVec4 = MutableIntVec4(x * rhs.x, y * rhs.y, z * rhs.z, w * rhs.w)
operator fun div(rhs: MutableByteVec4): MutableIntVec4 = MutableIntVec4(x / rhs.x, y / rhs.y, z / rhs.z, w / rhs.w)
operator fun rem(rhs: MutableByteVec4): MutableIntVec4 = MutableIntVec4(x % rhs.x, y % rhs.y, z % rhs.z, w % rhs.w)
operator fun plus(rhs: Byte): MutableIntVec4 = MutableIntVec4(x + rhs, y + rhs, z + rhs, w + rhs)
operator fun minus(rhs: Byte): MutableIntVec4 = MutableIntVec4(x - rhs, y - rhs, z - rhs, w - rhs)
operator fun times(rhs: Byte): MutableIntVec4 = MutableIntVec4(x * rhs, y * rhs, z * rhs, w * rhs)
operator fun div(rhs: Byte): MutableIntVec4 = MutableIntVec4(x / rhs, y / rhs, z / rhs, w / rhs)
operator fun rem(rhs: Byte): MutableIntVec4 = MutableIntVec4(x % rhs, y % rhs, z % rhs, w % rhs)
inline fun map(func: (Byte) -> Byte): MutableByteVec4 = MutableByteVec4(func(x), func(y), func(z), func(w))
fun toList(): List<Byte> = listOf(x, y, z, w)
// Predefined vector constants
companion object Constants {
val zero: MutableByteVec4 get() = MutableByteVec4(0.toByte(), 0.toByte(), 0.toByte(), 0.toByte())
val ones: MutableByteVec4 get() = MutableByteVec4(1.toByte(), 1.toByte(), 1.toByte(), 1.toByte())
val unitX: MutableByteVec4 get() = MutableByteVec4(1.toByte(), 0.toByte(), 0.toByte(), 0.toByte())
val unitY: MutableByteVec4 get() = MutableByteVec4(0.toByte(), 1.toByte(), 0.toByte(), 0.toByte())
val unitZ: MutableByteVec4 get() = MutableByteVec4(0.toByte(), 0.toByte(), 1.toByte(), 0.toByte())
val unitW: MutableByteVec4 get() = MutableByteVec4(0.toByte(), 0.toByte(), 0.toByte(), 1.toByte())
}
// Conversions to Float
fun toVec(): Vec4 = Vec4(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat())
inline fun toVec(conv: (Byte) -> Float): Vec4 = Vec4(conv(x), conv(y), conv(z), conv(w))
fun toVec2(): Vec2 = Vec2(x.toFloat(), y.toFloat())
inline fun toVec2(conv: (Byte) -> Float): Vec2 = Vec2(conv(x), conv(y))
fun toVec3(): Vec3 = Vec3(x.toFloat(), y.toFloat(), z.toFloat())
inline fun toVec3(conv: (Byte) -> Float): Vec3 = Vec3(conv(x), conv(y), conv(z))
fun toVec4(): Vec4 = Vec4(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat())
inline fun toVec4(conv: (Byte) -> Float): Vec4 = Vec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Float
fun toMutableVec(): MutableVec4 = MutableVec4(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat())
inline fun toMutableVec(conv: (Byte) -> Float): MutableVec4 = MutableVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableVec2(): MutableVec2 = MutableVec2(x.toFloat(), y.toFloat())
inline fun toMutableVec2(conv: (Byte) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y))
fun toMutableVec3(): MutableVec3 = MutableVec3(x.toFloat(), y.toFloat(), z.toFloat())
inline fun toMutableVec3(conv: (Byte) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), conv(z))
fun toMutableVec4(): MutableVec4 = MutableVec4(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat())
inline fun toMutableVec4(conv: (Byte) -> Float): MutableVec4 = MutableVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Double
fun toDoubleVec(): DoubleVec4 = DoubleVec4(x.toDouble(), y.toDouble(), z.toDouble(), w.toDouble())
inline fun toDoubleVec(conv: (Byte) -> Double): DoubleVec4 = DoubleVec4(conv(x), conv(y), conv(z), conv(w))
fun toDoubleVec2(): DoubleVec2 = DoubleVec2(x.toDouble(), y.toDouble())
inline fun toDoubleVec2(conv: (Byte) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y))
fun toDoubleVec3(): DoubleVec3 = DoubleVec3(x.toDouble(), y.toDouble(), z.toDouble())
inline fun toDoubleVec3(conv: (Byte) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), conv(z))
fun toDoubleVec4(): DoubleVec4 = DoubleVec4(x.toDouble(), y.toDouble(), z.toDouble(), w.toDouble())
inline fun toDoubleVec4(conv: (Byte) -> Double): DoubleVec4 = DoubleVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Double
fun toMutableDoubleVec(): MutableDoubleVec4 = MutableDoubleVec4(x.toDouble(), y.toDouble(), z.toDouble(), w.toDouble())
inline fun toMutableDoubleVec(conv: (Byte) -> Double): MutableDoubleVec4 = MutableDoubleVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableDoubleVec2(): MutableDoubleVec2 = MutableDoubleVec2(x.toDouble(), y.toDouble())
inline fun toMutableDoubleVec2(conv: (Byte) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y))
fun toMutableDoubleVec3(): MutableDoubleVec3 = MutableDoubleVec3(x.toDouble(), y.toDouble(), z.toDouble())
inline fun toMutableDoubleVec3(conv: (Byte) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), conv(z))
fun toMutableDoubleVec4(): MutableDoubleVec4 = MutableDoubleVec4(x.toDouble(), y.toDouble(), z.toDouble(), w.toDouble())
inline fun toMutableDoubleVec4(conv: (Byte) -> Double): MutableDoubleVec4 = MutableDoubleVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Int
fun toIntVec(): IntVec4 = IntVec4(x.toInt(), y.toInt(), z.toInt(), w.toInt())
inline fun toIntVec(conv: (Byte) -> Int): IntVec4 = IntVec4(conv(x), conv(y), conv(z), conv(w))
fun toIntVec2(): IntVec2 = IntVec2(x.toInt(), y.toInt())
inline fun toIntVec2(conv: (Byte) -> Int): IntVec2 = IntVec2(conv(x), conv(y))
fun toIntVec3(): IntVec3 = IntVec3(x.toInt(), y.toInt(), z.toInt())
inline fun toIntVec3(conv: (Byte) -> Int): IntVec3 = IntVec3(conv(x), conv(y), conv(z))
fun toIntVec4(): IntVec4 = IntVec4(x.toInt(), y.toInt(), z.toInt(), w.toInt())
inline fun toIntVec4(conv: (Byte) -> Int): IntVec4 = IntVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Int
fun toMutableIntVec(): MutableIntVec4 = MutableIntVec4(x.toInt(), y.toInt(), z.toInt(), w.toInt())
inline fun toMutableIntVec(conv: (Byte) -> Int): MutableIntVec4 = MutableIntVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableIntVec2(): MutableIntVec2 = MutableIntVec2(x.toInt(), y.toInt())
inline fun toMutableIntVec2(conv: (Byte) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y))
fun toMutableIntVec3(): MutableIntVec3 = MutableIntVec3(x.toInt(), y.toInt(), z.toInt())
inline fun toMutableIntVec3(conv: (Byte) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), conv(z))
fun toMutableIntVec4(): MutableIntVec4 = MutableIntVec4(x.toInt(), y.toInt(), z.toInt(), w.toInt())
inline fun toMutableIntVec4(conv: (Byte) -> Int): MutableIntVec4 = MutableIntVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Long
fun toLongVec(): LongVec4 = LongVec4(x.toLong(), y.toLong(), z.toLong(), w.toLong())
inline fun toLongVec(conv: (Byte) -> Long): LongVec4 = LongVec4(conv(x), conv(y), conv(z), conv(w))
fun toLongVec2(): LongVec2 = LongVec2(x.toLong(), y.toLong())
inline fun toLongVec2(conv: (Byte) -> Long): LongVec2 = LongVec2(conv(x), conv(y))
fun toLongVec3(): LongVec3 = LongVec3(x.toLong(), y.toLong(), z.toLong())
inline fun toLongVec3(conv: (Byte) -> Long): LongVec3 = LongVec3(conv(x), conv(y), conv(z))
fun toLongVec4(): LongVec4 = LongVec4(x.toLong(), y.toLong(), z.toLong(), w.toLong())
inline fun toLongVec4(conv: (Byte) -> Long): LongVec4 = LongVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Long
fun toMutableLongVec(): MutableLongVec4 = MutableLongVec4(x.toLong(), y.toLong(), z.toLong(), w.toLong())
inline fun toMutableLongVec(conv: (Byte) -> Long): MutableLongVec4 = MutableLongVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableLongVec2(): MutableLongVec2 = MutableLongVec2(x.toLong(), y.toLong())
inline fun toMutableLongVec2(conv: (Byte) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y))
fun toMutableLongVec3(): MutableLongVec3 = MutableLongVec3(x.toLong(), y.toLong(), z.toLong())
inline fun toMutableLongVec3(conv: (Byte) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), conv(z))
fun toMutableLongVec4(): MutableLongVec4 = MutableLongVec4(x.toLong(), y.toLong(), z.toLong(), w.toLong())
inline fun toMutableLongVec4(conv: (Byte) -> Long): MutableLongVec4 = MutableLongVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Short
fun toShortVec(): ShortVec4 = ShortVec4(x.toShort(), y.toShort(), z.toShort(), w.toShort())
inline fun toShortVec(conv: (Byte) -> Short): ShortVec4 = ShortVec4(conv(x), conv(y), conv(z), conv(w))
fun toShortVec2(): ShortVec2 = ShortVec2(x.toShort(), y.toShort())
inline fun toShortVec2(conv: (Byte) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y))
fun toShortVec3(): ShortVec3 = ShortVec3(x.toShort(), y.toShort(), z.toShort())
inline fun toShortVec3(conv: (Byte) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), conv(z))
fun toShortVec4(): ShortVec4 = ShortVec4(x.toShort(), y.toShort(), z.toShort(), w.toShort())
inline fun toShortVec4(conv: (Byte) -> Short): ShortVec4 = ShortVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Short
fun toMutableShortVec(): MutableShortVec4 = MutableShortVec4(x.toShort(), y.toShort(), z.toShort(), w.toShort())
inline fun toMutableShortVec(conv: (Byte) -> Short): MutableShortVec4 = MutableShortVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableShortVec2(): MutableShortVec2 = MutableShortVec2(x.toShort(), y.toShort())
inline fun toMutableShortVec2(conv: (Byte) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y))
fun toMutableShortVec3(): MutableShortVec3 = MutableShortVec3(x.toShort(), y.toShort(), z.toShort())
inline fun toMutableShortVec3(conv: (Byte) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), conv(z))
fun toMutableShortVec4(): MutableShortVec4 = MutableShortVec4(x.toShort(), y.toShort(), z.toShort(), w.toShort())
inline fun toMutableShortVec4(conv: (Byte) -> Short): MutableShortVec4 = MutableShortVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Byte
fun toByteVec(): ByteVec4 = ByteVec4(x, y, z, w)
inline fun toByteVec(conv: (Byte) -> Byte): ByteVec4 = ByteVec4(conv(x), conv(y), conv(z), conv(w))
fun toByteVec2(): ByteVec2 = ByteVec2(x, y)
inline fun toByteVec2(conv: (Byte) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y))
fun toByteVec3(): ByteVec3 = ByteVec3(x, y, z)
inline fun toByteVec3(conv: (Byte) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), conv(z))
fun toByteVec4(): ByteVec4 = ByteVec4(x, y, z, w)
inline fun toByteVec4(conv: (Byte) -> Byte): ByteVec4 = ByteVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Byte
fun toMutableByteVec(): MutableByteVec4 = MutableByteVec4(x, y, z, w)
inline fun toMutableByteVec(conv: (Byte) -> Byte): MutableByteVec4 = MutableByteVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableByteVec2(): MutableByteVec2 = MutableByteVec2(x, y)
inline fun toMutableByteVec2(conv: (Byte) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y))
fun toMutableByteVec3(): MutableByteVec3 = MutableByteVec3(x, y, z)
inline fun toMutableByteVec3(conv: (Byte) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), conv(z))
fun toMutableByteVec4(): MutableByteVec4 = MutableByteVec4(x, y, z, w)
inline fun toMutableByteVec4(conv: (Byte) -> Byte): MutableByteVec4 = MutableByteVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Char
fun toCharVec(): CharVec4 = CharVec4(x.toChar(), y.toChar(), z.toChar(), w.toChar())
inline fun toCharVec(conv: (Byte) -> Char): CharVec4 = CharVec4(conv(x), conv(y), conv(z), conv(w))
fun toCharVec2(): CharVec2 = CharVec2(x.toChar(), y.toChar())
inline fun toCharVec2(conv: (Byte) -> Char): CharVec2 = CharVec2(conv(x), conv(y))
fun toCharVec3(): CharVec3 = CharVec3(x.toChar(), y.toChar(), z.toChar())
inline fun toCharVec3(conv: (Byte) -> Char): CharVec3 = CharVec3(conv(x), conv(y), conv(z))
fun toCharVec4(): CharVec4 = CharVec4(x.toChar(), y.toChar(), z.toChar(), w.toChar())
inline fun toCharVec4(conv: (Byte) -> Char): CharVec4 = CharVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Char
fun toMutableCharVec(): MutableCharVec4 = MutableCharVec4(x.toChar(), y.toChar(), z.toChar(), w.toChar())
inline fun toMutableCharVec(conv: (Byte) -> Char): MutableCharVec4 = MutableCharVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableCharVec2(): MutableCharVec2 = MutableCharVec2(x.toChar(), y.toChar())
inline fun toMutableCharVec2(conv: (Byte) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y))
fun toMutableCharVec3(): MutableCharVec3 = MutableCharVec3(x.toChar(), y.toChar(), z.toChar())
inline fun toMutableCharVec3(conv: (Byte) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), conv(z))
fun toMutableCharVec4(): MutableCharVec4 = MutableCharVec4(x.toChar(), y.toChar(), z.toChar(), w.toChar())
inline fun toMutableCharVec4(conv: (Byte) -> Char): MutableCharVec4 = MutableCharVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Boolean
fun toBoolVec(): BoolVec4 = BoolVec4(x != 0.toByte(), y != 0.toByte(), z != 0.toByte(), w != 0.toByte())
inline fun toBoolVec(conv: (Byte) -> Boolean): BoolVec4 = BoolVec4(conv(x), conv(y), conv(z), conv(w))
fun toBoolVec2(): BoolVec2 = BoolVec2(x != 0.toByte(), y != 0.toByte())
inline fun toBoolVec2(conv: (Byte) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y))
fun toBoolVec3(): BoolVec3 = BoolVec3(x != 0.toByte(), y != 0.toByte(), z != 0.toByte())
inline fun toBoolVec3(conv: (Byte) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), conv(z))
fun toBoolVec4(): BoolVec4 = BoolVec4(x != 0.toByte(), y != 0.toByte(), z != 0.toByte(), w != 0.toByte())
inline fun toBoolVec4(conv: (Byte) -> Boolean): BoolVec4 = BoolVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Boolean
fun toMutableBoolVec(): MutableBoolVec4 = MutableBoolVec4(x != 0.toByte(), y != 0.toByte(), z != 0.toByte(), w != 0.toByte())
inline fun toMutableBoolVec(conv: (Byte) -> Boolean): MutableBoolVec4 = MutableBoolVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableBoolVec2(): MutableBoolVec2 = MutableBoolVec2(x != 0.toByte(), y != 0.toByte())
inline fun toMutableBoolVec2(conv: (Byte) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y))
fun toMutableBoolVec3(): MutableBoolVec3 = MutableBoolVec3(x != 0.toByte(), y != 0.toByte(), z != 0.toByte())
inline fun toMutableBoolVec3(conv: (Byte) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), conv(z))
fun toMutableBoolVec4(): MutableBoolVec4 = MutableBoolVec4(x != 0.toByte(), y != 0.toByte(), z != 0.toByte(), w != 0.toByte())
inline fun toMutableBoolVec4(conv: (Byte) -> Boolean): MutableBoolVec4 = MutableBoolVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to String
fun toStringVec(): StringVec4 = StringVec4(x.toString(), y.toString(), z.toString(), w.toString())
inline fun toStringVec(conv: (Byte) -> String): StringVec4 = StringVec4(conv(x), conv(y), conv(z), conv(w))
fun toStringVec2(): StringVec2 = StringVec2(x.toString(), y.toString())
inline fun toStringVec2(conv: (Byte) -> String): StringVec2 = StringVec2(conv(x), conv(y))
fun toStringVec3(): StringVec3 = StringVec3(x.toString(), y.toString(), z.toString())
inline fun toStringVec3(conv: (Byte) -> String): StringVec3 = StringVec3(conv(x), conv(y), conv(z))
fun toStringVec4(): StringVec4 = StringVec4(x.toString(), y.toString(), z.toString(), w.toString())
inline fun toStringVec4(conv: (Byte) -> String): StringVec4 = StringVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to String
fun toMutableStringVec(): MutableStringVec4 = MutableStringVec4(x.toString(), y.toString(), z.toString(), w.toString())
inline fun toMutableStringVec(conv: (Byte) -> String): MutableStringVec4 = MutableStringVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableStringVec2(): MutableStringVec2 = MutableStringVec2(x.toString(), y.toString())
inline fun toMutableStringVec2(conv: (Byte) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y))
fun toMutableStringVec3(): MutableStringVec3 = MutableStringVec3(x.toString(), y.toString(), z.toString())
inline fun toMutableStringVec3(conv: (Byte) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), conv(z))
fun toMutableStringVec4(): MutableStringVec4 = MutableStringVec4(x.toString(), y.toString(), z.toString(), w.toString())
inline fun toMutableStringVec4(conv: (Byte) -> String): MutableStringVec4 = MutableStringVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to T2
inline fun <T2> toTVec(conv: (Byte) -> T2): TVec4<T2> = TVec4<T2>(conv(x), conv(y), conv(z), conv(w))
inline fun <T2> toTVec2(conv: (Byte) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y))
inline fun <T2> toTVec3(conv: (Byte) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), conv(z))
inline fun <T2> toTVec4(conv: (Byte) -> T2): TVec4<T2> = TVec4<T2>(conv(x), conv(y), conv(z), conv(w))
// Conversions to T2
inline fun <T2> toMutableTVec(conv: (Byte) -> T2): MutableTVec4<T2> = MutableTVec4<T2>(conv(x), conv(y), conv(z), conv(w))
inline fun <T2> toMutableTVec2(conv: (Byte) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y))
inline fun <T2> toMutableTVec3(conv: (Byte) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), conv(z))
inline fun <T2> toMutableTVec4(conv: (Byte) -> T2): MutableTVec4<T2> = MutableTVec4<T2>(conv(x), conv(y), conv(z), conv(w))
// Allows for swizzling, e.g. v.swizzle.xzx
inner class Swizzle {
val xx: MutableByteVec2 get() = MutableByteVec2(x, x)
var xy: MutableByteVec2
get() = MutableByteVec2(x, y)
set(value) {
x = value.x
y = value.y
}
var xz: MutableByteVec2
get() = MutableByteVec2(x, z)
set(value) {
x = value.x
z = value.y
}
var xw: MutableByteVec2
get() = MutableByteVec2(x, w)
set(value) {
x = value.x
w = value.y
}
var yx: MutableByteVec2
get() = MutableByteVec2(y, x)
set(value) {
y = value.x
x = value.y
}
val yy: MutableByteVec2 get() = MutableByteVec2(y, y)
var yz: MutableByteVec2
get() = MutableByteVec2(y, z)
set(value) {
y = value.x
z = value.y
}
var yw: MutableByteVec2
get() = MutableByteVec2(y, w)
set(value) {
y = value.x
w = value.y
}
var zx: MutableByteVec2
get() = MutableByteVec2(z, x)
set(value) {
z = value.x
x = value.y
}
var zy: MutableByteVec2
get() = MutableByteVec2(z, y)
set(value) {
z = value.x
y = value.y
}
val zz: MutableByteVec2 get() = MutableByteVec2(z, z)
var zw: MutableByteVec2
get() = MutableByteVec2(z, w)
set(value) {
z = value.x
w = value.y
}
var wx: MutableByteVec2
get() = MutableByteVec2(w, x)
set(value) {
w = value.x
x = value.y
}
var wy: MutableByteVec2
get() = MutableByteVec2(w, y)
set(value) {
w = value.x
y = value.y
}
var wz: MutableByteVec2
get() = MutableByteVec2(w, z)
set(value) {
w = value.x
z = value.y
}
val ww: MutableByteVec2 get() = MutableByteVec2(w, w)
val xxx: MutableByteVec3 get() = MutableByteVec3(x, x, x)
val xxy: MutableByteVec3 get() = MutableByteVec3(x, x, y)
val xxz: MutableByteVec3 get() = MutableByteVec3(x, x, z)
val xxw: MutableByteVec3 get() = MutableByteVec3(x, x, w)
val xyx: MutableByteVec3 get() = MutableByteVec3(x, y, x)
val xyy: MutableByteVec3 get() = MutableByteVec3(x, y, y)
var xyz: MutableByteVec3
get() = MutableByteVec3(x, y, z)
set(value) {
x = value.x
y = value.y
z = value.z
}
var xyw: MutableByteVec3
get() = MutableByteVec3(x, y, w)
set(value) {
x = value.x
y = value.y
w = value.z
}
val xzx: MutableByteVec3 get() = MutableByteVec3(x, z, x)
var xzy: MutableByteVec3
get() = MutableByteVec3(x, z, y)
set(value) {
x = value.x
z = value.y
y = value.z
}
val xzz: MutableByteVec3 get() = MutableByteVec3(x, z, z)
var xzw: MutableByteVec3
get() = MutableByteVec3(x, z, w)
set(value) {
x = value.x
z = value.y
w = value.z
}
val xwx: MutableByteVec3 get() = MutableByteVec3(x, w, x)
var xwy: MutableByteVec3
get() = MutableByteVec3(x, w, y)
set(value) {
x = value.x
w = value.y
y = value.z
}
var xwz: MutableByteVec3
get() = MutableByteVec3(x, w, z)
set(value) {
x = value.x
w = value.y
z = value.z
}
val xww: MutableByteVec3 get() = MutableByteVec3(x, w, w)
val yxx: MutableByteVec3 get() = MutableByteVec3(y, x, x)
val yxy: MutableByteVec3 get() = MutableByteVec3(y, x, y)
var yxz: MutableByteVec3
get() = MutableByteVec3(y, x, z)
set(value) {
y = value.x
x = value.y
z = value.z
}
var yxw: MutableByteVec3
get() = MutableByteVec3(y, x, w)
set(value) {
y = value.x
x = value.y
w = value.z
}
val yyx: MutableByteVec3 get() = MutableByteVec3(y, y, x)
val yyy: MutableByteVec3 get() = MutableByteVec3(y, y, y)
val yyz: MutableByteVec3 get() = MutableByteVec3(y, y, z)
val yyw: MutableByteVec3 get() = MutableByteVec3(y, y, w)
var yzx: MutableByteVec3
get() = MutableByteVec3(y, z, x)
set(value) {
y = value.x
z = value.y
x = value.z
}
val yzy: MutableByteVec3 get() = MutableByteVec3(y, z, y)
val yzz: MutableByteVec3 get() = MutableByteVec3(y, z, z)
var yzw: MutableByteVec3
get() = MutableByteVec3(y, z, w)
set(value) {
y = value.x
z = value.y
w = value.z
}
var ywx: MutableByteVec3
get() = MutableByteVec3(y, w, x)
set(value) {
y = value.x
w = value.y
x = value.z
}
val ywy: MutableByteVec3 get() = MutableByteVec3(y, w, y)
var ywz: MutableByteVec3
get() = MutableByteVec3(y, w, z)
set(value) {
y = value.x
w = value.y
z = value.z
}
val yww: MutableByteVec3 get() = MutableByteVec3(y, w, w)
val zxx: MutableByteVec3 get() = MutableByteVec3(z, x, x)
var zxy: MutableByteVec3
get() = MutableByteVec3(z, x, y)
set(value) {
z = value.x
x = value.y
y = value.z
}
val zxz: MutableByteVec3 get() = MutableByteVec3(z, x, z)
var zxw: MutableByteVec3
get() = MutableByteVec3(z, x, w)
set(value) {
z = value.x
x = value.y
w = value.z
}
var zyx: MutableByteVec3
get() = MutableByteVec3(z, y, x)
set(value) {
z = value.x
y = value.y
x = value.z
}
val zyy: MutableByteVec3 get() = MutableByteVec3(z, y, y)
val zyz: MutableByteVec3 get() = MutableByteVec3(z, y, z)
var zyw: MutableByteVec3
get() = MutableByteVec3(z, y, w)
set(value) {
z = value.x
y = value.y
w = value.z
}
val zzx: MutableByteVec3 get() = MutableByteVec3(z, z, x)
val zzy: MutableByteVec3 get() = MutableByteVec3(z, z, y)
val zzz: MutableByteVec3 get() = MutableByteVec3(z, z, z)
val zzw: MutableByteVec3 get() = MutableByteVec3(z, z, w)
var zwx: MutableByteVec3
get() = MutableByteVec3(z, w, x)
set(value) {
z = value.x
w = value.y
x = value.z
}
var zwy: MutableByteVec3
get() = MutableByteVec3(z, w, y)
set(value) {
z = value.x
w = value.y
y = value.z
}
val zwz: MutableByteVec3 get() = MutableByteVec3(z, w, z)
val zww: MutableByteVec3 get() = MutableByteVec3(z, w, w)
val wxx: MutableByteVec3 get() = MutableByteVec3(w, x, x)
var wxy: MutableByteVec3
get() = MutableByteVec3(w, x, y)
set(value) {
w = value.x
x = value.y
y = value.z
}
var wxz: MutableByteVec3
get() = MutableByteVec3(w, x, z)
set(value) {
w = value.x
x = value.y
z = value.z
}
val wxw: MutableByteVec3 get() = MutableByteVec3(w, x, w)
var wyx: MutableByteVec3
get() = MutableByteVec3(w, y, x)
set(value) {
w = value.x
y = value.y
x = value.z
}
val wyy: MutableByteVec3 get() = MutableByteVec3(w, y, y)
var wyz: MutableByteVec3
get() = MutableByteVec3(w, y, z)
set(value) {
w = value.x
y = value.y
z = value.z
}
val wyw: MutableByteVec3 get() = MutableByteVec3(w, y, w)
var wzx: MutableByteVec3
get() = MutableByteVec3(w, z, x)
set(value) {
w = value.x
z = value.y
x = value.z
}
var wzy: MutableByteVec3
get() = MutableByteVec3(w, z, y)
set(value) {
w = value.x
z = value.y
y = value.z
}
val wzz: MutableByteVec3 get() = MutableByteVec3(w, z, z)
val wzw: MutableByteVec3 get() = MutableByteVec3(w, z, w)
val wwx: MutableByteVec3 get() = MutableByteVec3(w, w, x)
val wwy: MutableByteVec3 get() = MutableByteVec3(w, w, y)
val wwz: MutableByteVec3 get() = MutableByteVec3(w, w, z)
val www: MutableByteVec3 get() = MutableByteVec3(w, w, w)
val xxxx: MutableByteVec4 get() = MutableByteVec4(x, x, x, x)
val xxxy: MutableByteVec4 get() = MutableByteVec4(x, x, x, y)
val xxxz: MutableByteVec4 get() = MutableByteVec4(x, x, x, z)
val xxxw: MutableByteVec4 get() = MutableByteVec4(x, x, x, w)
val xxyx: MutableByteVec4 get() = MutableByteVec4(x, x, y, x)
val xxyy: MutableByteVec4 get() = MutableByteVec4(x, x, y, y)
val xxyz: MutableByteVec4 get() = MutableByteVec4(x, x, y, z)
val xxyw: MutableByteVec4 get() = MutableByteVec4(x, x, y, w)
val xxzx: MutableByteVec4 get() = MutableByteVec4(x, x, z, x)
val xxzy: MutableByteVec4 get() = MutableByteVec4(x, x, z, y)
val xxzz: MutableByteVec4 get() = MutableByteVec4(x, x, z, z)
val xxzw: MutableByteVec4 get() = MutableByteVec4(x, x, z, w)
val xxwx: MutableByteVec4 get() = MutableByteVec4(x, x, w, x)
val xxwy: MutableByteVec4 get() = MutableByteVec4(x, x, w, y)
val xxwz: MutableByteVec4 get() = MutableByteVec4(x, x, w, z)
val xxww: MutableByteVec4 get() = MutableByteVec4(x, x, w, w)
val xyxx: MutableByteVec4 get() = MutableByteVec4(x, y, x, x)
val xyxy: MutableByteVec4 get() = MutableByteVec4(x, y, x, y)
val xyxz: MutableByteVec4 get() = MutableByteVec4(x, y, x, z)
val xyxw: MutableByteVec4 get() = MutableByteVec4(x, y, x, w)
val xyyx: MutableByteVec4 get() = MutableByteVec4(x, y, y, x)
val xyyy: MutableByteVec4 get() = MutableByteVec4(x, y, y, y)
val xyyz: MutableByteVec4 get() = MutableByteVec4(x, y, y, z)
val xyyw: MutableByteVec4 get() = MutableByteVec4(x, y, y, w)
val xyzx: MutableByteVec4 get() = MutableByteVec4(x, y, z, x)
val xyzy: MutableByteVec4 get() = MutableByteVec4(x, y, z, y)
val xyzz: MutableByteVec4 get() = MutableByteVec4(x, y, z, z)
var xyzw: MutableByteVec4
get() = MutableByteVec4(x, y, z, w)
set(value) {
x = value.x
y = value.y
z = value.z
w = value.w
}
val xywx: MutableByteVec4 get() = MutableByteVec4(x, y, w, x)
val xywy: MutableByteVec4 get() = MutableByteVec4(x, y, w, y)
var xywz: MutableByteVec4
get() = MutableByteVec4(x, y, w, z)
set(value) {
x = value.x
y = value.y
w = value.z
z = value.w
}
val xyww: MutableByteVec4 get() = MutableByteVec4(x, y, w, w)
val xzxx: MutableByteVec4 get() = MutableByteVec4(x, z, x, x)
val xzxy: MutableByteVec4 get() = MutableByteVec4(x, z, x, y)
val xzxz: MutableByteVec4 get() = MutableByteVec4(x, z, x, z)
val xzxw: MutableByteVec4 get() = MutableByteVec4(x, z, x, w)
val xzyx: MutableByteVec4 get() = MutableByteVec4(x, z, y, x)
val xzyy: MutableByteVec4 get() = MutableByteVec4(x, z, y, y)
val xzyz: MutableByteVec4 get() = MutableByteVec4(x, z, y, z)
var xzyw: MutableByteVec4
get() = MutableByteVec4(x, z, y, w)
set(value) {
x = value.x
z = value.y
y = value.z
w = value.w
}
val xzzx: MutableByteVec4 get() = MutableByteVec4(x, z, z, x)
val xzzy: MutableByteVec4 get() = MutableByteVec4(x, z, z, y)
val xzzz: MutableByteVec4 get() = MutableByteVec4(x, z, z, z)
val xzzw: MutableByteVec4 get() = MutableByteVec4(x, z, z, w)
val xzwx: MutableByteVec4 get() = MutableByteVec4(x, z, w, x)
var xzwy: MutableByteVec4
get() = MutableByteVec4(x, z, w, y)
set(value) {
x = value.x
z = value.y
w = value.z
y = value.w
}
val xzwz: MutableByteVec4 get() = MutableByteVec4(x, z, w, z)
val xzww: MutableByteVec4 get() = MutableByteVec4(x, z, w, w)
val xwxx: MutableByteVec4 get() = MutableByteVec4(x, w, x, x)
val xwxy: MutableByteVec4 get() = MutableByteVec4(x, w, x, y)
val xwxz: MutableByteVec4 get() = MutableByteVec4(x, w, x, z)
val xwxw: MutableByteVec4 get() = MutableByteVec4(x, w, x, w)
val xwyx: MutableByteVec4 get() = MutableByteVec4(x, w, y, x)
val xwyy: MutableByteVec4 get() = MutableByteVec4(x, w, y, y)
var xwyz: MutableByteVec4
get() = MutableByteVec4(x, w, y, z)
set(value) {
x = value.x
w = value.y
y = value.z
z = value.w
}
val xwyw: MutableByteVec4 get() = MutableByteVec4(x, w, y, w)
val xwzx: MutableByteVec4 get() = MutableByteVec4(x, w, z, x)
var xwzy: MutableByteVec4
get() = MutableByteVec4(x, w, z, y)
set(value) {
x = value.x
w = value.y
z = value.z
y = value.w
}
val xwzz: MutableByteVec4 get() = MutableByteVec4(x, w, z, z)
val xwzw: MutableByteVec4 get() = MutableByteVec4(x, w, z, w)
val xwwx: MutableByteVec4 get() = MutableByteVec4(x, w, w, x)
val xwwy: MutableByteVec4 get() = MutableByteVec4(x, w, w, y)
val xwwz: MutableByteVec4 get() = MutableByteVec4(x, w, w, z)
val xwww: MutableByteVec4 get() = MutableByteVec4(x, w, w, w)
val yxxx: MutableByteVec4 get() = MutableByteVec4(y, x, x, x)
val yxxy: MutableByteVec4 get() = MutableByteVec4(y, x, x, y)
val yxxz: MutableByteVec4 get() = MutableByteVec4(y, x, x, z)
val yxxw: MutableByteVec4 get() = MutableByteVec4(y, x, x, w)
val yxyx: MutableByteVec4 get() = MutableByteVec4(y, x, y, x)
val yxyy: MutableByteVec4 get() = MutableByteVec4(y, x, y, y)
val yxyz: MutableByteVec4 get() = MutableByteVec4(y, x, y, z)
val yxyw: MutableByteVec4 get() = MutableByteVec4(y, x, y, w)
val yxzx: MutableByteVec4 get() = MutableByteVec4(y, x, z, x)
val yxzy: MutableByteVec4 get() = MutableByteVec4(y, x, z, y)
val yxzz: MutableByteVec4 get() = MutableByteVec4(y, x, z, z)
var yxzw: MutableByteVec4
get() = MutableByteVec4(y, x, z, w)
set(value) {
y = value.x
x = value.y
z = value.z
w = value.w
}
val yxwx: MutableByteVec4 get() = MutableByteVec4(y, x, w, x)
val yxwy: MutableByteVec4 get() = MutableByteVec4(y, x, w, y)
var yxwz: MutableByteVec4
get() = MutableByteVec4(y, x, w, z)
set(value) {
y = value.x
x = value.y
w = value.z
z = value.w
}
val yxww: MutableByteVec4 get() = MutableByteVec4(y, x, w, w)
val yyxx: MutableByteVec4 get() = MutableByteVec4(y, y, x, x)
val yyxy: MutableByteVec4 get() = MutableByteVec4(y, y, x, y)
val yyxz: MutableByteVec4 get() = MutableByteVec4(y, y, x, z)
val yyxw: MutableByteVec4 get() = MutableByteVec4(y, y, x, w)
val yyyx: MutableByteVec4 get() = MutableByteVec4(y, y, y, x)
val yyyy: MutableByteVec4 get() = MutableByteVec4(y, y, y, y)
val yyyz: MutableByteVec4 get() = MutableByteVec4(y, y, y, z)
val yyyw: MutableByteVec4 get() = MutableByteVec4(y, y, y, w)
val yyzx: MutableByteVec4 get() = MutableByteVec4(y, y, z, x)
val yyzy: MutableByteVec4 get() = MutableByteVec4(y, y, z, y)
val yyzz: MutableByteVec4 get() = MutableByteVec4(y, y, z, z)
val yyzw: MutableByteVec4 get() = MutableByteVec4(y, y, z, w)
val yywx: MutableByteVec4 get() = MutableByteVec4(y, y, w, x)
val yywy: MutableByteVec4 get() = MutableByteVec4(y, y, w, y)
val yywz: MutableByteVec4 get() = MutableByteVec4(y, y, w, z)
val yyww: MutableByteVec4 get() = MutableByteVec4(y, y, w, w)
val yzxx: MutableByteVec4 get() = MutableByteVec4(y, z, x, x)
val yzxy: MutableByteVec4 get() = MutableByteVec4(y, z, x, y)
val yzxz: MutableByteVec4 get() = MutableByteVec4(y, z, x, z)
var yzxw: MutableByteVec4
get() = MutableByteVec4(y, z, x, w)
set(value) {
y = value.x
z = value.y
x = value.z
w = value.w
}
val yzyx: MutableByteVec4 get() = MutableByteVec4(y, z, y, x)
val yzyy: MutableByteVec4 get() = MutableByteVec4(y, z, y, y)
val yzyz: MutableByteVec4 get() = MutableByteVec4(y, z, y, z)
val yzyw: MutableByteVec4 get() = MutableByteVec4(y, z, y, w)
val yzzx: MutableByteVec4 get() = MutableByteVec4(y, z, z, x)
val yzzy: MutableByteVec4 get() = MutableByteVec4(y, z, z, y)
val yzzz: MutableByteVec4 get() = MutableByteVec4(y, z, z, z)
val yzzw: MutableByteVec4 get() = MutableByteVec4(y, z, z, w)
var yzwx: MutableByteVec4
get() = MutableByteVec4(y, z, w, x)
set(value) {
y = value.x
z = value.y
w = value.z
x = value.w
}
val yzwy: MutableByteVec4 get() = MutableByteVec4(y, z, w, y)
val yzwz: MutableByteVec4 get() = MutableByteVec4(y, z, w, z)
val yzww: MutableByteVec4 get() = MutableByteVec4(y, z, w, w)
val ywxx: MutableByteVec4 get() = MutableByteVec4(y, w, x, x)
val ywxy: MutableByteVec4 get() = MutableByteVec4(y, w, x, y)
var ywxz: MutableByteVec4
get() = MutableByteVec4(y, w, x, z)
set(value) {
y = value.x
w = value.y
x = value.z
z = value.w
}
val ywxw: MutableByteVec4 get() = MutableByteVec4(y, w, x, w)
val ywyx: MutableByteVec4 get() = MutableByteVec4(y, w, y, x)
val ywyy: MutableByteVec4 get() = MutableByteVec4(y, w, y, y)
val ywyz: MutableByteVec4 get() = MutableByteVec4(y, w, y, z)
val ywyw: MutableByteVec4 get() = MutableByteVec4(y, w, y, w)
var ywzx: MutableByteVec4
get() = MutableByteVec4(y, w, z, x)
set(value) {
y = value.x
w = value.y
z = value.z
x = value.w
}
val ywzy: MutableByteVec4 get() = MutableByteVec4(y, w, z, y)
val ywzz: MutableByteVec4 get() = MutableByteVec4(y, w, z, z)
val ywzw: MutableByteVec4 get() = MutableByteVec4(y, w, z, w)
val ywwx: MutableByteVec4 get() = MutableByteVec4(y, w, w, x)
val ywwy: MutableByteVec4 get() = MutableByteVec4(y, w, w, y)
val ywwz: MutableByteVec4 get() = MutableByteVec4(y, w, w, z)
val ywww: MutableByteVec4 get() = MutableByteVec4(y, w, w, w)
val zxxx: MutableByteVec4 get() = MutableByteVec4(z, x, x, x)
val zxxy: MutableByteVec4 get() = MutableByteVec4(z, x, x, y)
val zxxz: MutableByteVec4 get() = MutableByteVec4(z, x, x, z)
val zxxw: MutableByteVec4 get() = MutableByteVec4(z, x, x, w)
val zxyx: MutableByteVec4 get() = MutableByteVec4(z, x, y, x)
val zxyy: MutableByteVec4 get() = MutableByteVec4(z, x, y, y)
val zxyz: MutableByteVec4 get() = MutableByteVec4(z, x, y, z)
var zxyw: MutableByteVec4
get() = MutableByteVec4(z, x, y, w)
set(value) {
z = value.x
x = value.y
y = value.z
w = value.w
}
val zxzx: MutableByteVec4 get() = MutableByteVec4(z, x, z, x)
val zxzy: MutableByteVec4 get() = MutableByteVec4(z, x, z, y)
val zxzz: MutableByteVec4 get() = MutableByteVec4(z, x, z, z)
val zxzw: MutableByteVec4 get() = MutableByteVec4(z, x, z, w)
val zxwx: MutableByteVec4 get() = MutableByteVec4(z, x, w, x)
var zxwy: MutableByteVec4
get() = MutableByteVec4(z, x, w, y)
set(value) {
z = value.x
x = value.y
w = value.z
y = value.w
}
val zxwz: MutableByteVec4 get() = MutableByteVec4(z, x, w, z)
val zxww: MutableByteVec4 get() = MutableByteVec4(z, x, w, w)
val zyxx: MutableByteVec4 get() = MutableByteVec4(z, y, x, x)
val zyxy: MutableByteVec4 get() = MutableByteVec4(z, y, x, y)
val zyxz: MutableByteVec4 get() = MutableByteVec4(z, y, x, z)
var zyxw: MutableByteVec4
get() = MutableByteVec4(z, y, x, w)
set(value) {
z = value.x
y = value.y
x = value.z
w = value.w
}
val zyyx: MutableByteVec4 get() = MutableByteVec4(z, y, y, x)
val zyyy: MutableByteVec4 get() = MutableByteVec4(z, y, y, y)
val zyyz: MutableByteVec4 get() = MutableByteVec4(z, y, y, z)
val zyyw: MutableByteVec4 get() = MutableByteVec4(z, y, y, w)
val zyzx: MutableByteVec4 get() = MutableByteVec4(z, y, z, x)
val zyzy: MutableByteVec4 get() = MutableByteVec4(z, y, z, y)
val zyzz: MutableByteVec4 get() = MutableByteVec4(z, y, z, z)
val zyzw: MutableByteVec4 get() = MutableByteVec4(z, y, z, w)
var zywx: MutableByteVec4
get() = MutableByteVec4(z, y, w, x)
set(value) {
z = value.x
y = value.y
w = value.z
x = value.w
}
val zywy: MutableByteVec4 get() = MutableByteVec4(z, y, w, y)
val zywz: MutableByteVec4 get() = MutableByteVec4(z, y, w, z)
val zyww: MutableByteVec4 get() = MutableByteVec4(z, y, w, w)
val zzxx: MutableByteVec4 get() = MutableByteVec4(z, z, x, x)
val zzxy: MutableByteVec4 get() = MutableByteVec4(z, z, x, y)
val zzxz: MutableByteVec4 get() = MutableByteVec4(z, z, x, z)
val zzxw: MutableByteVec4 get() = MutableByteVec4(z, z, x, w)
val zzyx: MutableByteVec4 get() = MutableByteVec4(z, z, y, x)
val zzyy: MutableByteVec4 get() = MutableByteVec4(z, z, y, y)
val zzyz: MutableByteVec4 get() = MutableByteVec4(z, z, y, z)
val zzyw: MutableByteVec4 get() = MutableByteVec4(z, z, y, w)
val zzzx: MutableByteVec4 get() = MutableByteVec4(z, z, z, x)
val zzzy: MutableByteVec4 get() = MutableByteVec4(z, z, z, y)
val zzzz: MutableByteVec4 get() = MutableByteVec4(z, z, z, z)
val zzzw: MutableByteVec4 get() = MutableByteVec4(z, z, z, w)
val zzwx: MutableByteVec4 get() = MutableByteVec4(z, z, w, x)
val zzwy: MutableByteVec4 get() = MutableByteVec4(z, z, w, y)
val zzwz: MutableByteVec4 get() = MutableByteVec4(z, z, w, z)
val zzww: MutableByteVec4 get() = MutableByteVec4(z, z, w, w)
val zwxx: MutableByteVec4 get() = MutableByteVec4(z, w, x, x)
var zwxy: MutableByteVec4
get() = MutableByteVec4(z, w, x, y)
set(value) {
z = value.x
w = value.y
x = value.z
y = value.w
}
val zwxz: MutableByteVec4 get() = MutableByteVec4(z, w, x, z)
val zwxw: MutableByteVec4 get() = MutableByteVec4(z, w, x, w)
var zwyx: MutableByteVec4
get() = MutableByteVec4(z, w, y, x)
set(value) {
z = value.x
w = value.y
y = value.z
x = value.w
}
val zwyy: MutableByteVec4 get() = MutableByteVec4(z, w, y, y)
val zwyz: MutableByteVec4 get() = MutableByteVec4(z, w, y, z)
val zwyw: MutableByteVec4 get() = MutableByteVec4(z, w, y, w)
val zwzx: MutableByteVec4 get() = MutableByteVec4(z, w, z, x)
val zwzy: MutableByteVec4 get() = MutableByteVec4(z, w, z, y)
val zwzz: MutableByteVec4 get() = MutableByteVec4(z, w, z, z)
val zwzw: MutableByteVec4 get() = MutableByteVec4(z, w, z, w)
val zwwx: MutableByteVec4 get() = MutableByteVec4(z, w, w, x)
val zwwy: MutableByteVec4 get() = MutableByteVec4(z, w, w, y)
val zwwz: MutableByteVec4 get() = MutableByteVec4(z, w, w, z)
val zwww: MutableByteVec4 get() = MutableByteVec4(z, w, w, w)
val wxxx: MutableByteVec4 get() = MutableByteVec4(w, x, x, x)
val wxxy: MutableByteVec4 get() = MutableByteVec4(w, x, x, y)
val wxxz: MutableByteVec4 get() = MutableByteVec4(w, x, x, z)
val wxxw: MutableByteVec4 get() = MutableByteVec4(w, x, x, w)
val wxyx: MutableByteVec4 get() = MutableByteVec4(w, x, y, x)
val wxyy: MutableByteVec4 get() = MutableByteVec4(w, x, y, y)
var wxyz: MutableByteVec4
get() = MutableByteVec4(w, x, y, z)
set(value) {
w = value.x
x = value.y
y = value.z
z = value.w
}
val wxyw: MutableByteVec4 get() = MutableByteVec4(w, x, y, w)
val wxzx: MutableByteVec4 get() = MutableByteVec4(w, x, z, x)
var wxzy: MutableByteVec4
get() = MutableByteVec4(w, x, z, y)
set(value) {
w = value.x
x = value.y
z = value.z
y = value.w
}
val wxzz: MutableByteVec4 get() = MutableByteVec4(w, x, z, z)
val wxzw: MutableByteVec4 get() = MutableByteVec4(w, x, z, w)
val wxwx: MutableByteVec4 get() = MutableByteVec4(w, x, w, x)
val wxwy: MutableByteVec4 get() = MutableByteVec4(w, x, w, y)
val wxwz: MutableByteVec4 get() = MutableByteVec4(w, x, w, z)
val wxww: MutableByteVec4 get() = MutableByteVec4(w, x, w, w)
val wyxx: MutableByteVec4 get() = MutableByteVec4(w, y, x, x)
val wyxy: MutableByteVec4 get() = MutableByteVec4(w, y, x, y)
var wyxz: MutableByteVec4
get() = MutableByteVec4(w, y, x, z)
set(value) {
w = value.x
y = value.y
x = value.z
z = value.w
}
val wyxw: MutableByteVec4 get() = MutableByteVec4(w, y, x, w)
val wyyx: MutableByteVec4 get() = MutableByteVec4(w, y, y, x)
val wyyy: MutableByteVec4 get() = MutableByteVec4(w, y, y, y)
val wyyz: MutableByteVec4 get() = MutableByteVec4(w, y, y, z)
val wyyw: MutableByteVec4 get() = MutableByteVec4(w, y, y, w)
var wyzx: MutableByteVec4
get() = MutableByteVec4(w, y, z, x)
set(value) {
w = value.x
y = value.y
z = value.z
x = value.w
}
val wyzy: MutableByteVec4 get() = MutableByteVec4(w, y, z, y)
val wyzz: MutableByteVec4 get() = MutableByteVec4(w, y, z, z)
val wyzw: MutableByteVec4 get() = MutableByteVec4(w, y, z, w)
val wywx: MutableByteVec4 get() = MutableByteVec4(w, y, w, x)
val wywy: MutableByteVec4 get() = MutableByteVec4(w, y, w, y)
val wywz: MutableByteVec4 get() = MutableByteVec4(w, y, w, z)
val wyww: MutableByteVec4 get() = MutableByteVec4(w, y, w, w)
val wzxx: MutableByteVec4 get() = MutableByteVec4(w, z, x, x)
var wzxy: MutableByteVec4
get() = MutableByteVec4(w, z, x, y)
set(value) {
w = value.x
z = value.y
x = value.z
y = value.w
}
val wzxz: MutableByteVec4 get() = MutableByteVec4(w, z, x, z)
val wzxw: MutableByteVec4 get() = MutableByteVec4(w, z, x, w)
var wzyx: MutableByteVec4
get() = MutableByteVec4(w, z, y, x)
set(value) {
w = value.x
z = value.y
y = value.z
x = value.w
}
val wzyy: MutableByteVec4 get() = MutableByteVec4(w, z, y, y)
val wzyz: MutableByteVec4 get() = MutableByteVec4(w, z, y, z)
val wzyw: MutableByteVec4 get() = MutableByteVec4(w, z, y, w)
val wzzx: MutableByteVec4 get() = MutableByteVec4(w, z, z, x)
val wzzy: MutableByteVec4 get() = MutableByteVec4(w, z, z, y)
val wzzz: MutableByteVec4 get() = MutableByteVec4(w, z, z, z)
val wzzw: MutableByteVec4 get() = MutableByteVec4(w, z, z, w)
val wzwx: MutableByteVec4 get() = MutableByteVec4(w, z, w, x)
val wzwy: MutableByteVec4 get() = MutableByteVec4(w, z, w, y)
val wzwz: MutableByteVec4 get() = MutableByteVec4(w, z, w, z)
val wzww: MutableByteVec4 get() = MutableByteVec4(w, z, w, w)
val wwxx: MutableByteVec4 get() = MutableByteVec4(w, w, x, x)
val wwxy: MutableByteVec4 get() = MutableByteVec4(w, w, x, y)
val wwxz: MutableByteVec4 get() = MutableByteVec4(w, w, x, z)
val wwxw: MutableByteVec4 get() = MutableByteVec4(w, w, x, w)
val wwyx: MutableByteVec4 get() = MutableByteVec4(w, w, y, x)
val wwyy: MutableByteVec4 get() = MutableByteVec4(w, w, y, y)
val wwyz: MutableByteVec4 get() = MutableByteVec4(w, w, y, z)
val wwyw: MutableByteVec4 get() = MutableByteVec4(w, w, y, w)
val wwzx: MutableByteVec4 get() = MutableByteVec4(w, w, z, x)
val wwzy: MutableByteVec4 get() = MutableByteVec4(w, w, z, y)
val wwzz: MutableByteVec4 get() = MutableByteVec4(w, w, z, z)
val wwzw: MutableByteVec4 get() = MutableByteVec4(w, w, z, w)
val wwwx: MutableByteVec4 get() = MutableByteVec4(w, w, w, x)
val wwwy: MutableByteVec4 get() = MutableByteVec4(w, w, w, y)
val wwwz: MutableByteVec4 get() = MutableByteVec4(w, w, w, z)
val wwww: MutableByteVec4 get() = MutableByteVec4(w, w, w, w)
}
val swizzle: Swizzle get() = Swizzle()
}
fun mutableVecOf(x: Byte, y: Byte, z: Byte, w: Byte): MutableByteVec4 = MutableByteVec4(x, y, z, w)
operator fun Byte.plus(rhs: MutableByteVec4): MutableIntVec4 = MutableIntVec4(this + rhs.x, this + rhs.y, this + rhs.z, this + rhs.w)
operator fun Byte.minus(rhs: MutableByteVec4): MutableIntVec4 = MutableIntVec4(this - rhs.x, this - rhs.y, this - rhs.z, this - rhs.w)
operator fun Byte.times(rhs: MutableByteVec4): MutableIntVec4 = MutableIntVec4(this * rhs.x, this * rhs.y, this * rhs.z, this * rhs.w)
operator fun Byte.div(rhs: MutableByteVec4): MutableIntVec4 = MutableIntVec4(this / rhs.x, this / rhs.y, this / rhs.z, this / rhs.w)
operator fun Byte.rem(rhs: MutableByteVec4): MutableIntVec4 = MutableIntVec4(this % rhs.x, this % rhs.y, this % rhs.z, this % rhs.w)
| mit | 2cbec320fad2fbe89099c1134b73abe0 | 52.141237 | 134 | 0.575591 | 3.654261 | false | false | false | false |
armcha/Ribble | app/src/main/kotlin/io/armcha/ribble/presentation/utils/extensions/CommonEx.kt | 1 | 2339 | package io.armcha.ribble.presentation.utils.extensions
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.content.Context
import android.os.Build
import android.os.Handler
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.text.Html
import android.text.Spanned
import android.widget.Toast
import io.armcha.ribble.App
import io.armcha.ribble.presentation.utils.Experimental
/**
* Created by Chatikyan on 01.08.2017.
*/
infix fun Context.takeColor(colorId: Int) = ContextCompat.getColor(this, colorId)
operator fun Context.get(resId: Int): String = getString(resId)
operator fun Fragment.get(resId: Int): String = getString(resId)
@Experimental
fun Int.text(): String = App.instance.getString(this) //What do you think about it?
fun Context.showToast(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
inline fun delay(milliseconds: Long, crossinline action: () -> Unit) {
Handler().postDelayed({
action()
}, milliseconds)
}
@Deprecated("Use emptyString instead", ReplaceWith("emptyString"), level = DeprecationLevel.WARNING)
fun emptyString() = ""
val emptyString = ""
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
inline fun LorAbove(body: () -> Unit) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
body()
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
inline fun MorAbove(body: () -> Unit) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
body()
}
}
@TargetApi(Build.VERSION_CODES.N)
inline fun NorAbove(body: () -> Unit) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
body()
}
}
@SuppressLint("NewApi")
fun String.toHtml(): Spanned {
NorAbove {
return Html.fromHtml(this, Html.FROM_HTML_MODE_COMPACT)
}
return Html.fromHtml(this)
}
fun Int.toPx(context: Context): Int {
val density = context.resources.displayMetrics.density
return (this * density).toInt()
}
fun <T> unSafeLazy(initializer: () -> T): Lazy<T> {
return lazy(LazyThreadSafetyMode.NONE) {
initializer()
}
}
fun Int.isZero(): Boolean = this == 0
inline fun <F, S> doubleWith(first: F, second: S, runWith: F.(S) -> Unit) {
first.runWith(second)
}
val Any?.isNull: Boolean
get() = this == null | apache-2.0 | 9aca658385de06980727bb6aecfacf2a | 24.434783 | 100 | 0.704147 | 3.538578 | false | false | false | false |
ayatk/biblio | app/src/main/kotlin/com/ayatk/biblio/data/repository/EpisodeRepositoryImpl.kt | 1 | 1998 | /*
* Copyright (c) 2016-2018 ayatk.
*
* 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.ayatk.biblio.data.repository
import com.ayatk.biblio.data.remote.NarouDataStore
import com.ayatk.biblio.data.remote.entity.mapper.toEntity
import com.ayatk.biblio.di.scope.Narou
import com.ayatk.biblio.di.scope.Nocturne
import com.ayatk.biblio.infrastructure.database.dao.EpisodeDao
import com.ayatk.biblio.infrastructure.database.entity.EpisodeEntity
import com.ayatk.biblio.infrastructure.database.entity.NovelEntity
import com.ayatk.biblio.infrastructure.database.entity.enums.NovelState
import io.reactivex.Completable
import io.reactivex.Flowable
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class EpisodeRepositoryImpl @Inject constructor(
private val dao: EpisodeDao,
@Narou private val narouDataStore: NarouDataStore,
@Nocturne private val nocDataStore: NarouDataStore
) : EpisodeRepository {
override fun find(entity: NovelEntity, page: Int): Flowable<EpisodeEntity> =
if (entity.novelState == NovelState.SHORT_STORY) {
narouDataStore.getShortStory(entity.code)
} else {
narouDataStore.getEpisode(entity.code, page)
}
.map { it.toEntity() }
override fun save(episode: EpisodeEntity): Completable =
Completable.fromCallable { dao::insert }
override fun deleteAll(code: String): Completable =
Completable.fromRunnable {
dao.getAllEpisodeByCode(code)
.map { it.map(dao::delete) }
}
}
| apache-2.0 | 9051f28897caaf7fca2748751082e187 | 35.327273 | 78 | 0.765265 | 4.004008 | false | false | false | false |
iSoron/uhabits | uhabits-android/src/main/java/org/isoron/uhabits/activities/settings/SettingsActivity.kt | 1 | 1907 | /*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker 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.
*
* Loop Habit Tracker 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 org.isoron.uhabits.activities.settings
import android.os.Bundle
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import org.isoron.uhabits.HabitsApplication
import org.isoron.uhabits.R
import org.isoron.uhabits.activities.AndroidThemeSwitcher
import org.isoron.uhabits.core.models.PaletteColor
import org.isoron.uhabits.databinding.SettingsActivityBinding
import org.isoron.uhabits.utils.setupToolbar
class SettingsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val component = (application as HabitsApplication).component
val themeSwitcher = AndroidThemeSwitcher(this, component.preferences)
themeSwitcher.apply()
val binding = SettingsActivityBinding.inflate(LayoutInflater.from(this))
binding.root.setupToolbar(
toolbar = binding.toolbar,
title = resources.getString(R.string.settings),
color = PaletteColor(11),
theme = themeSwitcher.currentTheme,
)
setContentView(binding.root)
}
}
| gpl-3.0 | eb75fc214c9ee9b7ee01fcde5f8c504f | 39.553191 | 80 | 0.748164 | 4.570743 | false | false | false | false |
fwcd/kotlin-language-server | server/src/main/kotlin/org/javacs/kt/formatting/Formatter.kt | 1 | 459 | package org.javacs.kt.formatting
import com.facebook.ktfmt.format.Formatter
import com.facebook.ktfmt.format.FormattingOptions as KtfmtOptions
import org.eclipse.lsp4j.FormattingOptions
fun formatKotlinCode(
code: String,
options: FormattingOptions = FormattingOptions(4, true)
): String = Formatter.format(KtfmtOptions(
style = KtfmtOptions.Style.GOOGLE,
blockIndent = options.tabSize,
continuationIndent = 2 * options.tabSize
), code)
| mit | 10e2b509290c5bc1b481c2741b380e49 | 31.785714 | 66 | 0.784314 | 3.889831 | false | false | false | false |
anibyl/slounik | main/src/main/java/org/anibyl/slounik/ui/ProgressBar.kt | 1 | 1311 | package org.anibyl.slounik.ui
import android.content.Context
import android.util.AttributeSet
import android.view.View
import fr.castorflex.android.smoothprogressbar.SmoothProgressBar
import fr.castorflex.android.smoothprogressbar.SmoothProgressDrawable
/**
* Slounik's progress bar.
*
* @author Usievaład Kimajeŭ
* @created 21.12.2015
*/
class ProgressBar : SmoothProgressBar {
private var invisible: Boolean
get() { return visibility == View.INVISIBLE }
set(value) { visibility = if (value) View.INVISIBLE else View.VISIBLE }
constructor(context: Context) : super(context) {
init()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init()
}
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
init()
}
override fun progressiveStart() {
invisible = false
super.progressiveStart()
}
override fun progressiveStop() {
invisible = true
super.progressiveStop()
}
private fun init() {
visibility = View.INVISIBLE
setSmoothProgressDrawableCallbacks(object : SmoothProgressDrawable.Callbacks {
override fun onStop() {
if (invisible) {
visibility = View.INVISIBLE
}
}
override fun onStart() {
if (!invisible) {
visibility = View.VISIBLE
}
}
})
}
}
| gpl-3.0 | b04a9b4180f99fce61356180465ac05d | 21.186441 | 102 | 0.718869 | 3.509383 | false | false | false | false |
pflammertsma/cryptogram | app/src/main/java/com/pixplicity/cryptogram/utils/SystemUtils.kt | 1 | 1380 | package com.pixplicity.cryptogram.utils
import android.annotation.TargetApi
import android.content.Context
import android.os.Build
import android.provider.Settings
import android.text.TextUtils
object SystemUtils {
val deviceName: String
get() {
val manufacturer = Build.MANUFACTURER
val model = Build.MODEL
return if (model.startsWith(manufacturer)) {
capitalize(model)
} else capitalize(manufacturer) + " " + model
}
/**
* Gets the state of Airplane Mode.
*
* @param context
* @return true if enabled.
*/
fun isAirplaneModeOn(context: Context): Boolean {
return Settings.Global.getInt(context.contentResolver,
Settings.Global.AIRPLANE_MODE_ON, 0) != 0
}
private fun capitalize(str: String): String {
if (TextUtils.isEmpty(str)) {
return str
}
val arr = str.toCharArray()
var capitalizeNext = true
var phrase = ""
for (c in arr) {
if (capitalizeNext && Character.isLetter(c)) {
phrase += c.toUpperCase()
capitalizeNext = false
continue
} else if (Character.isWhitespace(c)) {
capitalizeNext = true
}
phrase += c
}
return phrase
}
}
| mit | d60edf7c7e16167ecf5e422323d83543 | 26.058824 | 62 | 0.566667 | 4.808362 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/iam/src/main/kotlin/com/kotlin/iam/IAMScenario.kt | 1 | 9239 | // snippet-sourcedescription:[IAMScenario.kt demonstrates how to perform various AWS Identity and Access Management (IAM) operations.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Identity and Access Management (IAM)]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.iam
// snippet-start:[iam.kotlin.scenario.import]
import aws.sdk.kotlin.runtime.auth.credentials.StaticCredentialsProvider
import aws.sdk.kotlin.services.iam.IamClient
import aws.sdk.kotlin.services.iam.model.AttachRolePolicyRequest
import aws.sdk.kotlin.services.iam.model.AttachedPolicy
import aws.sdk.kotlin.services.iam.model.CreatePolicyRequest
import aws.sdk.kotlin.services.iam.model.CreateRoleRequest
import aws.sdk.kotlin.services.iam.model.CreateUserRequest
import aws.sdk.kotlin.services.iam.model.DeletePolicyRequest
import aws.sdk.kotlin.services.iam.model.DeleteRoleRequest
import aws.sdk.kotlin.services.iam.model.DeleteUserRequest
import aws.sdk.kotlin.services.iam.model.DetachRolePolicyRequest
import aws.sdk.kotlin.services.iam.model.ListAttachedRolePoliciesRequest
import aws.sdk.kotlin.services.s3.S3Client
import aws.sdk.kotlin.services.s3.model.ListObjectsRequest
import aws.sdk.kotlin.services.sts.StsClient
import aws.sdk.kotlin.services.sts.model.AssumeRoleRequest
import kotlinx.coroutines.delay
import org.json.simple.JSONObject
import org.json.simple.parser.JSONParser
import java.io.FileReader
import kotlin.system.exitProcess
// snippet-end:[iam.kotlin.scenario.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
This example performs these operations:
1. Creates a user that has no permissions.
2. Creates a role and policy that grants Amazon S3 permissions.
3. Grants the user permissions.
4. Gets temporary credentials by assuming the role.
5. Creates an Amazon S3 Service client object with the temporary credentials and list objects in an Amazon S3 bucket.
6. Deletes the resources.
*/
// snippet-start:[iam.kotlin.scenario.main]
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<username> <policyName> <roleName> <roleSessionName> <fileLocation> <bucketName>
Where:
username - The name of the IAM user to create.
policyName - The name of the policy to create.
roleName - The name of the role to create.
roleSessionName - The name of the session required for the assumeRole operation.
fileLocation - The file location to the JSON required to create the role (see Readme).
bucketName - The name of the Amazon S3 bucket from which objects are read.
"""
if (args.size != 6) {
println(usage)
exitProcess(1)
}
val userName = args[0]
val policyName = args[1]
val roleName = args[2]
val roleSessionName = args[3]
val fileLocation = args[4]
val bucketName = args[5]
createUser(userName)
println("$userName was successfully created.")
val polArn = createPolicy(policyName)
println("The policy $polArn was successfully created.")
val roleArn = createRole(roleName, fileLocation)
println("$roleArn was successfully created.")
attachRolePolicy(roleName, polArn)
println("*** Wait for 1 MIN so the resource is available.")
delay(60000)
assumeGivenRole(roleArn, roleSessionName, bucketName)
println("*** Getting ready to delete the AWS resources.")
deleteRole(roleName, polArn)
deleteUser(userName)
println("This IAM Scenario has successfully completed.")
}
suspend fun createUser(usernameVal: String?): String? {
val request = CreateUserRequest {
userName = usernameVal
}
IamClient { region = "AWS_GLOBAL" }.use { iamClient ->
val response = iamClient.createUser(request)
return response.user?.userName
}
}
suspend fun createPolicy(policyNameVal: String?): String {
val policyDocumentValue: String = "{" +
" \"Version\": \"2012-10-17\"," +
" \"Statement\": [" +
" {" +
" \"Effect\": \"Allow\"," +
" \"Action\": [" +
" \"s3:*\"" +
" ]," +
" \"Resource\": \"*\"" +
" }" +
" ]" +
"}"
val request = CreatePolicyRequest {
policyName = policyNameVal
policyDocument = policyDocumentValue
}
IamClient { region = "AWS_GLOBAL" }.use { iamClient ->
val response = iamClient.createPolicy(request)
return response.policy?.arn.toString()
}
}
suspend fun createRole(rolenameVal: String?, fileLocation: String?): String? {
val jsonObject = fileLocation?.let { readJsonSimpleDemo(it) } as JSONObject
val request = CreateRoleRequest {
roleName = rolenameVal
assumeRolePolicyDocument = jsonObject.toJSONString()
description = "Created using the AWS SDK for Kotlin"
}
IamClient { region = "AWS_GLOBAL" }.use { iamClient ->
val response = iamClient.createRole(request)
return response.role?.arn
}
}
suspend fun attachRolePolicy(roleNameVal: String, policyArnVal: String) {
val request = ListAttachedRolePoliciesRequest {
roleName = roleNameVal
}
IamClient { region = "AWS_GLOBAL" }.use { iamClient ->
val response = iamClient.listAttachedRolePolicies(request)
val attachedPolicies = response.attachedPolicies
// Ensure that the policy is not attached to this role.
val checkStatus: Int
if (attachedPolicies != null) {
checkStatus = checkMyList(attachedPolicies, policyArnVal)
if (checkStatus == -1)
return
}
val policyRequest = AttachRolePolicyRequest {
roleName = roleNameVal
policyArn = policyArnVal
}
iamClient.attachRolePolicy(policyRequest)
println("Successfully attached policy $policyArnVal to role $roleNameVal")
}
}
fun checkMyList(attachedPolicies: List<AttachedPolicy>, policyArnVal: String): Int {
for (policy in attachedPolicies) {
val polArn = policy.policyArn.toString()
if (polArn.compareTo(policyArnVal) == 0) {
println("The policy is already attached to this role.")
return -1
}
}
return 0
}
suspend fun assumeGivenRole(roleArnVal: String?, roleSessionNameVal: String?, bucketName: String) {
val stsClient = StsClient {
region = "us-east-1"
}
val roleRequest = AssumeRoleRequest {
roleArn = roleArnVal
roleSessionName = roleSessionNameVal
}
val roleResponse = stsClient.assumeRole(roleRequest)
val myCreds = roleResponse.credentials
val key = myCreds?.accessKeyId
val secKey = myCreds?.secretAccessKey
val secToken = myCreds?.sessionToken
val staticCredentials = StaticCredentialsProvider {
accessKeyId = key
secretAccessKey = secKey
sessionToken = secToken
}
// List all objects in an Amazon S3 bucket using the temp creds.
val s3 = S3Client {
credentialsProvider = staticCredentials
region = "us-east-1"
}
println("Created a S3Client using temp credentials.")
println("Listing objects in $bucketName")
val listObjects = ListObjectsRequest {
bucket = bucketName
}
val response = s3.listObjects(listObjects)
response.contents?.forEach { myObject ->
println("The name of the key is ${myObject.key}")
println("The owner is ${myObject.owner}")
}
}
suspend fun deleteRole(roleNameVal: String, polArn: String) {
val iam = IamClient { region = "AWS_GLOBAL" }
// First the policy needs to be detached.
val rolePolicyRequest = DetachRolePolicyRequest {
policyArn = polArn
roleName = roleNameVal
}
iam.detachRolePolicy(rolePolicyRequest)
// Delete the policy.
val request = DeletePolicyRequest {
policyArn = polArn
}
iam.deletePolicy(request)
println("*** Successfully deleted $polArn")
// Delete the role.
val roleRequest = DeleteRoleRequest {
roleName = roleNameVal
}
iam.deleteRole(roleRequest)
println("*** Successfully deleted $roleNameVal")
}
suspend fun deleteUser(userNameVal: String) {
val iam = IamClient { region = "AWS_GLOBAL" }
val request = DeleteUserRequest {
userName = userNameVal
}
iam.deleteUser(request)
println("*** Successfully deleted $userNameVal")
}
@Throws(java.lang.Exception::class)
fun readJsonSimpleDemo(filename: String): Any? {
val reader = FileReader(filename)
val jsonParser = JSONParser()
return jsonParser.parse(reader)
}
// snippet-end:[iam.kotlin.scenario.main]
| apache-2.0 | dd7a4313b84644c8079fa7acd71ca98b | 30.646643 | 134 | 0.665007 | 4.416348 | false | false | false | false |
toddbernhard/server | src/main/kotlin/tech/pronghorn/http/protocol/HttpUrl.kt | 1 | 5578 | /*
* Copyright 2017 Pronghorn Technology 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 tech.pronghorn.http.protocol
import java.net.URLDecoder
import java.util.Arrays
import java.util.Objects
data class QueryParam(val name: ByteArray,
val value: ByteArray) {
constructor(name: String,
value: String) : this(name.toByteArray(Charsets.US_ASCII), value.toByteArray(Charsets.US_ASCII))
}
sealed class HttpUrlParseResult
object InvalidHttpUrl : HttpUrlParseResult()
object IncompleteHttpUrl : HttpUrlParseResult()
sealed class HttpUrl : HttpUrlParseResult() {
abstract fun getPathBytes(): ByteArray
abstract fun getPath(): String
abstract fun isSecure(): Boolean?
abstract fun getHostBytes(): ByteArray?
abstract fun getHost(): String?
abstract fun getPort(): Int?
abstract fun getQueryParams(): List<QueryParam>
override fun equals(other: Any?): Boolean {
return when (other) {
is HttpUrl -> {
return Arrays.equals(getPathBytes(), other.getPathBytes()) &&
isSecure() == other.isSecure() &&
Arrays.equals(getHostBytes(), other.getHostBytes()) &&
getPort() == other.getPort() &&
getQueryParams() == other.getQueryParams()
}
else -> false
}
}
override fun hashCode(): Int {
return Objects.hash(getPath(), isSecure(), getHost(), getPort(), getQueryParams())
}
override fun toString(): String {
return "[path='${getPath()}',isSecure=${isSecure()},host='${getHost()}',port=${getPort()},queryParams='${getQueryParams()}']"
}
}
private val rootBytes = byteArrayOf(forwardSlashByte)
class ByteArrayHttpUrl(private val path: ByteArray?,
private val isSecure: Boolean? = null,
private val host: ByteArray? = null,
private val port: Int? = null,
private val queryParams: ByteArray? = null,
private val pathContainsPercentEncoding: Boolean) : HttpUrl() {
override fun getPathBytes(): ByteArray {
if (path == null) {
return rootBytes
}
else {
return path
}
}
override fun getPath(): String {
if (path == null) {
return "/"
}
val pathString = path.toString()
if (!pathContainsPercentEncoding) {
return pathString
}
else {
return URLDecoder.decode(pathString, Charsets.UTF_8.name())
}
}
override fun isSecure(): Boolean? = isSecure
override fun getHostBytes(): ByteArray? = host
override fun getHost(): String? {
if (host == null) {
return null
}
return String(host, Charsets.US_ASCII)
}
override fun getPort(): Int? = port
override fun getQueryParams(): List<QueryParam> {
if(queryParams == null) {
return emptyList()
}
val params = mutableListOf<QueryParam>()
var x = 0
var nameStart = 0
var valueStart = -1
while(x < queryParams.size){
val byte = queryParams[x]
if(byte == equalsByte){
valueStart = x + 1
}
else if(byte == ampersandByte){
if(valueStart != -1){
val name = Arrays.copyOfRange(queryParams, nameStart, valueStart - nameStart - 1)
val value = Arrays.copyOfRange(queryParams, valueStart, x - valueStart)
params.add(QueryParam(name, value))
}
nameStart = x + 1
valueStart = -1
}
x += 1
}
if(valueStart != -1){
val name = Arrays.copyOfRange(queryParams, nameStart, valueStart - nameStart - 1)
val value = Arrays.copyOfRange(queryParams, valueStart, x - valueStart)
params.add(QueryParam(name, value))
}
return params
}
}
class ValueHttpUrl(private val path: String,
private val containsPercentEncoding: Boolean = false,
private val isSecure: Boolean? = null,
private val host: String? = null,
private val port: Int? = null,
private val queryParams: List<QueryParam> = emptyList()) : HttpUrl() {
override fun getPathBytes(): ByteArray = path.toByteArray(Charsets.US_ASCII)
override fun getPath(): String {
if (!containsPercentEncoding) {
return path
}
else {
return URLDecoder.decode(path, Charsets.UTF_8.name())
}
}
override fun isSecure(): Boolean? = isSecure
override fun getHostBytes(): ByteArray? = host?.toByteArray(Charsets.US_ASCII)
override fun getHost(): String? = host
override fun getPort(): Int? = port
override fun getQueryParams(): List<QueryParam> = queryParams
}
| apache-2.0 | 8dbf01fe981f88fe7bb9b08f3ad6ea89 | 31.242775 | 133 | 0.585335 | 4.984808 | false | false | false | false |
paplorinc/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/ui/table/Selection.kt | 2 | 4137 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.vcs.log.ui.table
import com.google.common.primitives.Ints
import com.intellij.ui.ScrollingUtil
import com.intellij.util.containers.ContainerUtil
import com.intellij.vcs.log.graph.VisibleGraph
import com.intellij.vcs.log.util.TroveUtil
import gnu.trove.TIntHashSet
import java.awt.Rectangle
import javax.swing.JTable
internal class Selection(private val table: VcsLogGraphTable) {
private val selectedCommits: TIntHashSet = TIntHashSet()
private val isOnTop: Boolean
private val scrollingTarget: ScrollingTarget?
init {
val selectedRows = ContainerUtil.sorted(Ints.asList(*table.selectedRows))
val selectedRowsToCommits = selectedRows.associateWith { table.visibleGraph.getRowInfo(it).commit }
TroveUtil.addAll(selectedCommits, selectedRowsToCommits.values)
val visibleRows = getVisibleRows(table)
if (visibleRows == null) {
isOnTop = false
scrollingTarget = null
}
else {
isOnTop = visibleRows.first == 0
val visibleRow = selectedRowsToCommits.values.find { visibleRows.contains(it) } ?: visibleRows.first
val visibleCommit = selectedRowsToCommits[visibleRow] ?: table.visibleGraph.getRowInfo(visibleRow).commit
scrollingTarget = ScrollingTarget(visibleCommit, getTopGap(visibleRow))
}
}
private fun getTopGap(row: Int) = table.getCellRect(row, 0, false).y - table.visibleRect.y
private fun getVisibleRows(table: JTable): IntRange? {
val visibleRows = ScrollingUtil.getVisibleRows(table)
val range = IntRange(visibleRows.first - 1, visibleRows.second)
if (range.isEmpty() || range.first < 0) return null
return range
}
fun restore(graph: VisibleGraph<Int>, scroll: Boolean, permanentGraphChanged: Boolean) {
val scrollToTop = isOnTop && permanentGraphChanged
val commitsToRows = mapCommitsToRows(graph, scroll && !scrollToTop)
table.selectionModel.valueIsAdjusting = true
for (commit in selectedCommits) {
val row = commitsToRows[commit]
if (row != null) {
table.addRowSelectionInterval(row, row)
}
}
table.selectionModel.valueIsAdjusting = false
if (scroll) {
if (scrollToTop) {
scrollToRow(0, 0)
}
else if (scrollingTarget != null) {
val scrollingTargetRow = commitsToRows[scrollingTarget.commit]
if (scrollingTargetRow != null) {
scrollToRow(scrollingTargetRow, scrollingTarget.topGap)
}
}
}
}
private fun mapCommitsToRows(graph: VisibleGraph<Int>, scroll: Boolean): MutableMap<Int, Int> {
val commits = mutableSetOf<Int>()
TroveUtil.addAll(commits, selectedCommits)
if (scroll && scrollingTarget != null) commits.add(scrollingTarget.commit)
return mapCommitsToRows(commits, graph)
}
private fun mapCommitsToRows(commits: MutableCollection<Int>, graph: VisibleGraph<Int>): MutableMap<Int, Int> {
val commitsToRows = mutableMapOf<Int, Int>()
for (row in 0 until graph.visibleCommitCount) {
val commit = graph.getRowInfo(row).commit
if (commits.remove(commit)) {
commitsToRows[commit] = row
}
if (commits.isEmpty()) break
}
return commitsToRows
}
private fun scrollToRow(row: Int?, delta: Int?) {
val startRect = table.getCellRect(row!!, 0, true)
table.scrollRectToVisible(Rectangle(startRect.x, Math.max(startRect.y - delta!!, 0),
startRect.width, table.visibleRect.height))
}
}
private data class ScrollingTarget(val commit: Int, val topGap: Int) | apache-2.0 | be8a6a99bf4972b9fd5c31c2796bc390 | 35.946429 | 113 | 0.715011 | 4.377778 | false | false | false | false |
StephenVinouze/AdvancedRecyclerView | pagination/src/main/kotlin/com/github/stephenvinouze/advancedrecyclerview/pagination/adapters/RecyclerPaginationAdapter.kt | 1 | 1759 | package com.github.stephenvinouze.advancedrecyclerview.pagination.adapters
import android.view.View
import android.view.ViewGroup
import com.github.stephenvinouze.advancedrecyclerview.core.adapters.RecyclerAdapter
import com.github.stephenvinouze.advancedrecyclerview.core.views.BaseViewHolder
/**
* Created by stephenvinouze on 10/11/2017.
*/
abstract class RecyclerPaginationAdapter<MODEL> : RecyclerAdapter<MODEL>() {
companion object {
private const val LOADING_VIEW_TYPE = 111
}
var isLoading = false
set(value) {
if (field != value) {
field = value
notifyItemRemoved(items.size)
}
}
override fun getItemCount(): Int =
if (isLoading) super.getItemCount() + 1 else super.getItemCount()
override fun getItemViewType(position: Int): Int =
if (isLoaderAt(position)) LOADING_VIEW_TYPE else super.getItemViewType(position)
override fun getItemId(position: Int): Long =
if (isLoaderAt(position)) Long.MAX_VALUE - LOADING_VIEW_TYPE else super.getItemId(position)
final override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder = when (viewType) {
LOADING_VIEW_TYPE -> BaseViewHolder(onCreateLoaderView(parent, viewType))
else -> super.onCreateViewHolder(parent, viewType)
}
final override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
if (getItemViewType(position) != LOADING_VIEW_TYPE) {
super.onBindViewHolder(holder, position)
}
}
private fun isLoaderAt(position: Int): Boolean =
isLoading && position == itemCount - 1
protected abstract fun onCreateLoaderView(parent: ViewGroup, viewType: Int): View
} | apache-2.0 | b6e201c91f073363de9b9634dadf1fc7 | 34.918367 | 111 | 0.699261 | 4.819178 | false | false | false | false |
google/intellij-community | uast/uast-java/src/org/jetbrains/uast/java/declarations/JavaUMethod.kt | 1 | 4396 | // 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.uast.java
import com.intellij.psi.*
import com.intellij.psi.impl.light.LightElement
import com.intellij.psi.impl.light.LightRecordCanonicalConstructor
import com.intellij.util.castSafelyTo
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.uast.*
import org.jetbrains.uast.internal.convertOrReport
import org.jetbrains.uast.java.internal.JavaUElementWithComments
@ApiStatus.Internal
open class JavaUMethod(
override val javaPsi: PsiMethod,
uastParent: UElement?
) : JavaAbstractUElement(uastParent), UMethod, JavaUElementWithComments, UAnchorOwner, PsiMethod by javaPsi {
@Suppress("OverridingDeprecatedMember")
override val psi
get() = javaPsi
override val sourcePsi: PsiElement?
get() =
// hah, there is a Lombok and Enums and also Records, so we have fake PsiElements even in Java (IDEA-216248)
javaPsi.takeIf { it !is LightElement }
override val uastBody: UExpression? by lz {
val body = sourcePsi.castSafelyTo<PsiMethod>()?.body ?: return@lz null
UastFacade.findPlugin(body)?.convertElement(body, this) as? UExpression
}
override val uAnnotations: List<UAnnotation> by lz { javaPsi.annotations.map { JavaUAnnotation(it, this) } }
override val uastParameters: List<UParameter> by lz {
javaPsi.parameterList.parameters.mapNotNull { convertOrReport(it, this) }
}
override fun getPsiParentForLazyConversion(): PsiElement? = super.getPsiParentForLazyConversion() ?: javaPsi.containingClass
override val uastAnchor: UIdentifier?
get() {
val psiElement = (sourcePsi as? PsiNameIdentifierOwner)?.nameIdentifier // return elements of library sources, do not switch to binary
?: (sourcePsi?.originalElement as? PsiNameIdentifierOwner)?.nameIdentifier
?: sourcePsi.castSafelyTo<PsiMethod>()?.nameIdentifier ?: return null
return UIdentifier(psiElement, this)
}
override fun equals(other: Any?): Boolean = other is JavaUMethod && javaPsi == other.javaPsi
override fun hashCode(): Int = javaPsi.hashCode()
companion object {
fun create(psiRecordHeader: PsiRecordHeader, containingElement: UElement?): JavaUMethod? {
val lightCanonicalConstructor = psiRecordHeader.containingClass?.constructors
?.filterIsInstance<LightRecordCanonicalConstructor>()?.firstOrNull() ?: return null
return JavaRecordConstructorUMethod(psiRecordHeader, lightCanonicalConstructor, containingElement)
}
fun create(psi: PsiMethod, languagePlugin: UastLanguagePlugin, containingElement: UElement?): JavaUMethod = when (psi) {
is LightRecordCanonicalConstructor -> {
val recordHeader = psi.containingClass.recordHeader
if (recordHeader != null)
JavaRecordConstructorUMethod(recordHeader, psi, containingElement)
else JavaUMethod(psi, containingElement)
}
is PsiAnnotationMethod -> JavaUAnnotationMethod(psi, languagePlugin, containingElement)
else -> JavaUMethod(psi, containingElement)
}
}
override val returnTypeReference: UTypeReferenceExpression? by lz {
javaPsi.returnTypeElement?.let { JavaUTypeReferenceExpression(it, this) }
}
override fun getOriginalElement(): PsiElement? = javaPsi.originalElement
}
private class JavaRecordConstructorUMethod(
val psiRecordHeader: PsiRecordHeader,
lightConstructor: LightRecordCanonicalConstructor,
uastParent: UElement?) : JavaUMethod(lightConstructor, uastParent) {
override val uastBody: UExpression? get() = null
override val sourcePsi: PsiElement get() = psiRecordHeader
override val uastAnchor: UIdentifier?
get() = psiRecordHeader.containingClass?.nameIdentifier?.let { UIdentifier(it, this) }
}
@ApiStatus.Internal
class JavaUAnnotationMethod(
override val javaPsi: PsiAnnotationMethod,
languagePlugin: UastLanguagePlugin,
containingElement: UElement?
) : JavaUMethod(javaPsi, containingElement), UAnnotationMethod, UDeclarationEx {
@Suppress("OverridingDeprecatedMember")
override val psi
get() = javaPsi
override val uastDefaultValue: UExpression? by lz {
val defaultValue = javaPsi.defaultValue ?: return@lz null
languagePlugin.convertElement(defaultValue, this, null) as? UExpression
}
}
| apache-2.0 | 9b31d977aca3271d3cc338b688628b69 | 39.703704 | 140 | 0.754095 | 5.245823 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/j2k/old-post-processing/src/org/jetbrains/kotlin/idea/j2k/old/post/processing/J2KPostProcessingRegistrarImpl.kt | 1 | 19282 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.j2k.old.post.processing
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.codeInsight.intentions.shared.RemoveUnnecessaryParenthesesIntention
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractApplicabilityBasedInspection
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.codeinsights.impl.base.KotlinInspectionFacade
import org.jetbrains.kotlin.idea.core.setVisibility
import org.jetbrains.kotlin.idea.inspections.*
import org.jetbrains.kotlin.idea.inspections.branchedTransformations.IfThenToElvisInspection
import org.jetbrains.kotlin.idea.inspections.branchedTransformations.IfThenToSafeAccessInspection
import org.jetbrains.kotlin.idea.inspections.conventionNameCalls.ReplaceGetOrSetInspection
import org.jetbrains.kotlin.idea.intentions.*
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.FoldIfToReturnAsymmetricallyIntention
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.FoldIfToReturnIntention
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isTrivialStatementBody
import org.jetbrains.kotlin.idea.j2k.J2KPostProcessingRegistrar
import org.jetbrains.kotlin.idea.j2k.J2kPostProcessing
import org.jetbrains.kotlin.idea.quickfix.RemoveModifierFixBase
import org.jetbrains.kotlin.idea.quickfix.RemoveUselessCastFix
import org.jetbrains.kotlin.idea.quickfix.asKotlinIntentionActionsFactory
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getChildOfType
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import org.jetbrains.kotlin.psi.psiUtil.visibilityModifierType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.utils.mapToIndex
import java.util.*
internal class J2KPostProcessingRegistrarImpl : J2KPostProcessingRegistrar {
private val myProcessings = ArrayList<J2kPostProcessing>()
override val processings: Collection<J2kPostProcessing>
get() = myProcessings
private val processingsToPriorityMap = HashMap<J2kPostProcessing, Int>()
override fun priority(processing: J2kPostProcessing): Int = processingsToPriorityMap[processing]!!
init {
myProcessings.add(RemoveExplicitTypeArgumentsProcessing())
myProcessings.add(RemoveRedundantOverrideVisibilityProcessing())
registerInspectionBasedProcessing(MoveLambdaOutsideParenthesesInspection())
myProcessings.add(FixObjectStringConcatenationProcessing())
myProcessings.add(ConvertToStringTemplateProcessing())
myProcessings.add(UsePropertyAccessSyntaxProcessing())
myProcessings.add(UninitializedVariableReferenceFromInitializerToThisReferenceProcessing())
myProcessings.add(UnresolvedVariableReferenceFromInitializerToThisReferenceProcessing())
myProcessings.add(RemoveRedundantSamAdaptersProcessing())
myProcessings.add(RemoveRedundantCastToNullableProcessing())
registerInspectionBasedProcessing(ReplacePutWithAssignmentInspection())
myProcessings.add(UseExpressionBodyProcessing())
registerInspectionBasedProcessing(UnnecessaryVariableInspection())
registerInspectionBasedProcessing(FoldInitializerAndIfToElvisInspection())
registerIntentionBasedProcessing(FoldIfToReturnIntention()) {
it.then.isTrivialStatementBody() && it.`else`.isTrivialStatementBody()
}
registerIntentionBasedProcessing(FoldIfToReturnAsymmetricallyIntention()) {
it.then.isTrivialStatementBody() && (KtPsiUtil.skipTrailingWhitespacesAndComments(
it
) as KtReturnExpression).returnedExpression.isTrivialStatementBody()
}
registerInspectionBasedProcessing(IfThenToSafeAccessInspection())
registerInspectionBasedProcessing(IfThenToElvisInspection(true))
registerInspectionBasedProcessing(KotlinInspectionFacade.instance.simplifyNegatedBinaryExpression)
registerInspectionBasedProcessing(ReplaceGetOrSetInspection())
registerInspectionBasedProcessing(AddOperatorModifierInspection())
registerIntentionBasedProcessing(ObjectLiteralToLambdaIntention())
registerIntentionBasedProcessing(AnonymousFunctionToLambdaIntention())
registerIntentionBasedProcessing(RemoveUnnecessaryParenthesesIntention())
registerIntentionBasedProcessing(DestructureIntention())
registerInspectionBasedProcessing(SimplifyAssertNotNullInspection())
registerIntentionBasedProcessing(RemoveRedundantCallsOfConversionMethodsIntention())
registerInspectionBasedProcessing(JavaMapForEachInspection())
registerInspectionBasedProcessing(ReplaceGuardClauseWithFunctionCallInspection())
registerDiagnosticBasedProcessing<KtBinaryExpressionWithTypeRHS>(Errors.USELESS_CAST) { element, _ ->
val expression = RemoveUselessCastFix.invoke(element)
val variable = expression.parent as? KtProperty
if (variable != null && expression == variable.initializer && variable.isLocal) {
val ref = ReferencesSearch.search(variable, LocalSearchScope(variable.containingFile)).findAll().singleOrNull()
if (ref != null && ref.element is KtSimpleNameExpression) {
ref.element.replace(expression)
variable.delete()
}
}
}
registerDiagnosticBasedProcessing<KtTypeProjection>(Errors.REDUNDANT_PROJECTION) { _, diagnostic ->
val fix = RemoveModifierFixBase.createRemoveProjectionFactory(true)
.asKotlinIntentionActionsFactory()
.createActions(diagnostic).single() as RemoveModifierFixBase
fix.invoke()
}
registerDiagnosticBasedProcessingFactory(
Errors.VAL_REASSIGNMENT, Errors.CAPTURED_VAL_INITIALIZATION, Errors.CAPTURED_MEMBER_VAL_INITIALIZATION
) { element: KtSimpleNameExpression, _: Diagnostic ->
val property = element.mainReference.resolve() as? KtProperty
if (property == null) {
null
} else {
{
if (!property.isVar) {
property.valOrVarKeyword.replace(KtPsiFactory(element.project).createVarKeyword())
}
}
}
}
registerDiagnosticBasedProcessing<KtSimpleNameExpression>(Errors.UNNECESSARY_NOT_NULL_ASSERTION) { element, _ ->
val exclExclExpr = element.parent as KtUnaryExpression
val baseExpression = exclExclExpr.baseExpression!!
val context = baseExpression.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS)
if (context.diagnostics.forElement(element).any { it.factory == Errors.UNNECESSARY_NOT_NULL_ASSERTION }) {
exclExclExpr.replace(baseExpression)
}
}
processingsToPriorityMap.putAll(myProcessings.mapToIndex())
}
private inline fun <reified TElement : KtElement, TIntention : SelfTargetingRangeIntention<TElement>> registerIntentionBasedProcessing(
intention: TIntention,
noinline additionalChecker: (TElement) -> Boolean = { true }
) {
myProcessings.add(object : J2kPostProcessing {
// Intention can either need or not need write action
override val writeActionNeeded = intention.startInWriteAction()
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (!TElement::class.java.isInstance(element)) return null
val tElement = element as TElement
if (intention.applicabilityRange(tElement) == null) return null
if (!additionalChecker(tElement)) return null
return {
if (intention.applicabilityRange(tElement) != null) { // check availability of the intention again because something could change
intention.applyTo(element, null)
}
}
}
})
}
private inline fun
<reified TElement : KtElement,
TInspection : AbstractApplicabilityBasedInspection<TElement>> registerInspectionBasedProcessing(
inspection: TInspection,
acceptInformationLevel: Boolean = false
) {
myProcessings.add(object : J2kPostProcessing {
// Inspection can either need or not need write action
override val writeActionNeeded = inspection.startFixInWriteAction
private fun isApplicable(element: TElement): Boolean {
if (!inspection.isApplicable(element)) return false
return acceptInformationLevel || inspection.inspectionHighlightType(element) != ProblemHighlightType.INFORMATION
}
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (!TElement::class.java.isInstance(element)) return null
val tElement = element as TElement
if (!isApplicable(tElement)) return null
return {
if (isApplicable(tElement)) { // check availability of the inspection again because something could change
inspection.applyTo(tElement)
}
}
}
})
}
private inline fun <reified TElement : KtElement> registerDiagnosticBasedProcessing(
vararg diagnosticFactory: DiagnosticFactory<*>,
crossinline fix: (TElement, Diagnostic) -> Unit
) {
registerDiagnosticBasedProcessingFactory(*diagnosticFactory) { element: TElement, diagnostic: Diagnostic ->
{
fix(
element,
diagnostic
)
}
}
}
private inline fun <reified TElement : KtElement> registerDiagnosticBasedProcessingFactory(
vararg diagnosticFactory: DiagnosticFactory<*>,
crossinline fixFactory: (TElement, Diagnostic) -> (() -> Unit)?
) {
myProcessings.add(object : J2kPostProcessing {
// ???
override val writeActionNeeded = true
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (!TElement::class.java.isInstance(element)) return null
val diagnostic = diagnostics.forElement(element).firstOrNull { it.factory in diagnosticFactory } ?: return null
return fixFactory(element as TElement, diagnostic)
}
})
}
private class RemoveExplicitTypeArgumentsProcessing : J2kPostProcessing {
override val writeActionNeeded = true
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element !is KtTypeArgumentList || !RemoveExplicitTypeArgumentsIntention.isApplicableTo(
element,
approximateFlexible = true
)
) return null
return {
if (RemoveExplicitTypeArgumentsIntention.isApplicableTo(element, approximateFlexible = true)) {
element.delete()
}
}
}
}
private class RemoveRedundantOverrideVisibilityProcessing : J2kPostProcessing {
override val writeActionNeeded = true
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element !is KtCallableDeclaration || !element.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return null
val modifier = element.visibilityModifierType() ?: return null
return { element.setVisibility(modifier) }
}
}
private class ConvertToStringTemplateProcessing : J2kPostProcessing {
override val writeActionNeeded = true
private val intention = ConvertToStringTemplateIntention()
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element is KtBinaryExpression && intention.isApplicableTo(element) && ConvertToStringTemplateIntention.shouldSuggestToConvert(
element
)
) {
return { intention.applyTo(element, null) }
} else {
return null
}
}
}
private class UsePropertyAccessSyntaxProcessing : J2kPostProcessing {
override val writeActionNeeded = true
private val intention = UsePropertyAccessSyntaxIntention()
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element !is KtCallExpression) return null
val propertyName = intention.detectPropertyNameToUse(element) ?: return null
return { intention.applyTo(element, propertyName, reformat = true) }
}
}
private class RemoveRedundantSamAdaptersProcessing : J2kPostProcessing {
override val writeActionNeeded = true
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element !is KtCallExpression) return null
val expressions = RedundantSamConstructorInspection.samConstructorCallsToBeConverted(element)
if (expressions.isEmpty()) return null
return {
RedundantSamConstructorInspection.samConstructorCallsToBeConverted(element)
.forEach { RedundantSamConstructorInspection.replaceSamConstructorCall(it) }
}
}
}
private class UseExpressionBodyProcessing : J2kPostProcessing {
override val writeActionNeeded = true
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element !is KtPropertyAccessor) return null
val inspection = UseExpressionBodyInspection(convertEmptyToUnit = false)
if (!inspection.isActiveFor(element)) return null
return {
if (inspection.isActiveFor(element)) {
inspection.simplify(element, false)
}
}
}
}
private class RemoveRedundantCastToNullableProcessing : J2kPostProcessing {
override val writeActionNeeded = true
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element !is KtBinaryExpressionWithTypeRHS) return null
val context = element.analyze()
val leftType = context.getType(element.left) ?: return null
val rightType = context.get(BindingContext.TYPE, element.right) ?: return null
if (!leftType.isMarkedNullable && rightType.isMarkedNullable) {
return {
val type = element.right?.typeElement as? KtNullableType
type?.replace(type.innerType!!)
}
}
return null
}
}
private class FixObjectStringConcatenationProcessing : J2kPostProcessing {
override val writeActionNeeded = true
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element !is KtBinaryExpression ||
element.operationToken != KtTokens.PLUS ||
diagnostics.forElement(element.operationReference).none {
it.factory == Errors.UNRESOLVED_REFERENCE_WRONG_RECEIVER
|| it.factory == Errors.NONE_APPLICABLE
}
)
return null
val bindingContext = element.analyze()
val rightType = element.right?.getType(bindingContext) ?: return null
if (KotlinBuiltIns.isString(rightType)) {
return {
val psiFactory = KtPsiFactory(element.project)
element.left!!.replace(psiFactory.buildExpression {
appendFixedText("(")
appendExpression(element.left)
appendFixedText(").toString()")
})
}
}
return null
}
}
private class UninitializedVariableReferenceFromInitializerToThisReferenceProcessing : J2kPostProcessing {
override val writeActionNeeded = true
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element !is KtSimpleNameExpression || diagnostics.forElement(element)
.none { it.factory == Errors.UNINITIALIZED_VARIABLE }
) return null
val resolved = element.mainReference.resolve() ?: return null
if (resolved.isAncestor(element, strict = true)) {
if (resolved is KtVariableDeclaration && resolved.hasInitializer()) {
val anonymousObject = element.getParentOfType<KtClassOrObject>(true) ?: return null
if (resolved.initializer!!.getChildOfType<KtClassOrObject>() == anonymousObject) {
return { element.replaced(KtPsiFactory(element.project).createThisExpression()) }
}
}
}
return null
}
}
private class UnresolvedVariableReferenceFromInitializerToThisReferenceProcessing : J2kPostProcessing {
override val writeActionNeeded = true
override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? {
if (element !is KtSimpleNameExpression || diagnostics.forElement(element)
.none { it.factory == Errors.UNRESOLVED_REFERENCE }
) return null
val anonymousObject = element.getParentOfType<KtClassOrObject>(true) ?: return null
val variable = anonymousObject.getParentOfType<KtVariableDeclaration>(true) ?: return null
if (variable.nameAsName == element.getReferencedNameAsName() &&
variable.initializer?.getChildOfType<KtClassOrObject>() == anonymousObject
) {
return { element.replaced(KtPsiFactory(element.project).createThisExpression()) }
}
return null
}
}
} | apache-2.0 | 9aa3999a3ed701dbea9dd0807cf9a30b | 46.146699 | 149 | 0.678508 | 6.288976 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/view/step_quiz_review/ui/fragment/StepQuizReviewTeacherFragment.kt | 1 | 11289 | package org.stepik.android.view.step_quiz_review.ui.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.text.HtmlCompat
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.jakewharton.rxrelay2.BehaviorRelay
import kotlinx.android.synthetic.main.error_no_connection_with_button_small.view.*
import kotlinx.android.synthetic.main.fragment_step_quiz.*
import kotlinx.android.synthetic.main.fragment_step_quiz.view.*
import kotlinx.android.synthetic.main.fragment_step_quiz_review_teacher.*
import kotlinx.android.synthetic.main.fragment_step_quiz_review_teacher.view.*
import kotlinx.android.synthetic.main.view_step_quiz_submit_button.*
import org.stepic.droid.R
import org.stepic.droid.analytic.Analytic
import org.stepic.droid.base.App
import org.stepic.droid.persistence.model.StepPersistentWrapper
import org.stepic.droid.ui.util.collapse
import org.stepic.droid.ui.util.expand
import org.stepic.droid.ui.util.snackbar
import org.stepik.android.domain.lesson.model.LessonData
import org.stepik.android.domain.step_quiz.model.StepQuizLessonData
import org.stepik.android.model.ReviewStrategyType
import org.stepik.android.presentation.step_quiz.StepQuizFeature
import org.stepik.android.presentation.step_quiz.model.ReplyResult
import org.stepik.android.presentation.step_quiz_review.StepQuizReviewTeacherFeature
import org.stepik.android.presentation.step_quiz_review.StepQuizReviewTeacherViewModel
import org.stepik.android.view.lesson.ui.interfaces.Moveable
import org.stepik.android.view.step.ui.interfaces.StepMenuNavigator
import org.stepik.android.view.step_quiz.ui.delegate.StepQuizDelegate
import org.stepik.android.view.step_quiz.ui.delegate.StepQuizFeedbackBlocksDelegate
import org.stepik.android.view.step_quiz.ui.factory.StepQuizFormFactory
import org.stepik.android.view.step_quiz.ui.factory.StepQuizViewStateDelegateFactory
import org.stepik.android.view.step_quiz_review.ui.factory.StepQuizFormReviewFactory
import org.stepik.android.view.ui.delegate.ViewStateDelegate
import ru.nobird.app.core.model.safeCast
import ru.nobird.app.presentation.redux.container.ReduxView
import ru.nobird.android.view.base.ui.extension.argument
import ru.nobird.android.view.base.ui.extension.toPx
import ru.nobird.android.view.redux.ui.extension.reduxViewModel
import javax.inject.Inject
class StepQuizReviewTeacherFragment :
Fragment(),
ReduxView<StepQuizReviewTeacherFeature.State, StepQuizReviewTeacherFeature.Action.ViewAction> {
companion object {
val supportedQuizTypes = StepQuizReviewFragment.supportedQuizTypes
fun newInstance(stepId: Long, instructionType: ReviewStrategyType): Fragment =
StepQuizReviewTeacherFragment()
.apply {
this.stepId = stepId
this.instructionType = instructionType
}
}
@Inject
internal lateinit var analytic: Analytic
@Inject
internal lateinit var stepQuizViewStateDelegateFactory: StepQuizViewStateDelegateFactory
@Inject
internal lateinit var viewModelFactory: ViewModelProvider.Factory
@Inject
internal lateinit var stepWrapperRxRelay: BehaviorRelay<StepPersistentWrapper>
@Inject
internal lateinit var lessonData: LessonData
private val stepQuizReviewTeacherViewModel: StepQuizReviewTeacherViewModel by reduxViewModel(this) { viewModelFactory }
private var stepId: Long by argument()
private var instructionType: ReviewStrategyType by argument()
private lateinit var stepWrapper: StepPersistentWrapper
private lateinit var stepQuizFormFactory: StepQuizFormFactory
private lateinit var quizLayout: View
private lateinit var quizDelegate: StepQuizDelegate
private lateinit var viewStateDelegate: ViewStateDelegate<StepQuizReviewTeacherFeature.State>
private lateinit var quizViewStateDelegate: ViewStateDelegate<StepQuizFeature.State>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
injectComponent()
stepWrapper = stepWrapperRxRelay.value ?: throw IllegalStateException("Step wrapper cannot be null")
stepQuizFormFactory = StepQuizFormReviewFactory(childFragmentManager, ::syncReplyState)
}
private fun injectComponent() {
App.componentManager()
.stepComponent(stepId)
.inject(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
val view = inflater.inflate(R.layout.fragment_step_quiz_review_teacher, container, false)
val quizContainer = view.stepQuizReviewTeacherQuiz as ConstraintLayout
val quizLayoutRes = stepQuizFormFactory.getLayoutResForStep(stepWrapper.step.block?.name)
quizLayout = inflater.inflate(quizLayoutRes, quizContainer, false)
quizContainer.addView(quizLayout)
realignQuizLayout(quizContainer, quizLayout)
return view
}
/**
* Align quiz container as vertical linear layout for smooth collapsing animation
*/
private fun realignQuizLayout(quizContainer: ConstraintLayout, quizLayout: View) {
val feedbackBlocks = quizContainer.stepQuizFeedbackBlocks
quizLayout.updateLayoutParams<ConstraintLayout.LayoutParams> {
bottomToTop = ConstraintLayout.LayoutParams.UNSET
}
feedbackBlocks.updateLayoutParams<ConstraintLayout.LayoutParams> {
bottomToTop = ConstraintLayout.LayoutParams.UNSET
topToBottom = quizLayout.id
topMargin = 16.toPx()
}
quizContainer.stepQuizActionContainer.updateLayoutParams<ConstraintLayout.LayoutParams> {
topToBottom = feedbackBlocks.id
topMargin = 16.toPx()
bottomMargin = 16.toPx()
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
viewStateDelegate = ViewStateDelegate()
viewStateDelegate.addState<StepQuizReviewTeacherFeature.State.Idle>(
stepQuizReviewTeacherQuizSkeleton,
stepQuizReviewTeacherButtonSkeleton
)
viewStateDelegate.addState<StepQuizReviewTeacherFeature.State.Loading>(
stepQuizReviewTeacherQuizSkeleton,
stepQuizReviewTeacherButtonSkeleton
)
viewStateDelegate.addState<StepQuizReviewTeacherFeature.State.Error>(
stepQuizReviewTeacherNetworkError
)
viewStateDelegate.addState<StepQuizReviewTeacherFeature.State.Data>(
stepQuizReviewTeacherSpoiler,
stepQuizReviewTeacherContainer,
stepQuizReviewTeacherDescription,
stepQuizReviewTeacherSubmissions
)
quizViewStateDelegate = stepQuizViewStateDelegateFactory
.create(stepQuizReviewTeacherQuiz, quizLayout)
val blockName = stepWrapper.step.block?.name
stepQuizReviewTeacherSpoiler.setOnClickListener {
stepQuizReviewTeacherArrow.changeState()
if (stepQuizReviewTeacherArrow.isExpanded()) {
stepQuizReviewTeacherContainer.expand()
} else {
stepQuizReviewTeacherContainer.collapse()
}
}
stepQuizReviewTeacherMessage.isVisible = false
val stepQuizBlockDelegate =
StepQuizFeedbackBlocksDelegate(stepQuizFeedbackBlocks, isTeacher = false, hasReview = false) {}
quizDelegate =
StepQuizDelegate(
step = stepWrapper.step,
stepQuizLessonData = StepQuizLessonData(lessonData),
stepQuizFormDelegate = stepQuizFormFactory.getDelegateForStep(blockName, view) ?: throw IllegalStateException("Unsupported quiz"),
stepQuizFeedbackBlocksDelegate = stepQuizBlockDelegate,
stepQuizActionButton = stepQuizAction,
stepRetryButton = stepQuizRetry,
stepQuizDiscountingPolicy = stepQuizDiscountingPolicy,
stepQuizReviewTeacherMessage = null,
onNewMessage = {
stepQuizReviewTeacherViewModel.onNewMessage(StepQuizReviewTeacherFeature.Message.StepQuizMessage(it))
},
onNextClicked = {
(parentFragment as? Moveable)?.move()
}
)
stepQuizReviewTeacherNetworkError.tryAgain.setOnClickListener {
stepQuizReviewTeacherViewModel
.onNewMessage(StepQuizReviewTeacherFeature.Message.InitWithStep(stepWrapper, lessonData, instructionType, forceUpdate = true))
}
stepQuizNetworkError.tryAgain.setOnClickListener {
val quizMessage = StepQuizFeature.Message.InitWithStep(stepWrapper, lessonData, forceUpdate = true)
stepQuizReviewTeacherViewModel
.onNewMessage(StepQuizReviewTeacherFeature.Message.StepQuizMessage(quizMessage))
}
stepQuizReviewTeacherSubmissions.setOnClickListener {
parentFragment.safeCast<StepMenuNavigator>()
?.showSubmissions()
}
}
override fun render(state: StepQuizReviewTeacherFeature.State) {
viewStateDelegate.switchState(state)
if (state is StepQuizReviewTeacherFeature.State.Data) {
stepQuizReviewTeacherContainer.isVisible =
stepQuizReviewTeacherArrow.isExpanded()
quizViewStateDelegate.switchState(state.quizState)
stepQuizReviewTeacherMessage.isVisible = false
if (state.quizState is StepQuizFeature.State.AttemptLoaded) {
quizDelegate.setState(state.quizState)
}
stepQuizReviewTeacherDescription.text =
when (state.instructionType) {
ReviewStrategyType.INSTRUCTOR ->
if (state.availableReviewCount > 0) {
val submissions = resources.getQuantityString(R.plurals.solutions, state.availableReviewCount, state.availableReviewCount)
HtmlCompat.fromHtml(getString(R.string.step_quiz_review_teacher_notice_instructors_submissions, submissions), HtmlCompat.FROM_HTML_MODE_COMPACT)
} else {
getString(R.string.step_quiz_review_teacher_notice_instructors_no_submissions)
}
ReviewStrategyType.PEER ->
getString(R.string.step_quiz_review_teacher_notice_peer)
}
}
}
override fun onAction(action: StepQuizReviewTeacherFeature.Action.ViewAction) {
when (action) {
StepQuizReviewTeacherFeature.Action.ViewAction.ShowNetworkError ->
view?.snackbar(messageRes = R.string.no_connection)
}
}
private fun syncReplyState(replyResult: ReplyResult) {
stepQuizReviewTeacherViewModel.onNewMessage(
StepQuizReviewTeacherFeature.Message.StepQuizMessage(
StepQuizFeature.Message.SyncReply(replyResult.reply)))
}
} | apache-2.0 | 2ba3405a878442cb58bd2764e88281f4 | 43.27451 | 172 | 0.723448 | 5.667169 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/io/github/chrislo27/rhre3/stage/bg/PolyrhythmBackground.kt | 2 | 2415 | package io.github.chrislo27.rhre3.stage.bg
class PolyrhythmBackground(id: String) : BlockBasedBackground(id) {
companion object {
private val borderedFace = Face(3, 0)
private val borderedRedFace = Face(0, 1)
private val polyFace = Face(1, 1)
private val polyRedFace = Face(2, 1)
val POLY_FLOOR: Block = Block("poly_floor", polyFace, polyFace, polyFace)
val POLY_REDLINE_FLOOR: Block = Block("poly_floor_redline", polyFace, polyRedFace, polyRedFace)
val POLY_PLATFORM: Block = Block("poly_platform", borderedFace, borderedFace, borderedFace)
val POLY_REDLINE_PLATFORM: Block = Block("poly_platform_redline", borderedFace, borderedRedFace, borderedRedFace)
}
override val map: Map = Map(17, 5, 16, 30f, 30f, xMultiplier = 1.1f, zMultiplier = 1.1f)
override fun buildMap() {
camera.apply {
position.y = 11.75f
position.x = 1f
update()
}
map.iterateSorted { _, x, y, z ->
map.setBlock(if (y >= map.sizeY - 2) Block.NOTHING else POLY_FLOOR, x, y, z)
map.setMetadata(0.toByte(), x, y, z)
}
val aPlatformStart = 5
val redLine = 4
for (x in 0 until map.sizeX) {
for (z in 0..2) {
map.setBlock(Block.NOTHING, x, map.sizeY - 3, z)
}
}
for (x in 0 until map.sizeX) {
map.setBlock(POLY_FLOOR, x, map.sizeY - 2, aPlatformStart + 7)
map.setBlock(POLY_FLOOR, x, map.sizeY - 1, aPlatformStart + 8)
}
for (x in 0 until map.sizeX) {
map.setBlock(POLY_PLATFORM, x, map.sizeY - (if (x <= redLine) 2 else 3), aPlatformStart)
map.setBlock(POLY_PLATFORM, x, map.sizeY - (if (x <= redLine) 2 else 3), aPlatformStart + 3)
}
for (z in 0 until map.sizeZ) {
for (y in map.sizeY downTo 0) {
val block = map.getBlock(redLine, y, z)
if (block != Block.NOTHING) {
map.setBlock(when (block) {
POLY_FLOOR -> POLY_REDLINE_FLOOR
POLY_PLATFORM -> POLY_REDLINE_PLATFORM
else -> block
}, redLine, y, z)
break
}
}
}
}
} | gpl-3.0 | 70d41f034f0f4796f757ba0b2ab71728 | 36.75 | 121 | 0.521325 | 3.965517 | false | false | false | false |
allotria/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/generators/Generators.kt | 3 | 34609 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:Suppress("unused")
package com.intellij.testGuiFramework.generators
import com.intellij.icons.AllIcons
import com.intellij.ide.plugins.PluginTable
import com.intellij.ide.projectView.impl.ProjectViewTree
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.actionSystem.impl.ActionMenu
import com.intellij.openapi.actionSystem.impl.ActionMenuItem
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl
import com.intellij.openapi.editor.impl.EditorComponentImpl
import com.intellij.openapi.ui.*
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.ex.WindowManagerEx
import com.intellij.openapi.wm.impl.welcomeScreen.FlatWelcomeFrame
import com.intellij.testGuiFramework.cellReader.ExtendedJListCellReader
import com.intellij.testGuiFramework.cellReader.ExtendedJTableCellReader
import com.intellij.testGuiFramework.driver.CheckboxTreeDriver
import com.intellij.testGuiFramework.fixtures.MainToolbarFixture
import com.intellij.testGuiFramework.fixtures.MessagesFixture
import com.intellij.testGuiFramework.fixtures.NavigationBarFixture
import com.intellij.testGuiFramework.fixtures.SettingsTreeFixture
import com.intellij.testGuiFramework.fixtures.extended.getPathStrings
import com.intellij.testGuiFramework.framework.GuiTestUtil
import com.intellij.testGuiFramework.generators.Utils.clicks
import com.intellij.testGuiFramework.generators.Utils.convertSimpleTreeItemToPath
import com.intellij.testGuiFramework.generators.Utils.findBoundedText
import com.intellij.testGuiFramework.generators.Utils.getCellText
import com.intellij.testGuiFramework.generators.Utils.getJTreePath
import com.intellij.testGuiFramework.generators.Utils.getJTreePathItemsString
import com.intellij.testGuiFramework.generators.Utils.withRobot
import com.intellij.testGuiFramework.impl.GuiTestUtilKt
import com.intellij.testGuiFramework.impl.GuiTestUtilKt.getComponentText
import com.intellij.testGuiFramework.impl.GuiTestUtilKt.isTextComponent
import com.intellij.testGuiFramework.impl.GuiTestUtilKt.onHeightCenter
import com.intellij.ui.CheckboxTree
import com.intellij.ui.EditorNotificationPanel
import com.intellij.ui.HyperlinkLabel
import com.intellij.ui.InplaceButton
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.JBList
import com.intellij.ui.components.JBTabbedPane
import com.intellij.ui.components.labels.ActionLink
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.ui.messages.SheetController
import com.intellij.ui.tabs.impl.TabLabel
import com.intellij.ui.treeStructure.SimpleTree
import com.intellij.ui.treeStructure.treetable.TreeTable
import com.intellij.util.ui.tree.TreeUtil
import org.fest.reflect.core.Reflection.field
import org.fest.swing.core.BasicRobot
import org.fest.swing.core.ComponentMatcher
import org.fest.swing.core.GenericTypeMatcher
import org.fest.swing.core.Robot
import org.fest.swing.exception.ComponentLookupException
import java.awt.*
import java.awt.event.MouseEvent
import java.io.File
import java.net.URI
import java.nio.file.Paths
import java.util.*
import java.util.jar.JarFile
import javax.swing.*
import javax.swing.plaf.basic.BasicArrowButton
import javax.swing.tree.TreeNode
import javax.swing.tree.TreePath
//**********COMPONENT GENERATORS**********
private const val leftButton = MouseEvent.BUTTON1
private const val rightButton = MouseEvent.BUTTON3
private fun MouseEvent.isLeftButton() = (this.button == leftButton)
private fun MouseEvent.isRightButton() = (this.button == rightButton)
class JButtonGenerator : ComponentCodeGenerator<JButton> {
override fun accept(cmp: Component): Boolean = cmp is JButton
override fun generate(cmp: JButton, me: MouseEvent, cp: Point): String = """button("${cmp.text}").click()"""
}
class InplaceButtonGenerator : ComponentCodeGenerator<InplaceButton> {
override fun accept(cmp: Component): Boolean = cmp is InplaceButton
override fun generate(cmp: InplaceButton, me: MouseEvent, cp: Point): String = """inplaceButton(${getIconClassName(cmp)}).click()"""
private fun getIconClassName(inplaceButton: InplaceButton): String {
val icon = inplaceButton.icon
val iconField = AllIcons::class.java.classes.flatMap { it.fields.filter { it.type == Icon::class.java } }.firstOrNull {
it.get(null) is Icon && (it.get(null) as Icon) == icon
} ?: return "REPLACE IT WITH ICON $icon"
return "${iconField.declaringClass?.canonicalName}.${iconField.name}"
}
}
class JSpinnerGenerator : ComponentCodeGenerator<JButton> {
override fun accept(cmp: Component): Boolean = cmp.parent is JSpinner
override fun priority(): Int = 1
override fun generate(cmp: JButton, me: MouseEvent, cp: Point): String {
val labelText = Utils.getBoundedLabel(cmp.parent).text
return if (cmp.name.contains("nextButton"))
"""spinner("$labelText").increment()"""
else
"""spinner("$labelText").decrement()"""
}
}
class TreeTableGenerator : ComponentCodeGenerator<TreeTable> {
override fun accept(cmp: Component): Boolean = cmp is TreeTable
override fun generate(cmp: TreeTable, me: MouseEvent, cp: Point): String {
val path = cmp.tree.getClosestPathForLocation(cp.x, cp.y)
val treeStringPath = getJTreePath(cmp.tree, path)
val column = cmp.columnAtPoint(cp)
return """treeTable().clickColumn($column, $treeStringPath)"""
}
override fun priority(): Int = 10
}
class ComponentWithBrowseButtonGenerator : ComponentCodeGenerator<FixedSizeButton> {
override fun accept(cmp: Component): Boolean {
return cmp.parent.parent is ComponentWithBrowseButton<*>
}
override fun generate(cmp: FixedSizeButton, me: MouseEvent, cp: Point): String {
val componentWithBrowseButton = cmp.parent.parent
val labelText = Utils.getBoundedLabel(componentWithBrowseButton).text
return """componentWithBrowseButton("$labelText").clickButton()"""
}
}
class ActionButtonGenerator : ComponentCodeGenerator<ActionButton> {
override fun accept(cmp: Component): Boolean = cmp is ActionButton
override fun generate(cmp: ActionButton, me: MouseEvent, cp: Point): String {
val text = cmp.action.templatePresentation.text
val simpleClassName = cmp.action.javaClass.simpleName
val result: String = if (text.isNullOrEmpty())
"""actionButtonByClass("$simpleClassName").click()"""
else
"""actionButton("$text").click()"""
return result
}
}
class ActionLinkGenerator : ComponentCodeGenerator<ActionLink> {
override fun priority(): Int = 1
override fun accept(cmp: Component): Boolean = cmp is ActionLink
override fun generate(cmp: ActionLink, me: MouseEvent, cp: Point): String = """actionLink("${cmp.text}").click()"""
}
class JTextFieldGenerator : ComponentCodeGenerator<JTextField> {
override fun accept(cmp: Component): Boolean = cmp is JTextField
override fun generate(cmp: JTextField, me: MouseEvent, cp: Point): String = """textfield("${findBoundedText(cmp).orEmpty()}").${clicks(
me)}"""
}
class JBListGenerator : ComponentCodeGenerator<JBList<*>> {
override fun priority(): Int = 1
override fun accept(cmp: Component): Boolean = cmp is JBList<*>
private fun JBList<*>.isPopupList() = this.javaClass.name.toLowerCase().contains("listpopup")
private fun JBList<*>.isFrameworksTree() = this.javaClass.name.toLowerCase().contains("AddSupportForFrameworksPanel".toLowerCase())
override fun generate(cmp: JBList<*>, me: MouseEvent, cp: Point): String {
val cellText = getCellText(cmp, cp).orEmpty()
if (cmp.isPopupList()) return """popupMenu("$cellText").clickSearchedItem()"""
if (me.button == MouseEvent.BUTTON2) return """jList("$cellText").item("$cellText").rightClick()"""
if (me.clickCount == 2) return """jList("$cellText").doubleClickItem("$cellText")"""
return """jList("$cellText").clickItem("$cellText")"""
}
}
class BasicComboPopupGenerator : ComponentCodeGenerator<JList<*>> {
override fun accept(cmp: Component): Boolean = cmp is JList<*> && cmp.javaClass.name.contains("BasicComboPopup")
override fun generate(cmp: JList<*>, me: MouseEvent, cp: Point): String {
val cellText = getCellText(cmp, cp).orEmpty()
return """.selectItem("$cellText")""" // check that combobox is open
}
}
class CheckboxTreeGenerator : ComponentCodeGenerator<CheckboxTree> {
override fun accept(cmp: Component): Boolean = cmp is CheckboxTree
private fun JTree.getPath(cp: Point): TreePath = this.getClosestPathForLocation(cp.x, cp.y)
private fun wasClickOnCheckBox(cmp: CheckboxTree, cp: Point): Boolean {
val treePath = cmp.getPath(cp)
println("CheckboxTreeGenerator.wasClickOnCheckBox: treePath = ${treePath.path.joinToString()}")
return withRobot {
val checkboxComponent = CheckboxTreeDriver(it).getCheckboxComponent(cmp, treePath) ?: throw Exception(
"Checkbox component from cell renderer is null")
val pathBounds = GuiTestUtilKt.computeOnEdt { cmp.getPathBounds(treePath) }!!
val checkboxTreeBounds = Rectangle(pathBounds.x + checkboxComponent.x, pathBounds.y + checkboxComponent.y, checkboxComponent.width,
checkboxComponent.height)
checkboxTreeBounds.contains(cp)
}
}
override fun generate(cmp: CheckboxTree, me: MouseEvent, cp: Point): String {
val path = getJTreePath(cmp, cmp.getPath(cp))
return if (wasClickOnCheckBox(cmp, cp))
"checkboxTree($path).clickCheckbox()"
else
"checkboxTree($path).clickPath()"
}
}
class SimpleTreeGenerator : ComponentCodeGenerator<SimpleTree> {
override fun accept(cmp: Component): Boolean = cmp is SimpleTree
private fun SimpleTree.getPath(cp: Point) = convertSimpleTreeItemToPath(this, this.getDeepestRendererComponentAt(cp.x, cp.y).toString())
override fun generate(cmp: SimpleTree, me: MouseEvent, cp: Point): String {
val path = cmp.getPath(cp)
if (me.isRightButton()) return """jTree("$path").rightClickPath("$path")"""
return """jTree("$path").selectPath("$path")"""
}
}
class JTableGenerator : ComponentCodeGenerator<JTable> {
override fun accept(cmp: Component): Boolean = cmp is JTable
override fun generate(cmp: JTable, me: MouseEvent, cp: Point): String {
val row = cmp.rowAtPoint(cp)
val col = cmp.columnAtPoint(cp)
val cellText = ExtendedJTableCellReader().valueAt(cmp, row, col)
return """table("$cellText").cell("$cellText")""".addClick(me)
}
}
class JBCheckBoxGenerator : ComponentCodeGenerator<JBCheckBox> {
override fun priority(): Int = 1
override fun accept(cmp: Component): Boolean = cmp is JBCheckBox
override fun generate(cmp: JBCheckBox, me: MouseEvent, cp: Point): String = """checkbox("${cmp.text}").click()"""
}
class JCheckBoxGenerator : ComponentCodeGenerator<JCheckBox> {
override fun accept(cmp: Component): Boolean = cmp is JCheckBox
override fun generate(cmp: JCheckBox, me: MouseEvent, cp: Point): String = """checkbox("${cmp.text}").click()"""
}
class JComboBoxGenerator : ComponentCodeGenerator<JComboBox<*>> {
override fun accept(cmp: Component): Boolean = cmp is JComboBox<*>
override fun generate(cmp: JComboBox<*>, me: MouseEvent, cp: Point): String = """combobox("${findBoundedText(cmp).orEmpty()}")"""
}
class BasicArrowButtonDelegatedGenerator : ComponentCodeGenerator<BasicArrowButton> {
override fun priority(): Int = 1 //make sense if we challenge with simple jbutton
override fun accept(cmp: Component): Boolean = (cmp is BasicArrowButton) && (cmp.parent is JComboBox<*>)
override fun generate(cmp: BasicArrowButton, me: MouseEvent, cp: Point): String =
JComboBoxGenerator().generate(cmp.parent as JComboBox<*>, me, cp)
}
class JRadioButtonGenerator : ComponentCodeGenerator<JRadioButton> {
override fun accept(cmp: Component): Boolean = cmp is JRadioButton
override fun generate(cmp: JRadioButton, me: MouseEvent, cp: Point): String = """radioButton("${cmp.text}").select()"""
}
class LinkLabelGenerator : ComponentCodeGenerator<LinkLabel<*>> {
override fun accept(cmp: Component): Boolean = cmp is LinkLabel<*>
override fun generate(cmp: LinkLabel<*>, me: MouseEvent, cp: Point): String = """linkLabel("${cmp.text}").click()"""
}
class HyperlinkLabelGenerator : ComponentCodeGenerator<HyperlinkLabel> {
override fun accept(cmp: Component): Boolean = cmp is HyperlinkLabel
override fun generate(cmp: HyperlinkLabel, me: MouseEvent, cp: Point): String {
//we assume, that hyperlink label has only one highlighted region
val linkText = cmp.highlightedRegionsBoundsMap.keys.toList().firstOrNull() ?: "null"
return """hyperlinkLabel("${cmp.text}").clickLink("$linkText")"""
}
}
class HyperlinkLabelInNotificationPanelGenerator : ComponentCodeGenerator<HyperlinkLabel> {
override fun accept(cmp: Component): Boolean = cmp is HyperlinkLabel && cmp.hasInParents(EditorNotificationPanel::class.java)
override fun priority(): Int = 1
override fun generate(cmp: HyperlinkLabel, me: MouseEvent, cp: Point): String {
//we assume, that hyperlink label has only one highlighted region
val linkText = cmp.highlightedRegionsBoundsMap.keys.toList().firstOrNull() ?: "null"
return """editor { notificationPanel().clickLink("$linkText") }"""
}
}
class JTreeGenerator : ComponentCodeGenerator<JTree> {
override fun accept(cmp: Component): Boolean = cmp is JTree
private fun JTree.getPath(cp: Point) = this.getClosestPathForLocation(cp.x, cp.y)
override fun generate(cmp: JTree, me: MouseEvent, cp: Point): String {
val path = getJTreePath(cmp, cmp.getPath(cp))
if (me.isRightButton()) return "jTree($path).rightClickPath()"
return "jTree($path).clickPath()"
}
}
class ProjectViewTreeGenerator : ComponentCodeGenerator<ProjectViewTree> {
override fun priority(): Int = 1
override fun accept(cmp: Component): Boolean = cmp is ProjectViewTree
private fun JTree.getPath(cp: Point) = this.getClosestPathForLocation(cp.x, cp.y)
override fun generate(cmp: ProjectViewTree, me: MouseEvent, cp: Point): String {
val path = if(cmp.getPath(cp) != null) getJTreePathItemsString(cmp, cmp.getPath(cp)) else ""
if (me.isRightButton()) return "path($path).rightClick()"
if (me.clickCount == 2) return "path($path).doubleClick()"
return "path($path).click()"
}
}
class PluginTableGenerator : ComponentCodeGenerator<PluginTable> {
override fun accept(cmp: Component): Boolean = cmp is PluginTable
override fun generate(cmp: PluginTable, me: MouseEvent, cp: Point): String {
val row = cmp.rowAtPoint(cp)
val ideaPluginDescriptor = cmp.getObjectAt(row)
return """pluginTable().selectPlugin("${ideaPluginDescriptor.name}")"""
}
}
class EditorComponentGenerator : ComponentSelectionCodeGenerator<EditorComponentImpl> {
override fun generateSelection(cmp: EditorComponentImpl, firstPoint: Point, lastPoint: Point): String {
val editor = cmp.editor
val firstOffset = editor.logicalPositionToOffset(editor.xyToLogicalPosition(firstPoint))
val lastOffset = editor.logicalPositionToOffset(editor.xyToLogicalPosition(lastPoint))
return "select($firstOffset, $lastOffset)"
}
override fun accept(cmp: Component): Boolean = cmp is EditorComponentImpl
override fun generate(cmp: EditorComponentImpl, me: MouseEvent, cp: Point): String {
val editor = cmp.editor
val logicalPos = editor.xyToLogicalPosition(cp)
val offset = editor.logicalPositionToOffset(logicalPos)
return when (me.button) {
leftButton -> "moveTo($offset)"
rightButton -> "rightClick($offset)"
else -> "//not implemented editor action"
}
}
}
class ActionMenuItemGenerator : ComponentCodeGenerator<ActionMenuItem> {
override fun accept(cmp: Component): Boolean = cmp is ActionMenuItem
override fun generate(cmp: ActionMenuItem, me: MouseEvent, cp: Point): String =
"menu(${buildPath(activatedActionMenuItem = cmp).joinToString(separator = ", ") { str -> "\"$str\"" }}).click()"
//for buildnig a path of actionMenus and actionMenuItem we need to scan all JBPopup and find a consequence of actions from a tail. Each discovered JBPopupMenu added to hashSet to avoid double sacnning and multiple component finding results
private fun buildPath(activatedActionMenuItem: ActionMenuItem): List<String> {
val jbPopupMenuSet = HashSet<Int>()
jbPopupMenuSet.add(activatedActionMenuItem.parent.hashCode())
val path = ArrayList<String>()
var actionItemName = activatedActionMenuItem.text
path.add(actionItemName)
var window = activatedActionMenuItem.getNextPopupSHeavyWeightWindow()
while (window?.getNextPopupSHeavyWeightWindow() != null) {
window = window.getNextPopupSHeavyWeightWindow()
actionItemName = window!!.findJBPopupMenu(jbPopupMenuSet).findParentActionMenu(jbPopupMenuSet)
path.add(0, actionItemName)
}
return path
}
private fun Component.getNextPopupSHeavyWeightWindow(): JWindow? {
if (this.parent == null) return null
var cmp = this.parent
while (cmp != null && !cmp.javaClass.name.endsWith("Popup\$HeavyWeightWindow")) cmp = cmp.parent
if (cmp == null) return null
return cmp as JWindow
}
private fun JWindow.findJBPopupMenu(jbPopupHashSet: MutableSet<Int>): JBPopupMenu {
return withRobot { robot ->
val resultJBPopupMenu = robot.finder().find(this, ComponentMatcher { component ->
(component is JBPopupMenu)
&& component.isShowing
&& component.isVisible
&& !jbPopupHashSet.contains(component.hashCode())
}) as JBPopupMenu
jbPopupHashSet.add(resultJBPopupMenu.hashCode())
resultJBPopupMenu
}
}
private fun JBPopupMenu.findParentActionMenu(jbPopupHashSet: MutableSet<Int>): String {
val actionMenu = this.subElements
.filterIsInstance(ActionMenu::class.java)
.find { actionMenu ->
actionMenu.subElements != null && actionMenu.subElements.isNotEmpty() && actionMenu.subElements.any { menuElement ->
menuElement is JBPopupMenu && jbPopupHashSet.contains(menuElement.hashCode())
}
} ?: throw Exception("Unable to find a proper ActionMenu")
return actionMenu.text
}
}
//**********GLOBAL CONTEXT GENERATORS**********
class WelcomeFrameGenerator : GlobalContextCodeGenerator<FlatWelcomeFrame>() {
override fun priority(): Int = 1
override fun accept(cmp: Component): Boolean = cmp is JComponent && cmp.rootPane?.parent is FlatWelcomeFrame
override fun generate(cmp: FlatWelcomeFrame): String {
return "welcomeFrame {"
}
}
class JDialogGenerator : GlobalContextCodeGenerator<JDialog>() {
override fun accept(cmp: Component): Boolean {
if (cmp !is JComponent || cmp.rootPane == null || cmp.rootPane.parent == null || cmp.rootPane.parent !is JDialog) return false
val dialog = cmp.rootPane.parent as JDialog
if (dialog.title == "This should not be shown") return false //do not add context for a SheetMessages on Mac
return true
}
override fun generate(cmp: JDialog): String = """dialog("${cmp.title}") {"""
}
class IdeFrameGenerator : GlobalContextCodeGenerator<JFrame>() {
override fun accept(cmp: Component): Boolean {
if (cmp !is JComponent) return false
val parent = cmp.rootPane.parent
return (parent is JFrame) && parent.title != "GUI Script Editor"
}
override fun generate(cmp: JFrame): String = "ideFrame {"
}
class TabbedPaneGenerator : ComponentCodeGenerator<Component> {
override fun priority(): Int = 2
override fun generate(cmp: Component, me: MouseEvent, cp: Point): String {
val tabbedPane = when {
cmp.parent.parent is JBTabbedPane -> cmp.parent.parent as JTabbedPane
else -> cmp.parent as JTabbedPane
}
val selectedTabIndex = tabbedPane.indexAtLocation(me.locationOnScreen.x - tabbedPane.locationOnScreen.x,
me.locationOnScreen.y - tabbedPane.locationOnScreen.y)
val title = tabbedPane.getTitleAt(selectedTabIndex)
return """tab("${title}").selectTab()"""
}
override fun accept(cmp: Component): Boolean = cmp.parent.parent is JBTabbedPane || cmp.parent is JBTabbedPane
}
//**********LOCAL CONTEXT GENERATORS**********
class ProjectViewGenerator : LocalContextCodeGenerator<JPanel>() {
override fun priority(): Int = 0
override fun isLastContext(): Boolean = true
override fun acceptor(): (Component) -> Boolean = { component -> component.javaClass.name.endsWith("ProjectViewImpl\$MyPanel") }
override fun generate(cmp: JPanel): String = "projectView {"
}
class ToolWindowGenerator : LocalContextCodeGenerator<Component>() {
override fun priority(): Int = 0
private fun Component.containsLocationOnScreen(locationOnScreen: Point): Boolean {
val rectangle = this.bounds
rectangle.location = this.locationOnScreen
return rectangle.contains(locationOnScreen)
}
private fun Component.centerOnScreen(): Point? {
val rectangle = this.bounds
rectangle.location = try {
this.locationOnScreen
}
catch (e: IllegalComponentStateException) {
return null
}
return Point(rectangle.centerX.toInt(), rectangle.centerY.toInt())
}
private fun getToolWindow(pointOnScreen: Point): ToolWindow? {
val project = WindowManagerEx.getInstanceEx().findFirstVisibleFrameHelper()?.project ?: return null
val toolWindowManager = ToolWindowManager.getInstance(project)
val visibleToolWindows = toolWindowManager.toolWindowIds
.asSequence()
.map { toolWindowId -> toolWindowManager.getToolWindow(toolWindowId) }
.filter { toolwindow -> toolwindow?.isVisible ?: false }
return visibleToolWindows
.find { it!!.component.containsLocationOnScreen(pointOnScreen) }
}
override fun acceptor(): (Component) -> Boolean = { component ->
val centerOnScreen = component.centerOnScreen()
if (centerOnScreen != null) {
val tw = getToolWindow(centerOnScreen)
tw != null && component == tw.component
}
else false
}
override fun generate(cmp: Component): String {
val pointOnScreen = cmp.centerOnScreen() ?: throw IllegalComponentStateException("Unable to get center on screen for component: $cmp")
val toolWindow = getToolWindow(pointOnScreen)!!
return """toolwindow(id = "${toolWindow.id}") {"""
}
}
internal class ToolWindowContextGenerator : LocalContextCodeGenerator<Component>() {
override fun priority(): Int = 2
private fun Component.containsLocationOnScreen(locationOnScreen: Point): Boolean {
val rectangle = this.bounds
rectangle.location = this.locationOnScreen
return rectangle.contains(locationOnScreen)
}
private fun Component.centerOnScreen(): Point? {
val rectangle = this.bounds
rectangle.location = try {
this.locationOnScreen
}
catch (e: IllegalComponentStateException) {
return null
}
return Point(rectangle.centerX.toInt(), rectangle.centerY.toInt())
}
private fun Component.contains(component: Component): Boolean {
return this.contains(Point(component.bounds.x, component.bounds.y)) &&
this.contains(Point(component.bounds.x + component.width, component.bounds.y + component.height))
}
private fun getToolWindow(pointOnScreen: Point): ToolWindow? {
val project = WindowManagerEx.getInstanceEx().findFirstVisibleFrameHelper()?.project ?: return null
val toolWindowManager = ToolWindowManager.getInstance(project)
val visibleToolWindows = toolWindowManager.toolWindowIds
.asSequence()
.map { toolWindowId -> toolWindowManager.getToolWindow(toolWindowId) }
.filter { toolwindow -> toolwindow?.isVisible ?: false }
return visibleToolWindows
.find { it!!.component.containsLocationOnScreen(pointOnScreen) }
}
override fun acceptor(): (Component) -> Boolean = { component ->
val pointOnScreen = component.centerOnScreen()
if (pointOnScreen != null) {
val tw = getToolWindow(pointOnScreen)
tw != null && tw.contentManager.selectedContent!!.component == component
}
else false
}
override fun generate(cmp: Component): String {
val toolWindow = getToolWindow(cmp.centerOnScreen()!!)!!
val tabName = toolWindow.contentManager.selectedContent?.tabName
return if (tabName != null) """content(tabName = "${tabName}") {"""
else "content {"
}
}
class MacMessageGenerator : LocalContextCodeGenerator<JButton>() {
override fun priority(): Int = 2
private fun acceptMacSheetPanel(cmp: Component): Boolean {
if (cmp !is JComponent) return false
if (!(Messages.canShowMacSheetPanel() && cmp.rootPane.parent is JDialog)) return false
val panel = cmp.rootPane.contentPane as JPanel
if (panel.javaClass.name.startsWith(SheetController::class.java.name) && panel.isShowing) {
val controller = MessagesFixture.findSheetController(panel)
val sheetPanel = field("mySheetPanel").ofType(JPanel::class.java).`in`(controller).get()
if (sheetPanel === panel) {
return true
}
}
return false
}
override fun acceptor(): (Component) -> Boolean = { component -> acceptMacSheetPanel(component) }
override fun generate(cmp: JButton): String {
val panel = cmp.rootPane.contentPane as JPanel
val title = withRobot { robot -> MessagesFixture.getTitle(panel, robot) }
return """message("$title") {"""
}
}
class MessageGenerator : LocalContextCodeGenerator<JDialog>() {
override fun priority(): Int = 2
override fun acceptor(): (Component) -> Boolean = { cmp ->
cmp is JDialog && MessagesFixture.isMessageDialog(cmp)
}
override fun generate(cmp: JDialog): String {
return """message("${cmp.title}") {"""
}
}
class EditorGenerator : LocalContextCodeGenerator<EditorComponentImpl>() {
override fun priority(): Int = 3
override fun acceptor(): (Component) -> Boolean = { component -> component is EditorComponentImpl }
override fun generate(cmp: EditorComponentImpl): String = "editor {"
}
class MainToolbarGenerator : LocalContextCodeGenerator<ActionToolbarImpl>() {
override fun acceptor(): (Component) -> Boolean = { component ->
component is ActionToolbarImpl
&& MainToolbarFixture.isMainToolbar(component)
}
override fun generate(cmp: ActionToolbarImpl): String = "toolbar {"
}
class NavigationBarGenerator : LocalContextCodeGenerator<JPanel>() {
override fun acceptor(): (Component) -> Boolean = { component ->
component is JPanel
&& NavigationBarFixture.isNavBar(component)
}
override fun generate(cmp: JPanel): String = "navigationBar {"
}
class TabGenerator : LocalContextCodeGenerator<TabLabel>() {
override fun acceptor(): (Component) -> Boolean = { component ->
component is TabLabel
}
override fun generate(cmp: TabLabel): String = "editor(\"" + cmp.info.text + "\") {"
}
//class JBPopupMenuGenerator: LocalContextCodeGenerator<JBPopupMenu>() {
//
// override fun acceptor(): (Component) -> Boolean = { component -> component is JBPopupMenu}
// override fun generate(cmp: JBPopupMenu, me: MouseEvent, cp: Point) = "popupMenu {"
//}
object Generators {
fun getGenerators(): List<ComponentCodeGenerator<*>> {
val generatorClassPaths = getSiblingsList().filter { path -> path.endsWith("Generator.class") }
val classLoader = Generators.javaClass.classLoader
return generatorClassPaths
.map { clzPath -> classLoader.loadClass("${Generators.javaClass.`package`.name}.${File(clzPath).nameWithoutExtension}") }
.filter { clz -> ComponentCodeGenerator::class.java.isAssignableFrom(clz) && !clz.isInterface }
.map(Class<*>::newInstance)
.filterIsInstance(ComponentCodeGenerator::class.java)
}
fun getGlobalContextGenerators(): List<GlobalContextCodeGenerator<*>> {
val generatorClassPaths = getSiblingsList().filter { path -> path.endsWith("Generator.class") }
val classLoader = Generators.javaClass.classLoader
return generatorClassPaths
.map { clzPath -> classLoader.loadClass("${Generators.javaClass.`package`.name}.${File(clzPath).nameWithoutExtension}") }
.filter { clz -> clz.superclass == GlobalContextCodeGenerator::class.java }
.map(Class<*>::newInstance)
.filterIsInstance(GlobalContextCodeGenerator::class.java)
}
fun getLocalContextCodeGenerator(): List<LocalContextCodeGenerator<*>> {
val generatorClassPaths = getSiblingsList().filter { path -> path.endsWith("Generator.class") }
val classLoader = Generators.javaClass.classLoader
return generatorClassPaths
.map { clzPath -> classLoader.loadClass("${Generators.javaClass.`package`.name}.${File(clzPath).nameWithoutExtension}") }
.filter { clz -> clz.superclass == LocalContextCodeGenerator::class.java }
.map(Class<*>::newInstance)
.filterIsInstance(LocalContextCodeGenerator::class.java)
}
private fun getSiblingsList(): List<String> {
val path = "/${Generators.javaClass.`package`.name.replace(".", "/")}"
val url = Generators.javaClass.getResource(path)
if (url.path.contains(".jar!")) {
val jarFile = JarFile(Paths.get(URI(url.file.substringBefore(".jar!").plus(".jar"))).toString())
val entries = jarFile.entries()
val genPath = url.path.substringAfter(".jar!").removePrefix("/")
return entries.toList().filter { entry -> entry.name.contains(genPath) }.map { entry -> entry.name }
}
else return File(url.toURI()).listFiles().map { file -> file.toURI().path }
}
}
object Utils {
fun getLabel(container: Container, jTextField: JTextField): JLabel? {
return withRobot { robot -> GuiTestUtil.findBoundedLabel(container, jTextField, robot) }
}
fun getLabel(jTextField: JTextField): JLabel? {
val parentContainer = jTextField.rootPane.parent
return withRobot { robot -> GuiTestUtil.findBoundedLabel(parentContainer, jTextField, robot) }
}
fun clicks(me: MouseEvent): String {
if (me.clickCount == 1) return "click()"
if (me.clickCount == 2) return "doubleClick()"
return ""
}
fun getCellText(jList: JList<*>, pointOnList: Point): String? {
return withRobot { robot ->
val extCellReader = ExtendedJListCellReader()
val index = jList.locationToIndex(pointOnList)
extCellReader.valueAt(jList, index)
}
}
fun convertSimpleTreeItemToPath(tree: SimpleTree, itemName: String): String {
val searchableNodeRef = Ref.create<TreeNode>()
val searchableNode: TreeNode?
TreeUtil.traverse(tree.model.root as TreeNode) { node ->
val valueFromNode = SettingsTreeFixture.getValueFromNode(tree, node)
if (valueFromNode != null && valueFromNode == itemName) {
assert(node is TreeNode)
searchableNodeRef.set(node as TreeNode)
}
true
}
searchableNode = searchableNodeRef.get()
val path = TreeUtil.getPathFromRoot(searchableNode!!)
return (0 until path.pathCount).map { path.getPathComponent(it).toString() }.filter(String::isNotEmpty).joinToString("/")
}
fun getBoundedLabel(component: Component): JLabel {
return getBoundedLabelRecursive(component, component.parent)
}
private fun getBoundedLabelRecursive(component: Component, parent: Component): JLabel {
val boundedLabel = findBoundedLabel(component, parent)
if (boundedLabel != null) return boundedLabel
else {
if (parent.parent == null) throw ComponentLookupException("Unable to find bounded label")
return getBoundedLabelRecursive(component, parent.parent)
}
}
private fun findBoundedLabel(component: Component, componentParent: Component): JLabel? {
return withRobot { robot ->
var resultLabel: JLabel?
if (componentParent is LabeledComponent<*>) resultLabel = componentParent.label
else {
try {
resultLabel = robot.finder().find(componentParent as Container, object : GenericTypeMatcher<JLabel>(JLabel::class.java) {
override fun isMatching(label: JLabel) = (label.labelFor != null && label.labelFor == component)
})
}
catch (e: ComponentLookupException) {
resultLabel = null
}
}
resultLabel
}
}
fun findBoundedText(target: Component): String? {
//let's try to find bounded label firstly
try {
return getBoundedLabel(target).text
}
catch (_: ComponentLookupException) {
}
return findBoundedTextRecursive(target, target.parent)
}
private fun findBoundedTextRecursive(target: Component, parent: Component): String? {
val boundedText = findBoundedText(target, parent)
if (boundedText != null)
return boundedText
else
if (parent.parent != null) return findBoundedTextRecursive(target, parent.parent)
else return null
}
private fun findBoundedText(target: Component, container: Component): String? {
val textComponents = withRobot { robot ->
robot.finder().findAll(container as Container, ComponentMatcher { component ->
component!!.isShowing && component.isTextComponent() && target.onHeightCenter(component, true)
})
}
if (textComponents.isEmpty()) return null
//if more than one component is found let's take the righter one
return textComponents.sortedBy { it.bounds.x + it.bounds.width }.last().getComponentText()
}
fun getJTreePath(cmp: JTree, path: TreePath): String {
val pathArray = path.getPathStrings(cmp)
return pathArray.joinToString(separator = ", ", transform = { str -> "\"$str\"" })
}
fun getJTreePathItemsString(cmp: JTree, path: TreePath): String {
return path.getPathStrings(cmp)
.map { StringUtil.wrapWithDoubleQuote(it) }
.reduceRight { s, s1 -> "$s, $s1" }
}
fun <ReturnType> withRobot(robotFunction: (Robot) -> ReturnType): ReturnType {
val robot = BasicRobot.robotWithCurrentAwtHierarchyWithoutScreenLock()
return robotFunction(robot)
}
}
private fun String.addClick(me: MouseEvent): String {
return when {
me.isLeftButton() && me.clickCount == 2 -> "$this.doubleClick()"
me.isRightButton() -> "$this.rightClick()"
else -> "$this.click()"
}
}
private fun Component.hasInParents(componentType: Class<out Component>): Boolean {
var component = this
while (component.parent != null) {
if (componentType.isInstance(component)) return true
component = component.parent
}
return false
}
| apache-2.0 | cbed7304b67490e4a2e36fed9cfcf25b | 41.154689 | 241 | 0.726661 | 4.742258 | false | false | false | false |
allotria/intellij-community | platform/platform-tests/testSrc/org/jetbrains/concurrency/AsyncPromiseStateTest.kt | 6 | 4504 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.concurrency
import com.intellij.testFramework.assertions.Assertions.assertThat
import com.intellij.testFramework.assertions.Assertions.assertThatThrownBy
import com.intellij.util.TimeoutUtil.sleep
import org.junit.Test
import java.awt.EventQueue.invokeLater
import java.awt.EventQueue.isDispatchThread
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
class AsyncPromiseStateTest {
internal enum class State {
RESOLVE, REJECT, ERROR
}
@Test
fun resolveNow() {
val promise = promise(State.RESOLVE, When.NOW)
assertThat(promise.blockingGet(100)).isEqualTo("resolved")
}
@Test
fun resolveAfterHandlerSet() {
val promise = promise(State.RESOLVE, When.AFTER)
assertThat(promise.blockingGet(100)).isEqualTo("resolved")
}
@Test
fun resolveBeforeHandlerSet() {
val promise = promise(State.RESOLVE, When.BEFORE)
assertThat(promise.blockingGet(100)).isEqualTo("resolved")
}
@Test
fun rejectNow() {
val promise = promise(State.REJECT, When.NOW)
try {
assertThat(promise.blockingGet(100)).isNull()
}
catch (exception: Exception) {
if (!isMessageError(exception)) {
throw exception
}
}
}
@Test
fun rejectAfterHandlerSet() {
val promise = promise(State.REJECT, When.AFTER)
try {
assertThat(promise.blockingGet(100)).isNull()
}
catch (exception: Exception) {
if (!isMessageError(exception)) throw exception
}
}
@Test
fun rejectBeforeHandlerSet() {
val promise = promise(State.REJECT, When.BEFORE)
try {
assertThat(promise.blockingGet(100)).isNull()
}
catch (exception: Exception) {
if (!isMessageError(exception)) {
throw exception
}
}
}
@Test
fun errorNow() {
val promise = promise(State.ERROR, When.NOW)
assertThatThrownBy {
assertThat(promise.blockingGet(100)).isNull()
}.hasCauseExactlyInstanceOf(CheckedException::class.java)
}
@Test
fun errorAfterHandlerSet() {
val promise = promise(State.ERROR, When.AFTER)
assertThatThrownBy {
promise.blockingGet(100)
}.hasCauseExactlyInstanceOf(CheckedException::class.java)
}
@Test
fun errorBeforeHandlerSet() {
val promise = promise(State.ERROR, When.BEFORE)
assertThatThrownBy {
promise.blockingGet(100)
}.hasCauseExactlyInstanceOf(CheckedException::class.java)
}
}
private const val PRINT = false
private class CheckedException : Exception()
private fun log(message: String) {
@Suppress("ConstantConditionIf")
if (PRINT) {
println(message)
}
}
private fun promise(state: AsyncPromiseStateTest.State, `when`: When): AsyncPromise<String> {
assert(!isDispatchThread())
val latch = CountDownLatch(1)
val promise = AsyncPromise<String>()
val task = {
try {
sleep(10)
when (state) {
AsyncPromiseStateTest.State.RESOLVE -> {
log("resolve promise")
promise.setResult("resolved")
}
AsyncPromiseStateTest.State.REJECT -> {
log("reject promise")
promise.setError("rejected")
}
AsyncPromiseStateTest.State.ERROR -> {
log("notify promise about error to preserve a cause")
promise.onError { /* add empty error handler to ensure that promise will not call LOG.error */ }
promise.setError(CheckedException())
}
}
latch.countDown()
}
catch (throwable: Throwable) {
log("unexpected error that breaks current task")
throwable.printStackTrace()
}
}
when (`when`) {
When.NOW -> {
log("resolve promise immediately")
task()
}
When.AFTER -> {
log("resolve promise on another thread")
invokeLater(task)
}
When.BEFORE -> {
log("resolve promise on another thread before handler is set")
invokeLater(task)
sleep(50)
}
}
log("add processing handlers")
promise.onProcessed { log("promise is processed") }
try {
log("wait for task completion")
latch.await(100, TimeUnit.MILLISECONDS)
if (0L == latch.count) {
return promise
}
throw AssertionError("task is not completed")
}
catch (exception: InterruptedException) {
throw AssertionError("task is interrupted", exception)
}
}
private enum class When {
NOW, AFTER, BEFORE
} | apache-2.0 | b6225b4ddb423c8b895966dcde89052b | 24.890805 | 140 | 0.672069 | 4.351691 | false | true | false | false |
mrlem/happy-cows | core/src/org/mrlem/happycows/domain/model/Game.kt | 1 | 995 | package org.mrlem.happycows.domain.model
import com.badlogic.gdx.maps.tiled.TiledMap
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer
import com.badlogic.gdx.math.Vector2
import org.mrlem.happycows.domain.logic.WorldController
/**
* @author Sébastien Guillemin <[email protected]>
*/
data class Game(
val map: TiledMap,
val world: WorldController
) {
val mapSize by lazy {
val tiles = map.layers.filterIsInstance(TiledMapTileLayer::class.java).first()
Vector2(tiles.width * tiles.tileWidth * SCREEN_TO_WORLD, tiles.height * tiles.tileHeight * SCREEN_TO_WORLD)
}
fun dispose() {
map.dispose()
world.dispose()
}
companion object {
private const val WORLD_TO_SCREEN = 64f
const val SCREEN_TO_WORLD = 1 / WORLD_TO_SCREEN
const val POINTS_PER_BOTTLE = 1
const val GRAVITY = 9.8f // earth-like
const val COW_JUMP_VELOCITY = 11.5f
const val BOTTLE_BREAK_VELOCITY = 2f
}
}
| gpl-3.0 | b555fdb38e375769c22be9a28b39c79b | 26.611111 | 115 | 0.67002 | 3.722846 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/info/Credentials.kt | 1 | 745 | /**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: Kishore Reddy
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A tool-kit, utility library and server-backend
* mantra: Simplicity above all else
* </slate_header>
*/
package slatekit.common.info
data class Credentials(
@JvmField val id: String = "",
@JvmField val name: String = "",
@JvmField val email: String = "",
@JvmField val key: String = "",
@JvmField val env: String = "",
@JvmField val region: String = "",
@JvmField val roles: String = ""
) {
companion object {
@JvmStatic
val empty = Credentials()
}
}
| apache-2.0 | c54e4c5046f73e544d35ceae5ed15c59 | 24.689655 | 56 | 0.641611 | 3.781726 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-tests/testSrc/com/intellij/internal/statistics/ExternalEventLogSettingsTest.kt | 2 | 1587 | // 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.internal.statistics
import com.intellij.internal.statistic.eventLog.EventLogInternalApplicationInfo
import com.intellij.internal.statistic.eventLog.ExternalEventLogSettings
import com.intellij.internal.statistic.utils.StatisticsUploadAssistant
import com.intellij.testFramework.ExtensionTestUtil
import com.intellij.testFramework.fixtures.BasePlatformTestCase
import org.assertj.core.api.Assertions
private const val URL = "https://localhost/"
class ExternalEventLogSettingsTest : BasePlatformTestCase() {
private class TestExternalEventLogSettings: ExternalEventLogSettings {
override fun getTemplateUrl(recorderId: String): String = URL
override fun isSendAllowedOverride(): Boolean = true
override fun isCollectAllowedOverride(): Boolean = true
override fun getExtraLogUploadHeaders(): Map<String, String> = emptyMap()
}
override fun setUp() {
super.setUp()
installEp()
}
fun installEp() {
ExtensionTestUtil.maskExtensions(ExternalEventLogSettings.EP_NAME, listOf(TestExternalEventLogSettings()), testRootDisposable)
}
fun testSubstitution() {
val applicationInfo = EventLogInternalApplicationInfo("FUS", true)
Assertions.assertThat(applicationInfo.templateUrl).isEqualTo(URL)
}
fun testSendOverride() {
assertTrue(StatisticsUploadAssistant.getSendAllowedOverride())
}
fun testCollectOverride() {
assertTrue(StatisticsUploadAssistant.getCollectAllowedOverride())
}
} | apache-2.0 | efe76374a6379a99fa88e512d00fdc54 | 36.809524 | 130 | 0.798362 | 5.135922 | false | true | false | false |
Fotoapparat/Fotoapparat | fotoapparat/src/main/java/io/fotoapparat/hardware/CameraDevice.kt | 1 | 12495 | @file:Suppress("DEPRECATION")
package io.fotoapparat.hardware
import android.hardware.Camera
import android.media.MediaRecorder
import android.view.Surface
import androidx.annotation.FloatRange
import io.fotoapparat.capability.Capabilities
import io.fotoapparat.capability.provide.getCapabilities
import io.fotoapparat.characteristic.Characteristics
import io.fotoapparat.characteristic.toCameraId
import io.fotoapparat.coroutines.AwaitBroadcastChannel
import io.fotoapparat.exception.camera.CameraException
import io.fotoapparat.hardware.metering.FocalRequest
import io.fotoapparat.hardware.metering.convert.toFocusAreas
import io.fotoapparat.hardware.orientation.*
import io.fotoapparat.log.Logger
import io.fotoapparat.parameter.FocusMode
import io.fotoapparat.parameter.Resolution
import io.fotoapparat.parameter.camera.CameraParameters
import io.fotoapparat.parameter.camera.apply.applyInto
import io.fotoapparat.parameter.camera.convert.toCode
import io.fotoapparat.preview.PreviewStream
import io.fotoapparat.result.FocusResult
import io.fotoapparat.result.Photo
import io.fotoapparat.util.FrameProcessor
import io.fotoapparat.util.lineSeparator
import io.fotoapparat.view.Preview
import kotlinx.coroutines.CompletableDeferred
import java.io.IOException
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
typealias PreviewSize = io.fotoapparat.parameter.Resolution
/**
* Camera.
*/
internal open class CameraDevice(
private val logger: Logger,
val characteristics: Characteristics
) {
private val capabilities = CompletableDeferred<Capabilities>()
private val cameraParameters = AwaitBroadcastChannel<CameraParameters>()
private lateinit var previewStream: PreviewStream
private lateinit var surface: Surface
private lateinit var camera: Camera
private var cachedCameraParameters: Camera.Parameters? = null
private lateinit var displayOrientation: Orientation
private lateinit var imageOrientation: Orientation
private lateinit var previewOrientation: Orientation
/**
* Opens a connection to a camera.
*/
open fun open() {
logger.recordMethod()
val lensPosition = characteristics.lensPosition
val cameraId = lensPosition.toCameraId()
try {
camera = Camera.open(cameraId)
capabilities.complete(camera.getCapabilities())
previewStream = PreviewStream(camera)
} catch (e: RuntimeException) {
throw CameraException(
message = "Failed to open camera with lens position: $lensPosition and id: $cameraId",
cause = e
)
}
}
/**
* Closes the connection to a camera.
*/
open fun close() {
logger.recordMethod()
surface.release()
camera.release()
}
/**
* Starts preview.
*/
open fun startPreview() {
logger.recordMethod()
try {
camera.startPreview()
} catch (e: RuntimeException) {
throw CameraException(
message = "Failed to start preview for camera with lens " +
"position: ${characteristics.lensPosition} and id: ${characteristics.cameraId}",
cause = e
)
}
}
/**
* Stops preview.
*/
open fun stopPreview() {
logger.recordMethod()
camera.stopPreview()
}
/**
* Unlock camera.
*/
open fun unlock() {
logger.recordMethod()
camera.unlock()
}
/**
* Lock camera.
*/
open fun lock() {
logger.recordMethod()
camera.lock()
}
/**
* Invokes a still photo capture action.
*
* @return The captured photo.
*/
open fun takePhoto(): Photo {
logger.recordMethod()
return camera.takePhoto(imageOrientation.degrees)
}
/**
* Returns the [Capabilities] of the camera.
*/
open suspend fun getCapabilities(): Capabilities {
logger.recordMethod()
return capabilities.await()
}
/**
* Returns the [CameraParameters] used.
*/
open suspend fun getParameters(): CameraParameters {
logger.recordMethod()
return cameraParameters.getValue()
}
/**
* Updates the desired camera parameters.
*/
open suspend fun updateParameters(cameraParameters: CameraParameters) {
logger.recordMethod()
this.cameraParameters.send(cameraParameters)
logger.log("New camera parameters are: $cameraParameters")
cameraParameters.applyInto(cachedCameraParameters ?: camera.parameters)
.cacheLocally()
.setInCamera()
}
/**
* Updates the frame processor.
*/
open fun updateFrameProcessor(frameProcessor: FrameProcessor?) {
logger.recordMethod()
previewStream.updateProcessorSafely(frameProcessor)
}
/**
* Sets the current orientation of the display.
*/
open fun setDisplayOrientation(orientationState: OrientationState) {
logger.recordMethod()
imageOrientation = computeImageOrientation(
deviceOrientation = orientationState.deviceOrientation,
cameraOrientation = characteristics.cameraOrientation,
cameraIsMirrored = characteristics.isMirrored
)
displayOrientation = computeDisplayOrientation(
screenOrientation = orientationState.screenOrientation,
cameraOrientation = characteristics.cameraOrientation,
cameraIsMirrored = characteristics.isMirrored
)
previewOrientation = computePreviewOrientation(
screenOrientation = orientationState.screenOrientation,
cameraOrientation = characteristics.cameraOrientation,
cameraIsMirrored = characteristics.isMirrored
)
logger.log("Orientations: $lineSeparator" +
"Screen orientation (preview) is: ${orientationState.screenOrientation}. " + lineSeparator +
"Camera sensor orientation is always at: ${characteristics.cameraOrientation}. " + lineSeparator +
"Camera is " + if (characteristics.isMirrored) "mirrored." else "not mirrored."
)
logger.log("Orientation adjustments: $lineSeparator" +
"Image orientation will be adjusted by: ${imageOrientation.degrees} degrees. " + lineSeparator +
"Display orientation will be adjusted by: ${displayOrientation.degrees} degrees. " + lineSeparator +
"Preview orientation will be adjusted by: ${previewOrientation.degrees} degrees."
)
previewStream.frameOrientation = previewOrientation
camera.setDisplayOrientation(displayOrientation.degrees)
}
/**
* Changes zoom level of the camera. Must be called only if zoom is supported.
*
* @param level normalized zoom level. Value in range [0..1].
*/
open fun setZoom(@FloatRange(from = 0.0, to = 1.0) level: Float) {
logger.recordMethod()
setZoomSafely(level)
}
/**
* Performs auto focus. This is a blocking operation which returns the result of the operation
* when auto focus completes.
*/
open fun autoFocus(): FocusResult {
logger.recordMethod()
return camera.focusSafely()
}
/**
* Sets the point where the focus & exposure metering will happen.
*/
open suspend fun setFocalPoint(focalRequest: FocalRequest) {
logger.recordMethod()
if (capabilities.await().canSetFocusingAreas()) {
camera.updateFocusingAreas(focalRequest)
}
}
/**
* Clears the point where the focus & exposure will happen.
*/
open fun clearFocalPoint() {
logger.recordMethod()
camera.clearFocusingAreas()
}
/**
* Sets the desired surface on which the camera's preview will be displayed.
*/
@Throws(IOException::class)
open fun setDisplaySurface(preview: Preview) {
logger.recordMethod()
surface = camera.setDisplaySurface(preview)
}
/**
* Attaches the camera to the [MediaRecorder].
*/
open fun attachRecordingCamera(mediaRecorder: MediaRecorder) {
logger.recordMethod()
mediaRecorder.setCamera(camera)
}
/**
* Returns the [Resolution] of the displayed preview.
*/
open fun getPreviewResolution(): Resolution {
logger.recordMethod()
val previewResolution = camera.getPreviewResolution(previewOrientation)
logger.log("Preview resolution is: $previewResolution")
return previewResolution
}
private fun setZoomSafely(@FloatRange(from = 0.0, to = 1.0) level: Float) {
try {
setZoomUnsafe(level)
} catch (e: Exception) {
logger.log("Unable to change zoom level to " + level + " e: " + e.message)
}
}
private fun setZoomUnsafe(@FloatRange(from = 0.0, to = 1.0) level: Float) {
(cachedCameraParameters ?: camera.parameters)
.apply {
zoom = (maxZoom * level).toInt()
}
.cacheLocally()
.setInCamera()
}
private fun Camera.Parameters.cacheLocally() = apply {
cachedCameraParameters = this
}
private fun Camera.Parameters.setInCamera() = apply {
camera.parameters = this
}
private fun Camera.focusSafely(): FocusResult {
val latch = CountDownLatch(1)
try {
autoFocus { _, _ -> latch.countDown() }
} catch (e: Exception) {
logger.log("Failed to perform autofocus using device ${characteristics.cameraId} e: ${e.message}")
return FocusResult.UnableToFocus
}
try {
latch.await(AUTOFOCUS_TIMEOUT_SECONDS, TimeUnit.SECONDS)
} catch (e: InterruptedException) {
// Do nothing
}
return FocusResult.Focused
}
private suspend fun Camera.updateFocusingAreas(focalRequest: FocalRequest) {
val focusingAreas = focalRequest.toFocusAreas(
displayOrientationDegrees = displayOrientation.degrees,
cameraIsMirrored = characteristics.isMirrored
)
parameters = parameters.apply {
with(capabilities.await()) {
if (maxMeteringAreas > 0) {
meteringAreas = focusingAreas
}
if (maxFocusAreas > 0) {
if (focusModes.contains(FocusMode.Auto)) {
focusMode = FocusMode.Auto.toCode()
}
focusAreas = focusingAreas
}
}
}
}
private fun Camera.clearFocusingAreas() {
parameters = parameters.apply {
meteringAreas = null
focusAreas = null
}
}
}
private const val AUTOFOCUS_TIMEOUT_SECONDS = 3L
private fun Camera.takePhoto(imageRotation: Int): Photo {
val latch = CountDownLatch(1)
val photoReference = AtomicReference<Photo>()
takePicture(
null,
null,
null,
Camera.PictureCallback { data, _ ->
photoReference.set(
Photo(data, imageRotation)
)
latch.countDown()
}
)
latch.await()
return photoReference.get()
}
@Throws(IOException::class)
private fun Camera.setDisplaySurface(
preview: Preview
): Surface = when (preview) {
is Preview.Texture -> preview.surfaceTexture
.also(this::setPreviewTexture)
.let(::Surface)
is Preview.Surface -> preview.surfaceHolder
.also(this::setPreviewDisplay)
.surface
}
private fun Camera.getPreviewResolution(previewOrientation: Orientation): Resolution {
return parameters.previewSize
.run {
PreviewSize(width, height)
}
.run {
when (previewOrientation) {
is Orientation.Vertical -> this
is Orientation.Horizontal -> flipDimensions()
}
}
}
private fun Capabilities.canSetFocusingAreas(): Boolean =
maxMeteringAreas > 0 || maxFocusAreas > 0
| apache-2.0 | 3742dffebdee0f641826f2dc97dbb957 | 28.46934 | 116 | 0.629452 | 5.197587 | false | false | false | false |
cout970/Modeler | src/main/kotlin/com/cout970/modeler/controller/usecases/Animation.kt | 1 | 13995 | package com.cout970.modeler.controller.usecases
import com.cout970.modeler.api.animation.*
import com.cout970.modeler.api.model.`object`.RootGroupRef
import com.cout970.modeler.api.model.selection.SelectionTarget
import com.cout970.modeler.api.model.selection.SelectionType
import com.cout970.modeler.controller.tasks.*
import com.cout970.modeler.core.animation.*
import com.cout970.modeler.core.model.objects
import com.cout970.modeler.core.model.selection.Selection
import com.cout970.modeler.core.model.toTRTS
import com.cout970.modeler.core.project.IProgramState
import com.cout970.modeler.core.project.ProjectManager
import com.cout970.modeler.gui.Gui
import com.cout970.modeler.gui.leguicomp.StringInput
import com.cout970.modeler.input.event.IInput
import com.cout970.modeler.render.tool.Animator
import com.cout970.modeler.util.*
import com.cout970.reactive.dsl.width
import org.liquidengine.legui.component.Component
import kotlin.math.roundToInt
private var lastAnimation = 0
private var lastChannel = 0
private fun selectAnimation(projectManager: ProjectManager, it: Gui, ref: IAnimationRef) {
projectManager.selectedAnimation = ref
val length = projectManager.animation.timeLength
it.animator.animationState = AnimationState.STOP
it.animator.animationTime = 0f
it.animator.offset = 5.fromFrame()
it.animator.zoom = (length.toFrame() + 10).fromFrame()
it.animator.sendUpdate()
}
@UseCase("animation.add")
private fun addAnimation(programState: ProjectManager): ITask {
val model = programState.model
val animation = Animation.of("Animation_${lastAnimation++}")
return TaskChain(listOf(
TaskUpdateModel(model, model.addAnimation(animation)),
ModifyGui {
selectAnimation(programState, it, animation.ref)
}
))
}
@UseCase("animation.rename")
private fun renameAnimation(programState: IProgramState, component: Component): ITask {
val model = programState.model
val text = (component as StringInput).text
if (text.isEmpty()) return TaskNone
val animation = programState.animation.withName(text)
return TaskChain(listOf(
TaskUpdateModel(model, model.modifyAnimation(animation))
))
}
@UseCase("animation.dup")
private fun duplicateAnimation(programState: ProjectManager): ITask {
val model = programState.model
val selected = programState.animation
if (selected == AnimationNone) return TaskNone
val animation = Animation.of(
selected.name + "_copy",
selected.timeLength,
selected.channels,
selected.channelMapping
)
return TaskChain(listOf(
TaskUpdateModel(model, model.addAnimation(animation)),
ModifyGui { programState.selectedAnimation = animation.ref; it.animator.sendUpdate() }
))
}
@UseCase("animation.remove")
private fun removeAnimation(programState: ProjectManager): ITask {
val model = programState.model
val animation = programState.selectedAnimation
return TaskChain(listOf(
ModifyGui { programState.selectedAnimation = AnimationRefNone; it.animator.sendUpdate() },
TaskUpdateModel(model, model.removeAnimation(animation))
))
}
@UseCase("animation.channel.add")
private fun addAnimationChannel(programState: IProgramState): ITask {
val group = programState.selectedGroup
val selection = programState.modelSelection
val anim = programState.animation
val model = programState.model
if (anim.ref !in programState.model.animationMap) {
return TaskNone
}
val target = if (group == RootGroupRef) {
val sel = selection.getOrNull() ?: return TaskNone
AnimationTargetObject(sel.objects)
} else {
AnimationTargetGroup(group)
}
val defaultTRS = target.getTransformation(model).toTRTS()
val channel = Channel(
name = "Channel ${lastChannel++}",
interpolation = InterpolationMethod.LINEAR,
keyframes = listOf(
Keyframe(0f, defaultTRS),
Keyframe(anim.timeLength, defaultTRS)
)
)
val newAnimation = anim
.withChannel(channel)
.withMapping(channel.ref, target)
return TaskChain(listOf(
TaskUpdateModel(programState.model, programState.model.modifyAnimation(newAnimation)),
ModifyGui { it.animator.selectedChannel = channel.ref }
))
}
@UseCase("animation.channel.select")
private fun selectAnimationChannel(comp: Component, projectManager: ProjectManager): ITask {
val animation = projectManager.animation
val channel = comp.metadata["ref"] as IChannelRef
val task1 = ModifyGui { it.animator.selectedChannel = channel }
val target = animation.channelMapping[channel] ?: return task1
return when (target) {
is AnimationTargetGroup -> {
TaskChain(listOf(task1, ModifyGui { projectManager.selectedGroup = target.ref }))
}
is AnimationTargetObject -> {
val sel = projectManager.modelSelection
val task2 = TaskUpdateModelSelection(sel, Selection.of(target.refs).asNullable())
TaskChain(listOf(task1, task2))
}
}
}
@UseCase("animation.channel.rename")
private fun renameAnimationChannel(component: Component, programState: IProgramState, animator: Animator): ITask {
val ref = component.metadata["ref"] as IChannelRef
val text = (component as StringInput).text
if (text.isEmpty()) return TaskNone
val model = programState.model
val animation = animator.animation
val channel = animation.channels[ref] ?: error("Missing Channel $ref")
val newChannel = channel.withName(text)
val newAnimation = animator.animation.withChannel(newChannel)
return TaskChain(listOf(
TaskUpdateModel(model, model.modifyAnimation(newAnimation))
))
}
@UseCase("animation.channel.disable")
private fun disableAnimationChannel(comp: Component, programState: IProgramState): ITask {
val animation = programState.animation
val ref = comp.metadata["ref"] as IChannelRef
val channel = animation.channels[ref]!!
val newAnimation = animation.withChannel(channel.withEnable(false))
return TaskUpdateModel(programState.model, programState.model.modifyAnimation(newAnimation))
}
@UseCase("animation.channel.enable")
private fun enableAnimationChannel(comp: Component, programState: IProgramState): ITask {
val animation = programState.animation
val ref = comp.metadata["ref"] as IChannelRef
val channel = animation.channels[ref] ?: error("Missing channel $ref")
val newAnimation = animation.withChannel(channel.withEnable(true))
return TaskUpdateModel(programState.model, programState.model.modifyAnimation(newAnimation))
}
@UseCase("animation.channel.interpolation")
private fun setAnimationChannelInterpolation(comp: Component, programState: IProgramState): ITask {
val ref = comp.metadata["ref"] as IChannelRef
val method = comp.metadata["type"] as InterpolationMethod
val animation = programState.animation
val channel = animation.channels[ref] ?: error("Missing channel $ref")
val newAnimation = animation.withChannel(channel.withInterpolation(method))
return TaskUpdateModel(programState.model, programState.model.modifyAnimation(newAnimation))
}
@UseCase("animation.channel.type")
private fun setAnimationChannelType(comp: Component, programState: IProgramState): ITask {
val ref = comp.metadata["ref"] as IChannelRef
val type = comp.metadata["type"] as ChannelType
val animation = programState.animation
val channel = animation.channels[ref] ?: error("Missing channel $ref")
val newAnimation = animation.withChannel(channel.withType(type))
return TaskUpdateModel(programState.model, programState.model.modifyAnimation(newAnimation))
}
@UseCase("animation.channel.update.object")
private fun setAnimationChannelObjects(comp: Component, programState: IProgramState): ITask {
val ref = comp.metadata["ref"] as IChannelRef
val animation = programState.animation
val selection = programState.modelSelection.getOrNull() ?: return TaskNone
if (selection.selectionType != SelectionType.OBJECT) return TaskNone
if (selection.selectionTarget != SelectionTarget.MODEL) return TaskNone
val target = AnimationTargetObject(selection.objects)
val newAnimation = animation.withMapping(ref, target)
return TaskUpdateModel(programState.model, programState.model.modifyAnimation(newAnimation))
}
@UseCase("animation.channel.update.group")
private fun setAnimationChannelGroup(comp: Component, programState: IProgramState): ITask {
val ref = comp.metadata["ref"] as IChannelRef
val animation = programState.animation
val group = programState.selectedGroup
val target = if (group != RootGroupRef) AnimationTargetGroup(group) else return TaskNone
val newAnimation = animation.withMapping(ref, target)
return TaskUpdateModel(programState.model, programState.model.modifyAnimation(newAnimation))
}
@UseCase("animation.select")
private fun selectAnimation(comp: Component, projectManager: ProjectManager): ITask = ModifyGui {
val ref = comp.metadata["animation"] as IAnimationRef
selectAnimation(projectManager, it, ref)
}
@UseCase("animation.channel.delete")
private fun removeAnimationChannel(comp: Component, programState: IProgramState): ITask {
val animation = programState.animation
val channel = comp.metadata["ref"] as IChannelRef
val newAnimation = animation.removeChannels(listOf(channel))
return TaskUpdateModel(programState.model, programState.model.modifyAnimation(newAnimation))
}
@UseCase("animation.set.length")
private fun setAnimationLength(comp: Component, programState: IProgramState): ITask {
var animation = programState.animation
val newLength = comp.metadata["time"] as Float
if (newLength <= 0) return TaskNone
val diff = newLength / animation.timeLength
val newChannels = animation.channels.values.map { channel ->
channel.withKeyframes(channel.keyframes.map { keyframe ->
keyframe.withTime((keyframe.time * diff * 60f).roundToInt() / 60f)
})
}
newChannels.forEach {
animation = animation.withChannel(it)
}
animation = animation.withTimeLength(newLength)
return TaskUpdateModel(programState.model, programState.model.modifyAnimation(animation))
}
@UseCase("animation.panel.key")
private fun onAnimationPanelKey(comp: Component): ITask {
val offset = 5.fromFrame() * (if (comp.metadata["key"] == "left") -1 else 1)
return ModifyGui {
it.animator.animationTime += offset
}
}
@UseCase("animation.panel.click")
private fun onAnimationPanelClick(comp: Component, animator: Animator, input: IInput): ITask {
val mousePos = input.mouse.getMousePos()
val compPos = comp.absolutePositionV
val diffX = mousePos.xf - compPos.xf
val diffY = mousePos.yf - compPos.yf
val zoom = animator.zoom
val timeToPixel = comp.width / zoom
val pixelOffset = animator.offset * timeToPixel
val channels = animator.animation.channels.values
val time = (diffX - pixelOffset) / timeToPixel
// TODO fix incorrect bounding box
channels.forEachIndexed { i, channel ->
if (diffY > i * 24f && diffY <= (i + 1) * 24f) {
channel.keyframes.forEachIndexed { index, keyframe ->
val pos = keyframe.time * timeToPixel + pixelOffset
if (diffX > pos - 12f && diffX <= pos + 12f) {
return ModifyGui {
animator.selectedChannel = channel.ref
animator.selectedKeyframe = index
animator.animationTime = keyframe.time
animator.animationState = AnimationState.STOP
it.state.cursor.update(it)
}
}
}
}
}
// if (animator.animationState != AnimationState.STOP) return TaskNone
return ModifyGui {
animator.selectedKeyframe = null
animator.animationTime = time.toFrame().fromFrame()
it.state.cursor.update(it)
}
}
@UseCase("animation.state.toggle")
private fun animationTogglePlay(): ITask = ModifyGui {
if (it.animator.animationState == AnimationState.STOP) {
it.animator.animationState = AnimationState.FORWARD
} else {
it.animator.animationState = AnimationState.STOP
}
}
@UseCase("animation.state.backward")
private fun animationPlayBackwards(): ITask = ModifyGui {
it.animator.animationState = AnimationState.BACKWARD
}
@UseCase("animation.state.forward")
private fun animationPlayForward(): ITask = ModifyGui {
it.animator.animationState = AnimationState.FORWARD
}
@UseCase("animation.state.stop")
private fun animationStop(): ITask = ModifyGui {
it.animator.animationState = AnimationState.STOP
}
@UseCase("animation.seek.start")
private fun animationSeekStart(): ITask = ModifyGui {
it.animator.animationTime = 0f
}
@UseCase("animation.seek.end")
private fun animationSeekEnd(): ITask = ModifyGui {
it.animator.animationTime = it.programState.animation.timeLength
}
@UseCase("animation.prev.keyframe")
private fun prevKeyframe(animator: Animator): ITask {
val selected = animator.selectedChannel ?: return TaskNone
val channel = animator.animation.channels[selected]!!
val prev = channel.keyframes.findLast { it.time < animator.animationTime } ?: return TaskNone
return ModifyGui {
it.animator.animationTime = prev.time
it.state.cursor.update(it)
}
}
@UseCase("animation.next.keyframe")
private fun nextKeyframe(animator: Animator): ITask {
val selected = animator.selectedChannel ?: return TaskNone
val channel = animator.animation.channels[selected]!!
val next = channel.keyframes.find { it.time > animator.animationTime } ?: return TaskNone
return ModifyGui {
it.animator.animationTime = next.time
it.state.cursor.update(it)
}
} | gpl-3.0 | b7421379585dceb25d085155551c23aa | 34.704082 | 114 | 0.722758 | 4.609684 | false | false | false | false |
dev-cloverlab/Kloveroid | app/src/main/kotlin/com/cloverlab/kloveroid/usecases/BaseUseCase.kt | 1 | 8359 | package com.cloverlab.kloveroid.usecases
import com.cloverlab.kloveroid.usecases.BaseUseCase.RequestValues
import com.cloverlab.kloveroid.usecases.executor.PostExecutionThread
import com.cloverlab.kloveroid.usecases.executor.ThreadExecutor
import com.devrapid.kotlinshaver.ObserverPlugin
import com.trello.rxlifecycle3.LifecycleProvider
import com.trello.rxlifecycle3.kotlin.bindToLifecycle
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.Scheduler
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.ThreadPoolExecutor
/**
* Abstract class for a Use Case (Interactor in terms of Clean Architecture).
* This interface represents a execution unit for different use cases (this means any use case in the
* application should implement this contract).
*
* By convention each UseCase implementation will return the result using a [org.reactivestreams.Subscriber]
* that will execute its job in a background thread and will post the result in the UI thread.
*
* For passing a request parameters [RequestValues] to data layer that set a generic type for wrapping
* vary data.
*
* @author Jieyi Wu
* @since 2017/09/25
*/
abstract class BaseUseCase<T, R : BaseUseCase.RequestValues>(
threadExecutor: ThreadExecutor,
postExecutionThread: PostExecutionThread
) {
/** Provide a common parameter variable for the children class. */
var requestValues: R? = null
//region Usecase with an anonymous function.
/**
* Execute the current use case.
*
* @param lifecycleProvider the life cycle provider for cutting RxJava runs.
* @param block add some chain actions between [subscribeOn] and [observeOn].
* @param observer a reaction of [Observer] from viewmodel, the data are omitted from database or remote.
*/
fun <F> execute(
lifecycleProvider: LifecycleProvider<*>? = null,
block: Observable<T>.() -> Observable<F>,
observer: Observer<F>
) =
buildUseCaseObservable(block).apply { lifecycleProvider?.let { bindToLifecycle(it) } }.subscribe(observer)
/**
* Execute the current use case with request [parameter].
*
* @param parameter the parameter for retrieving data.
* @param lifecycleProvider the life cycle provider for cutting RxJava runs.
* @param block add some chain actions between [subscribeOn] and [observeOn].
* @param observer a reaction of [Observer] from viewmodel, the data are omitted from database or remote.
*/
fun <F> execute(
parameter: R,
lifecycleProvider: LifecycleProvider<*>? = null,
block: Observable<T>.() -> Observable<F>,
observer: Observer<F>
) {
requestValues = parameter
execute(lifecycleProvider, block, observer)
}
/**
* Execute the current use case with an anonymous function.
*
* @param lifecycleProvider an activity or a fragment of the [LifecycleProvider] object.
* @param block add some chain actions between [subscribeOn] and [observeOn].
* @param observer a reaction of [ObserverPlugin] from viewmodel, the data are omitted from database or remote.
*/
fun <F> execute(
lifecycleProvider: LifecycleProvider<*>? = null,
block: Observable<T>.() -> Observable<F>,
observer: ObserverPlugin<F>.() -> Unit
) =
execute(lifecycleProvider, block, ObserverPlugin<F>().apply(observer))
/**
* Execute the current use case with request [parameter] with an anonymous function..
*
* @param parameter the parameter for retrieving data.
* @param lifecycleProvider an activity or a fragment of the [LifecycleProvider] object.
* @param block add some chain actions between [subscribeOn] and [observeOn].
* @param observer a reaction of [ObserverPlugin] from viewmodel, the data are omitted from database or remote.
*/
fun <F> execute(
parameter: R,
lifecycleProvider: LifecycleProvider<*>? = null,
block: Observable<T>.() -> Observable<F>,
observer: ObserverPlugin<F>.() -> Unit
) {
requestValues = parameter
execute(lifecycleProvider, block, observer)
}
/**
* Build an [Observable] which will be used when executing the current [BaseUseCase].
* There is a [subscribeOn] for fetching the data from the
* [com.cloverlab.kloveroid.repository.repositories.DataRepository] works on the new thread
* so after [subscribeOn]'s chain function will be ran on the same thread.
* This is for who needs transfer the thread to UI, IO, or new thread again.
*
* @param block add some chain actions between [subscribeOn] and [observeOn].
* @return [Observable] for connecting with a [Observer] from the kotlin layer.
*/
private fun <F> buildUseCaseObservable(block: (Observable<T>.() -> Observable<F>)) =
fetchUsecase()
.subscribeOn(subscribeScheduler)
.run { block.invoke(this) }
.observeOn(observeScheduler)
//endregion
//region Usecase without an anonymous function.
/**
* Execute the current use case.
*
* @param lifecycleProvider the life cycle provider for cutting RxJava runs.
* @param observer a reaction of [Observer] from viewmodel, the data are omitted from database or remote.
*/
fun execute(lifecycleProvider: LifecycleProvider<*>? = null, observer: Observer<T>) =
buildUseCaseObservable().apply { lifecycleProvider?.let { bindToLifecycle(it) } }.subscribe(observer)
/**
* Execute the current use case with request [parameter].
*
* @param parameter the parameter for retrieving data.
* @param lifecycleProvider the life cycle provider for cutting RxJava runs.
* @param observer a reaction of [Observer] from viewmodel, the data are omitted from database or remote.
*/
fun execute(parameter: R, lifecycleProvider: LifecycleProvider<*>? = null, observer: Observer<T>) {
requestValues = parameter
execute(lifecycleProvider, observer)
}
/**
* Execute the current use case.
*
* @param lifecycleProvider an activity or a fragment of the [LifecycleProvider] object.
* @param observer a reaction of [ObserverPlugin] from viewmodel, the data are omitted from database or remote.
*/
fun execute(lifecycleProvider: LifecycleProvider<*>? = null, observer: ObserverPlugin<T>.() -> Unit) =
execute(lifecycleProvider, ObserverPlugin<T>().apply(observer))
/**
* Execute the current use case with request [parameter].
*
* @param parameter the parameter for retrieving data.
* @param lifecycleProvider an activity or a fragment of the [LifecycleProvider] object.
* @param observer a reaction of [ObserverPlugin] from viewmodel, the data are omitted from database or remote.
*/
fun execute(parameter: R, lifecycleProvider: LifecycleProvider<*>? = null, observer: ObserverPlugin<T>.() -> Unit) {
requestValues = parameter
execute(lifecycleProvider, observer)
}
/**
* Build an [Observable] which will be used when executing the current [BaseUseCase] and run on
* the UI thread.
*
* @return [Observable] for connecting with a [Observer] from the kotlin layer.
*/
private fun buildUseCaseObservable() =
fetchUsecase()
.subscribeOn(subscribeScheduler)
.observeOn(observeScheduler)
//endregion
/**
* Choose a method from [com.cloverlab.kloveroid.repository.source.IDataStore] and fit this usecase
* for return some data.
*
* @return an [Observer] for chaining on working threads.
*/
protected abstract fun fetchUsecase(): Observable<T>
/**
* Obtain a thread for while [Observable] is doing their tasks.
*
* @return [Scheduler] implement from [PostExecutionThread].
*/
protected open val observeScheduler: Scheduler = postExecutionThread.scheduler
/**
* Obtain a thread from [ThreadPoolExecutor] for while [Scheduler] is doing their tasks.
*
* @return [Scheduler] implement from [ThreadExecutor].
*/
protected open val subscribeScheduler: Scheduler = Schedulers.from(threadExecutor)
/** Interface for wrap a data for passing to a request.*/
interface RequestValues
}
| mit | 1b0c0094c44f4b73af26c39f50f937fb | 41.431472 | 120 | 0.693025 | 4.937389 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/jvm-debugger/eval4j/src/org/jetbrains/eval4j/jdi/jdiEval.kt | 1 | 22140 | // 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.eval4j.jdi
import com.intellij.openapi.util.text.StringUtil
import com.sun.jdi.*
import org.jetbrains.eval4j.*
import org.jetbrains.eval4j.Value
import org.jetbrains.org.objectweb.asm.Type
import java.lang.reflect.AccessibleObject
import com.sun.jdi.Type as jdi_Type
import com.sun.jdi.Value as jdi_Value
private val CLASS = Type.getType(Class::class.java)
private val OBJECT = Type.getType(Any::class.java)
private val BOOTSTRAP_CLASS_DESCRIPTORS = setOf("Ljava/lang/String;", "Ljava/lang/ClassLoader;", "Ljava/lang/Class;")
open class JDIEval(
private val vm: VirtualMachine,
private val defaultClassLoader: ClassLoaderReference?,
protected val thread: ThreadReference,
private val invokePolicy: Int
) : Eval {
private val primitiveTypes = mapOf(
Type.BOOLEAN_TYPE.className to vm.mirrorOf(true).type(),
Type.BYTE_TYPE.className to vm.mirrorOf(1.toByte()).type(),
Type.SHORT_TYPE.className to vm.mirrorOf(1.toShort()).type(),
Type.INT_TYPE.className to vm.mirrorOf(1).type(),
Type.CHAR_TYPE.className to vm.mirrorOf('1').type(),
Type.LONG_TYPE.className to vm.mirrorOf(1L).type(),
Type.FLOAT_TYPE.className to vm.mirrorOf(1.0f).type(),
Type.DOUBLE_TYPE.className to vm.mirrorOf(1.0).type()
)
private val isJava8OrLater = StringUtil.compareVersionNumbers(vm.version(), "1.8") >= 0
override fun loadClass(classType: Type): Value {
return loadClass(classType, defaultClassLoader)
}
private fun loadClass(classType: Type, classLoader: ClassLoaderReference?): Value {
val loadedClasses = vm.classesByName(classType.jdiName)
if (loadedClasses.isNotEmpty()) {
for (loadedClass in loadedClasses) {
if (loadedClass.isPrepared && (classType.descriptor in BOOTSTRAP_CLASS_DESCRIPTORS || loadedClass.classLoader() == classLoader)) {
return loadedClass.classObject().asValue()
}
}
}
if (classLoader == null) {
return invokeStaticMethod(
MethodDescription(
CLASS.internalName,
"forName",
"(Ljava/lang/String;)Ljava/lang/Class;",
true
),
listOf(vm.mirrorOf(classType.jdiName).asValue())
)
} else {
return invokeStaticMethod(
MethodDescription(
CLASS.internalName,
"forName",
"(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;",
true
),
listOf(
vm.mirrorOf(classType.jdiName).asValue(),
boolean(true),
classLoader.asValue()
)
)
}
}
private fun loadClassByName(name: String, classLoader: ClassLoaderReference): jdi_Type {
val dimensions = name.count { it == '[' }
val baseTypeName = if (dimensions > 0) name.substring(0, name.indexOf('[')) else name
val baseType = primitiveTypes[baseTypeName] ?: Type.getType("L$baseTypeName;").asReferenceType(classLoader)
return if (dimensions == 0)
baseType
else
Type.getType("[".repeat(dimensions) + baseType.asType().descriptor).asReferenceType(classLoader)
}
override fun loadString(str: String): Value = vm.mirrorOf(str).asValue()
override fun newInstance(classType: Type): Value {
return NewObjectValue(classType)
}
override fun isInstanceOf(value: Value, targetType: Type): Boolean {
assert(targetType.sort == Type.OBJECT || targetType.sort == Type.ARRAY) {
"Can't check isInstanceOf() for non-object type $targetType"
}
val clazz = loadClass(targetType)
return invokeMethod(
clazz,
MethodDescription(
CLASS.internalName,
"isInstance",
"(Ljava/lang/Object;)Z",
false
),
listOf(value)
).boolean
}
private fun Type.asReferenceType(classLoader: ClassLoaderReference? = [email protected]): ReferenceType =
loadClass(this, classLoader).jdiClass!!.reflectedType()
private fun Type.asArrayType(classLoader: ClassLoaderReference? = [email protected]): ArrayType =
asReferenceType(classLoader) as ArrayType
override fun newArray(arrayType: Type, size: Int): Value {
val jdiArrayType = arrayType.asArrayType()
return jdiArrayType.newInstance(size).asValue()
}
private val Type.arrayElementType: Type
get(): Type {
assert(sort == Type.ARRAY) { "Not an array type: $this" }
return Type.getType(descriptor.substring(1))
}
private fun fillArray(elementType: Type, size: Int, nestedSizes: List<Int>): Value {
val arr = newArray(Type.getType("[" + elementType.descriptor), size)
if (nestedSizes.isNotEmpty()) {
val nestedElementType = elementType.arrayElementType
val nestedSize = nestedSizes[0]
val tail = nestedSizes.drop(1)
for (i in 0 until size) {
setArrayElement(arr, int(i), fillArray(nestedElementType, nestedSize, tail))
}
}
return arr
}
override fun newMultiDimensionalArray(arrayType: Type, dimensionSizes: List<Int>): Value {
return fillArray(arrayType.arrayElementType, dimensionSizes[0], dimensionSizes.drop(1))
}
private fun Value.array() = jdiObj.checkNull() as ArrayReference
override fun getArrayLength(array: Value): Value {
return int(array.array().length())
}
override fun getArrayElement(array: Value, index: Value): Value {
try {
return array.array().getValue(index.int).asValue()
} catch (e: IndexOutOfBoundsException) {
throwInterpretingException(ArrayIndexOutOfBoundsException(e.message))
}
}
override fun setArrayElement(array: Value, index: Value, newValue: Value) {
try {
return array.array().setValue(index.int, newValue.asJdiValue(vm, array.asmType.arrayElementType))
} catch (e: IndexOutOfBoundsException) {
throwInterpretingException(ArrayIndexOutOfBoundsException(e.message))
}
}
private fun findField(fieldDesc: FieldDescription, receiver: ReferenceType? = null): Field {
receiver?.fieldByName(fieldDesc.name)?.let { return it }
fieldDesc.ownerType.asReferenceType().fieldByName(fieldDesc.name)?.let { return it }
throwBrokenCodeException(NoSuchFieldError("Field not found: $fieldDesc"))
}
private fun findStaticField(fieldDesc: FieldDescription): Field {
val field = findField(fieldDesc)
if (!field.isStatic) {
throwBrokenCodeException(NoSuchFieldError("Field is not static: $fieldDesc"))
}
return field
}
override fun getStaticField(fieldDesc: FieldDescription): Value {
val field = findStaticField(fieldDesc)
return mayThrow { field.declaringType().getValue(field) }.ifFail(field).asValue()
}
override fun setStaticField(fieldDesc: FieldDescription, newValue: Value) {
val field = findStaticField(fieldDesc)
if (field.isFinal) {
throwBrokenCodeException(NoSuchFieldError("Can't modify a final field: $field"))
}
val clazz = field.declaringType() as? ClassType
?: throwBrokenCodeException(NoSuchFieldError("Can't a field in a non-class: $field"))
val jdiValue = newValue.asJdiValue(vm, field.type().asType())
mayThrow { clazz.setValue(field, jdiValue) }.ifFail(field)
}
private fun findMethod(methodDesc: MethodDescription, clazz: ReferenceType = methodDesc.ownerType.asReferenceType()): Method {
val method = findMethodOrNull(methodDesc, clazz)
if (method != null) {
return method
}
throwBrokenCodeException(NoSuchMethodError("Method not found: $methodDesc"))
}
private fun findMethodOrNull(methodDesc: MethodDescription, clazz: ReferenceType): Method? {
val methodName = methodDesc.name
var method: Method?
when (clazz) {
is ClassType -> {
method = clazz.concreteMethodByName(methodName, methodDesc.desc)
}
is ArrayType -> { // Copied from com.intellij.debugger.engine.DebuggerUtils.findMethod
val objectType = OBJECT.asReferenceType()
method = findMethodOrNull(methodDesc, objectType)
if (method == null && methodDesc.name == "clone" && methodDesc.desc == "()[Ljava/lang/Object;") {
method = findMethodOrNull(MethodDescription(OBJECT.internalName, "clone", "()[Ljava/lang/Object;", false), objectType)
}
}
else -> {
method = clazz.methodsByName(methodName, methodDesc.desc).firstOrNull()
}
}
if (method != null) {
return method
}
// Module name can be different for internal functions during evaluation and compilation
val internalNameWithoutSuffix = internalNameWithoutModuleSuffix(methodName)
if (internalNameWithoutSuffix != null) {
val internalMethods = clazz.visibleMethods().filter {
val name = it.name()
name.startsWith(internalNameWithoutSuffix) && '$' in name && it.signature() == methodDesc.desc
}
if (internalMethods.isNotEmpty()) {
return internalMethods.singleOrNull()
?: throwBrokenCodeException(IllegalArgumentException("Several internal methods found for $methodDesc"))
}
}
return null
}
private fun internalNameWithoutModuleSuffix(name: String): String? {
val indexOfDollar = name.indexOf('$')
val demangledName = if (indexOfDollar >= 0) name.substring(0, indexOfDollar) else null
return if (demangledName != null) "$demangledName$" else null
}
open fun jdiInvokeStaticMethod(type: ClassType, method: Method, args: List<jdi_Value?>, invokePolicy: Int): jdi_Value? {
return type.invokeMethod(thread, method, args, invokePolicy)
}
open fun jdiInvokeStaticMethod(type: InterfaceType, method: Method, args: List<jdi_Value?>, invokePolicy: Int): jdi_Value? {
return type.invokeMethod(thread, method, args, invokePolicy)
}
override fun invokeStaticMethod(methodDesc: MethodDescription, arguments: List<Value>): Value {
val method = findMethod(methodDesc)
if (!method.isStatic) {
throwBrokenCodeException(NoSuchMethodError("Method is not static: $methodDesc"))
}
val declaringType = method.declaringType()
val args = mapArguments(arguments, method.safeArgumentTypes())
if (shouldInvokeMethodWithReflection(method, args)) {
return invokeMethodWithReflection(declaringType.asType(), NULL_VALUE, args, methodDesc)
}
args.disableCollection()
val result = mayThrow {
when (declaringType) {
is ClassType -> jdiInvokeStaticMethod(declaringType, method, args, invokePolicy)
is InterfaceType -> {
if (!isJava8OrLater) {
val message = "Calling interface static methods is not supported in JVM ${vm.version()} ($method)"
throwBrokenCodeException(NoSuchMethodError(message))
}
jdiInvokeStaticMethod(declaringType, method, args, invokePolicy)
}
else -> {
val message = "Calling static methods is only supported for classes and interfaces ($method)"
throwBrokenCodeException(NoSuchMethodError(message))
}
}
}.ifFail(method)
args.enableCollection()
return result.asValue()
}
override fun getField(instance: Value, fieldDesc: FieldDescription): Value {
val receiver = instance.jdiObj.checkNull()
val field = findField(fieldDesc, receiver.referenceType())
return mayThrow {
try {
receiver.getValue(field)
} catch (e: IllegalArgumentException) {
throw IllegalArgumentException(
"Possibly incompatible types: " +
"field declaring type = ${field.declaringType()}, " +
"instance type = ${receiver.referenceType()}"
)
}
}.ifFail(field, receiver).asValue()
}
override fun setField(instance: Value, fieldDesc: FieldDescription, newValue: Value) {
val receiver = instance.jdiObj.checkNull()
val field = findField(fieldDesc, receiver.referenceType())
val jdiValue = newValue.asJdiValue(vm, field.type().asType())
mayThrow { receiver.setValue(field, jdiValue) }
}
private fun unboxType(boxedValue: Value, type: Type): Value {
val method = when (type) {
Type.INT_TYPE -> MethodDescription("java/lang/Integer", "intValue", "()I", false)
Type.BOOLEAN_TYPE -> MethodDescription("java/lang/Boolean", "booleanValue", "()Z", false)
Type.CHAR_TYPE -> MethodDescription("java/lang/Character", "charValue", "()C", false)
Type.SHORT_TYPE -> MethodDescription("java/lang/Character", "shortValue", "()S", false)
Type.LONG_TYPE -> MethodDescription("java/lang/Long", "longValue", "()J", false)
Type.BYTE_TYPE -> MethodDescription("java/lang/Byte", "byteValue", "()B", false)
Type.FLOAT_TYPE -> MethodDescription("java/lang/Float", "floatValue", "()F", false)
Type.DOUBLE_TYPE -> MethodDescription("java/lang/Double", "doubleValue", "()D", false)
else -> throw UnsupportedOperationException("Couldn't unbox non primitive type ${type.internalName}")
}
return invokeMethod(boxedValue, method, listOf(), true)
}
open fun jdiInvokeMethod(obj: ObjectReference, method: Method, args: List<jdi_Value?>, policy: Int): jdi_Value? {
return obj.invokeMethod(thread, method, args, policy)
}
override fun invokeMethod(instance: Value, methodDesc: MethodDescription, arguments: List<Value>, invokeSpecial: Boolean): Value {
if (invokeSpecial && methodDesc.name == "<init>") {
// Constructor call
val ctor = findMethod(methodDesc)
val clazz = (instance as NewObjectValue).asmType.asReferenceType() as ClassType
val args = mapArguments(arguments, ctor.safeArgumentTypes())
args.disableCollection()
val result = mayThrow { clazz.newInstance(thread, ctor, args, invokePolicy) }.ifFail(ctor)
args.enableCollection()
instance.value = result
return result.asValue()
}
fun doInvokeMethod(obj: ObjectReference, method: Method, policy: Int): Value {
val args = mapArguments(arguments, method.safeArgumentTypes())
if (shouldInvokeMethodWithReflection(method, args)) {
return invokeMethodWithReflection(instance.asmType, instance, args, methodDesc)
}
args.disableCollection()
val result = mayThrow { jdiInvokeMethod(obj, method, args, policy) }.ifFail(method, obj)
args.enableCollection()
return result.asValue()
}
val obj = instance.jdiObj.checkNull()
return if (invokeSpecial) {
val method = findMethod(methodDesc)
doInvokeMethod(obj, method, invokePolicy or ObjectReference.INVOKE_NONVIRTUAL)
} else {
val method = findMethod(methodDesc, obj.referenceType() ?: methodDesc.ownerType.asReferenceType())
doInvokeMethod(obj, method, invokePolicy)
}
}
private fun shouldInvokeMethodWithReflection(method: Method, args: List<com.sun.jdi.Value?>): Boolean {
if (method.isVarArgs) {
return false
}
val argumentTypes = try {
method.argumentTypes()
} catch (e: ClassNotLoadedException) {
return false
}
return args.zip(argumentTypes).any { isArrayOfInterfaces(it.first?.type(), it.second) }
}
private fun isArrayOfInterfaces(valueType: jdi_Type?, expectedType: jdi_Type?): Boolean {
return (valueType as? ArrayType)?.componentType() is InterfaceType && (expectedType as? ArrayType)?.componentType() == OBJECT.asReferenceType()
}
private fun invokeMethodWithReflection(ownerType: Type, instance: Value, args: List<jdi_Value?>, methodDesc: MethodDescription): Value {
val methodToInvoke = invokeMethod(
loadClass(ownerType),
MethodDescription(
CLASS.internalName,
"getDeclaredMethod",
"(Ljava/lang/String;[L${CLASS.internalName};)Ljava/lang/reflect/Method;",
true
),
listOf(vm.mirrorOf(methodDesc.name).asValue(), *methodDesc.parameterTypes.map { loadClass(it) }.toTypedArray())
)
invokeMethod(
methodToInvoke,
MethodDescription(
Type.getType(AccessibleObject::class.java).internalName,
"setAccessible",
"(Z)V",
true
),
listOf(vm.mirrorOf(true).asValue())
)
val invocationResult = invokeMethod(
methodToInvoke,
MethodDescription(
methodToInvoke.asmType.internalName,
"invoke",
"(L${OBJECT.internalName};[L${OBJECT.internalName};)L${OBJECT.internalName};",
true
),
listOf(instance, mirrorOfArgs(args))
)
return if (methodDesc.returnType.sort != Type.OBJECT &&
methodDesc.returnType.sort != Type.ARRAY &&
methodDesc.returnType.sort != Type.VOID
)
unboxType(invocationResult, methodDesc.returnType)
else
invocationResult
}
private fun mirrorOfArgs(args: List<jdi_Value?>): Value {
val arrayObject = newArray(Type.getType("[" + OBJECT.descriptor), args.size)
args.forEachIndexed { index, value ->
val indexValue = vm.mirrorOf(index).asValue()
setArrayElement(arrayObject, indexValue, value.asValue())
}
return arrayObject
}
private fun List<jdi_Value?>.disableCollection() {
forEach { (it as? ObjectReference)?.disableCollection() }
}
private fun List<jdi_Value?>.enableCollection() {
forEach { (it as? ObjectReference)?.enableCollection() }
}
private fun mapArguments(arguments: List<Value>, expectedTypes: List<jdi_Type>): List<jdi_Value?> {
return arguments.zip(expectedTypes).map {
val (arg, expectedType) = it
arg.asJdiValue(vm, expectedType.asType())
}
}
private fun Method.safeArgumentTypes(): List<jdi_Type> {
try {
return argumentTypes()
} catch (e: ClassNotLoadedException) {
return argumentTypeNames()!!.map { name ->
val classLoader = declaringType()?.classLoader()
if (classLoader != null) {
return@map loadClassByName(name, classLoader)
}
when (name) {
"void" -> virtualMachine().mirrorOfVoid().type()
"boolean" -> primitiveTypes.getValue(Type.BOOLEAN_TYPE.className)
"byte" -> primitiveTypes.getValue(Type.BYTE_TYPE.className)
"char" -> primitiveTypes.getValue(Type.CHAR_TYPE.className)
"short" -> primitiveTypes.getValue(Type.SHORT_TYPE.className)
"int" -> primitiveTypes.getValue(Type.INT_TYPE.className)
"long" -> primitiveTypes.getValue(Type.LONG_TYPE.className)
"float" -> primitiveTypes.getValue(Type.FLOAT_TYPE.className)
"double" -> primitiveTypes.getValue(Type.DOUBLE_TYPE.className)
else -> virtualMachine().classesByName(name).firstOrNull()
?: throw IllegalStateException("Unknown class $name")
}
}
}
}
}
internal val Type.jdiName: String
get() = internalName.replace('/', '.')
@Suppress("unused")
private sealed class JdiOperationResult<T> {
class Fail<T>(val cause: Exception) : JdiOperationResult<T>()
class OK<T>(val value: T) : JdiOperationResult<T>()
}
private fun <T> mayThrow(f: () -> T): JdiOperationResult<T> {
return try {
JdiOperationResult.OK(f())
} catch (e: IllegalArgumentException) {
JdiOperationResult.Fail(e)
} catch (e: InvocationException) {
throw ThrownFromEvaluatedCodeException(e.exception().asValue())
}
}
private fun memberInfo(member: TypeComponent, thisObj: ObjectReference?): String {
return "\nmember = $member\nobjectRef = $thisObj"
}
private fun <T> JdiOperationResult<T>.ifFail(member: TypeComponent, thisObj: ObjectReference? = null): T {
return ifFail { memberInfo(member, thisObj) }
}
private fun <T> JdiOperationResult<T>.ifFail(lazyMessage: () -> String): T {
return when (this) {
is JdiOperationResult.OK -> this.value
is JdiOperationResult.Fail -> {
if (cause is IllegalArgumentException) {
throwBrokenCodeException(IllegalArgumentException(lazyMessage(), this.cause))
} else {
throwBrokenCodeException(IllegalStateException(lazyMessage(), this.cause))
}
}
}
} | apache-2.0 | 0d81ad0a3cedda792783235231c590fd | 40.154275 | 158 | 0.617931 | 5.024966 | false | false | false | false |
square/okhttp | samples/guide/src/main/java/okhttp3/recipes/kt/PostForm.kt | 2 | 1284 | /*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.recipes.kt
import java.io.IOException
import okhttp3.FormBody
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.OkHttpClient
import okhttp3.Request
class PostForm {
private val client = OkHttpClient()
fun run() {
val formBody = FormBody.Builder()
.add("search", "Jurassic Park")
.build()
val request = Request(
url = "https://en.wikipedia.org/w/index.php".toHttpUrl(),
body = formBody,
)
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("Unexpected code $response")
println(response.body.string())
}
}
}
fun main() {
PostForm().run()
}
| apache-2.0 | 9a6d131377988cd673edc78ad485b6e6 | 26.913043 | 80 | 0.699377 | 3.975232 | false | false | false | false |
androidx/androidx | fragment/fragment/src/androidTest/java/androidx/fragment/app/ActivityLeakTest.kt | 3 | 4090 | /*
* Copyright 2019 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.fragment.app
import androidx.test.filters.LargeTest
import androidx.test.platform.app.InstrumentationRegistry
import androidx.testutils.RecreatedActivity
import androidx.testutils.recreate
import androidx.testutils.runOnUiThreadRethrow
import androidx.testutils.waitForExecution
import com.google.common.truth.Truth.assertWithMessage
import java.lang.ref.WeakReference
import leakcanary.DetectLeaksAfterTestSuccess
import org.junit.Rule
import org.junit.Test
import org.junit.rules.RuleChain
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
/**
* Class representing the different configurations for testing leaks
*/
sealed class LeakConfiguration {
abstract fun commit(fragmentManager: FragmentManager): Fragment?
override fun toString(): String = this.javaClass.simpleName
}
object NotRetained : LeakConfiguration() {
override fun commit(fragmentManager: FragmentManager) = StrictFragment().also {
fragmentManager.beginTransaction()
.add(it, "tag")
.commitNow()
}
}
object Retained : LeakConfiguration() {
@Suppress("DEPRECATION")
override fun commit(fragmentManager: FragmentManager) = StrictFragment().apply {
retainInstance = true
}.also {
fragmentManager.beginTransaction()
.add(it, "tag")
.commitNow()
}
}
object NoChild : LeakConfiguration() {
override fun commit(fragmentManager: FragmentManager): Fragment? = null
}
@LargeTest
@RunWith(Parameterized::class)
class ActivityLeakTest(
private val parentConfiguration: LeakConfiguration,
private val childConfiguration: LeakConfiguration
) {
companion object {
@JvmStatic
@Parameterized.Parameters(name = "parent={0}, child={1}")
fun data() = mutableListOf<Array<Any>>().apply {
arrayOf(
NotRetained,
Retained
).forEach { operation ->
add(arrayOf(operation, NotRetained))
add(arrayOf(operation, Retained))
add(arrayOf(operation, NoChild))
}
}
}
@Suppress("DEPRECATION")
val activityRule = androidx.test.rule.ActivityTestRule(ActivityLeakActivity::class.java)
// Detect leaks BEFORE and AFTER activity is destroyed
@get:Rule
val ruleChain: RuleChain = RuleChain.outerRule(DetectLeaksAfterTestSuccess())
.around(activityRule)
@Test
fun testActivityDoesNotLeak() {
// Restart the activity because activityRule keeps a strong reference to the
// old activity.
val activity = activityRule.recreate()
activityRule.runOnUiThreadRethrow {
val parent = parentConfiguration.commit(activity.supportFragmentManager)!!
childConfiguration.commit(parent.childFragmentManager)
}
val weakRef = WeakReference(ActivityLeakActivity.activity)
// Wait for everything to settle. We have to make sure that the old Activity
// is ready to be collected.
InstrumentationRegistry.getInstrumentation().waitForIdleSync()
activityRule.waitForExecution()
// Force a garbage collection.
forceGC()
assertWithMessage("Old activity should be garbage collected")
.that(weakRef.get())
.isNull()
}
}
class ActivityLeakActivity : RecreatedActivity() {
companion object {
val activity get() = RecreatedActivity.activity
}
}
| apache-2.0 | 9552cada0906edf4e66575b5fca203d9 | 31.983871 | 92 | 0.701467 | 4.98173 | false | true | false | false |
Yusspy/Jolt-Sphere | core/src/org/joltsphere/misc/NeuralNetwork.kt | 1 | 12551 | package org.joltsphere.misc
import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import com.badlogic.gdx.math.Vector2
import java.text.FieldPosition
/** Creates a fully fleshed out ReLu regression neural network
* - Feedforward on command, backpropagate to reduce error.
*
* @param numberOfInputs a value that sets the number of input neurons
* @param numberOfOutputs a value that sets the number of output neurons
* @param hiddenLayerConfiguration an int-array with the size of it setting the number of hidden layers, and with each corresponding value setting the number of neurons in that hidden layer
*/
class NeuralNetwork(val numberOfInputs: Int, val numberOfOutputs: Int, val hiddenLayerConfiguration: IntArray) {
var cost = 0f
val numberOfHiddenLayers = hiddenLayerConfiguration.size
val networkSynapses: Array<Array<FloatArray>>
lateinit var neuralView: NeuralViewer
init {
val layerSizes = IntArray(2+numberOfHiddenLayers)
layerSizes[0] = numberOfInputs // first layer consists of the input neurons
layerSizes[layerSizes.size-1] = numberOfOutputs // last layer is just the output neurons
for (i in 1 until layerSizes.size-1) layerSizes[i] = hiddenLayerConfiguration[i-1] // for each of the hidden layers, set the layer size to the number of hidden layer neurons
networkSynapses = Array(layerSizes.size-1, // create a weight matrix for every layer of the neural network except the output
{ i -> (randomMatrix(layerSizes[i]+1,layerSizes[i+1])).multiply(2f).subtract(1f) })
// the matrix size is equal to (layer size + a bias weight) X (layer size of the next layer); creates a random matrix *2 -1 to put all values from -1 to 1
}
/** Feeds an array of inputs into the network to predict a set of outputs to the best of its ability in its current state.
* @param inputs an array of inputs equivalent to the number of input neurons
* @return an array of outputs corresponding to the output neurons with respect to the inputs
*/
fun feedforward(inputs: FloatArray): FloatArray {
val input = Array(1, { inputs }) // turns array of inputs into a single row matrix
var justALayer = input // this is just a layer variable that is recycled throughout the feedforward process
for (i in 0 until networkSynapses.size) {
justALayer = addBiasColumn(justALayer).dot(networkSynapses[i]) // get next layer by multiplying current layer with a bias column by the synapses for that layer
if (i != networkSynapses.size-1) justALayer = leakyReLu(justALayer) // if it isn't the last layer, which has no activation, then apply the the leaky ReLu activation function
}
return justALayer[0] // returns the only row in the matrix
}
/** Reduces the error of the neural network using gradient descent. Increasing the size of the training data mini-batches will increase the accuracy of the error reduction.
* - Note that the training inputs matrix and target outputs matrix should have the same number of rows.
* @param trainingInputs a matrix of inputs with each row being a set of inputs for each input neuron
* @param targetOutputs a matrix with rows of the target output values corresponding to that row on the the training inputs
* @param learningRate how large of a gradient descent step the network takes, if set too high, it will converge quickly but will be inaccurate
* - you must set this below 0.03, for accuracy maybe even around 0.005
* @param weightDecay how much the network will focus on preventing over-fitting by favoring smaller weight values, set this around or below 0.1
*/
fun backpropagate(trainingInputs: Array<FloatArray>, targetOutputs: Array<FloatArray>, learningRate: Float, weightDecay: Float) {
// some error handling in case the training data is incompatible
if (columns(trainingInputs) != numberOfInputs) throw IllegalArgumentException("The training data's ${columns(trainingInputs)} != $numberOfInputs input neurons")
if (columns(targetOutputs) != numberOfOutputs) throw IllegalArgumentException("The target output's ${columns(targetOutputs)} != $numberOfOutputs output neurons")
var layers = Array(networkSynapses.size+1, { Array(1, { FloatArray(1) } ) }) // array of every layer after activation
val lastLayer = layers.size - 1
layers[0] = addBiasColumn(trainingInputs) // set the first layer to the inputs
for (i in 1 until layers.size) {
layers[i] = addBiasColumn(layers[i-1].dot(networkSynapses[i-1])) // get this layer by dot product multiplying previous layer by the synapses for that layer
if (i != layers.size-1) layers[i] = leakyReLu(layers[i]) // if it isn't the last layer, which has no activation, then apply the the leaky ReLu activation function
}
layers[lastLayer] = removeBiasColumn(layers[lastLayer]) // cut the uneccesary bias neuron from the output layer
val predictedOutputs = layers.last() // the final layer contains the network predictions
val layerErrors = layers.copyOf() // an array of matrices that contain the error for each layer
cost = ( (predictedOutputs.subtract(targetOutputs)).power(2f) ).mean() // cost is found by taking the average of all the squared errors
layerErrors[lastLayer] = 2f.multiply(predictedOutputs.subtract(targetOutputs)) // derivative of cost function
//printMatrix(layerErrors[lastLayer])
val layerDeltas = layerErrors.copyOf() // last layer is equivalent already due to the lack of a final layer activation function
val deltaNetworkSynapses = networkSynapses.copyOf()
for (i in networkSynapses.size-1 downTo 0) {
if (i != networkSynapses.size-1) {
// the error of the layer this synapse[i] feeds into = to the delta of the layer ahead dot product multiplied by the transpose of the synapses ahead
layerErrors[i+1] = removeBiasColumn(layerDeltas[i+2].dot(networkSynapses[i+1].T()))
// the delta change of the layer this synpase[i] feeds into = the layer's error element multiplied by the slope of that layer's activation
layerDeltas[i+1] = layerErrors[i+1].multiply(removeBiasColumn(leakyReLuPrime(layers[i+1])))
}
// the change in synapse matrix i equals the transpose of the layer i (that feeds into synapses i) dot-product multiplied by the layer delta of the layer ahead
deltaNetworkSynapses[i] = learningRate.multiply(layers[i].T().dot(layerDeltas[i+1]))
}
//println()
//println("Cost: " + cost)
//println("Predictions: ")
//printMatrix(predictedOutputs)
/*println("Input Layer: ")
printMatrix(layers[0])
println("Hidden Layer: ")
printMatrix(layers[1])
println("Synapses: Input to Hidden")
printMatrix(networkSynapses[0])
println("Synapses: Hidden to Out")
printMatrix(networkSynapses[1])*/
for (i in 0 until networkSynapses.size) // the weight decay is computed to prefer smaller weights
networkSynapses[i] = networkSynapses[i].subtract( // subtract the changes
deltaNetworkSynapses[i].add(weightDecay.multiply(zeroBiasWeights(networkSynapses[i])))) // just add the changes of the matrix + weight decay
}
/** Returns a string of every weight of the neural network, with each line being a different weight.
*/
fun getSaveState(): String {
var string = ""
for (i in 0 until networkSynapses.size)
for (j in 0 until rows(networkSynapses[i]))
for (k in 0 until columns(networkSynapses[i]))
string = string + networkSynapses[i][j][k] + "\n"
return string
}
fun loadSaveState(saveState: String) {
try {
var currentLine = 1
for (i in 0 until networkSynapses.size)
for (j in 0 until rows(networkSynapses[i]))
for (k in 0 until columns(networkSynapses[i])) {
networkSynapses[i][j][k] = Misc.getLine(saveState, currentLine).toFloat()
currentLine++
}
}
catch (e: Exception) {
println("Failed to load")
println(e.message)
}
}
/** Adds a columns of 1's to your matrix! Have you ever wanted your layer's input values for the next layer to have a 1 in it to simulate a bias!?
* Well now you can thanks to our revolutionary, simple, and instant "Add-A-Bias"© matrix technology!
*/
fun addBiasColumn(matrix: Array<FloatArray>): Array<FloatArray> {
val output = Array(rows(matrix), { FloatArray(columns(matrix)+1) }) // creates a matrix of the equivalent size but with an extra columns
for (i in 0 until rows(matrix))
for (j in 0 until columns(matrix)) output[i][j] = matrix[i][j] // sets the values of the output to the values of the matrix
for (i in 0 until rows(output)) output[i][columns(output)-1] = 1f // set the bias values
return output
}
/** Simply removes the last column of your matrix... :\
*/
fun removeBiasColumn(matrix: Array<FloatArray>): Array<FloatArray> {
val output = Array(rows(matrix), { FloatArray(columns(matrix)-1) }) // creates a matrix of the equivalent size but with one less column
for (i in 0 until rows(output))
for (j in 0 until columns(output)) output[i][j] = matrix[i][j] // sets the values of the output to the values of the matrix
return output
}
/** Sets all your bias weights to zero by swapping the last row of your matrix with zeroes.
*/
fun zeroBiasWeights(matrix: Array<FloatArray>): Array<FloatArray> {
val output = Array(rows(matrix), { FloatArray(columns(matrix)) }) // creates a matrix of the equivalent size
for (i in 0 until rows(matrix)-1) // counts up to all but the last row
for (j in 0 until columns(matrix)) output[i][j] = matrix[i][j] // sets the values of the output to the values of the matrix
for (i in 0 until columns(output)) output[rows(output)-1][i] = 0f // set the bias weights to zero
return output
}
// To prevent the death of neurons, a very small gradient is added in to the max function when x < 0
private val leakyReLuSlope = 0.05f
fun leakyReLu(x: Array<FloatArray>): Array<FloatArray> {
val output = x
for (i in 0 until rows(x))
for (j in 0 until columns(x))
if (x[i][j] < 0) output[i][j] *= leakyReLuSlope
return output
}
fun leakyReLuPrime(x: Array<FloatArray>): Array<FloatArray> {
val output = x
for (i in 0 until rows(x))
for (j in 0 until columns(x))
if (x[i][j] > 0) output[i][j] = 1f
else output[i][j] = leakyReLuSlope
return output
}
inner class NeuralViewer(width: Float, height: Float, size: Float) {
var dimensions = Vector2(width, height)
var size = size
fun configureProperties(width: Float, height: Float, size: Float) {
dimensions = Vector2(width, height)
this.size = size
}
fun renderWeights(shapeRenderer: ShapeRenderer, position: Vector2) {
}
fun renderFeedforward(shapeRenderer: ShapeRenderer, position: Vector2) {
}
fun renderFeedforwardStep(shapeRenderer: ShapeRenderer, position: Vector2, isStep: Boolean) {
}
fun renderFeedforwardStepWithSynapses(shapeRenderer: ShapeRenderer, position: Vector2, isStep: Boolean) {
}
fun renderGrayNetwork(shapeRenderer: ShapeRenderer, position: Vector2) {
}
}
}
fun main(args: Array<String>) {
val inputs = createMatrix(
row(0f, 0f, 0f),
row(0f, 1f, 0f),
row(1f, 0f, 1f),
row(1f, 1f, 1f))
val targetOutputs = createMatrix(
row(0f, 1f, 0f),
row(1f, 0f, 1f),
row(1f, 1f, 1f),
row(0f, 0f, 0f))
val neuralNet = NeuralNetwork(3, 3, intArrayOf(20,10))
for (i in 1..300) neuralNet.backpropagate(inputs, targetOutputs, 0.1f, 0f)
//println("Input [0, 1] = " + neuralNet.feedforward(floatArrayOf(0f,1f))[0])
//println("Input [0, 0.5] = " + neuralNet.feedforward(floatArrayOf(0f,0.5f))[0])
} | agpl-3.0 | 27af99dae48bfac896ce6a93bbd0a2cf | 53.80786 | 189 | 0.66247 | 4.311233 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/inspections/AbstractResultUnusedChecker.kt | 4 | 2159 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
abstract class AbstractResultUnusedChecker(
private val expressionChecker: (KtExpression, AbstractResultUnusedChecker) -> Boolean,
private val callChecker: (ResolvedCall<*>, AbstractResultUnusedChecker) -> Boolean
) : AbstractKotlinInspection() {
protected fun check(expression: KtExpression): Boolean {
// Check whatever possible by PSI
if (!expressionChecker(expression, this)) return false
var current: PsiElement? = expression
var parent: PsiElement? = expression.parent
while (parent != null) {
if (parent is KtBlockExpression || parent is KtFunction || parent is KtFile) break
if (parent is KtValueArgument || parent is KtBinaryExpression || parent is KtUnaryExpression) return false
if (parent is KtQualifiedExpression && parent.receiverExpression == current) return false
// TODO: add when condition, if condition (later when it's applicable not only to Deferred)
current = parent
parent = parent.parent
}
// Then check by call
val context = expression.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL_WITH_CFA)
if (context == BindingContext.EMPTY || expression.isUsedAsExpression(context)) return false
val resolvedCall = expression.getResolvedCall(context) ?: return false
return callChecker(resolvedCall, this)
}
} | apache-2.0 | 405f5e2f1db245b566c5ad3c19ad860e | 55.842105 | 158 | 0.752663 | 5.165072 | false | false | false | false |
fvasco/pinpoi | app/src/main/java/io/github/fvasco/pinpoi/util/ProgressDialog.kt | 1 | 2198 | package io.github.fvasco.pinpoi.util
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.view.Gravity
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
class ProgressDialog(context: Context) : DialogInterface {
private val dialog: AlertDialog
private val progressBar = ProgressBar(context)
private val tvText = TextView(context)
init {
val llPadding = 20
val ll = LinearLayout(context)
ll.orientation = LinearLayout.HORIZONTAL
ll.setPadding(llPadding, llPadding, llPadding, llPadding)
ll.gravity = Gravity.CENTER
var llParam = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
llParam.gravity = Gravity.CENTER
ll.layoutParams = llParam
progressBar.isIndeterminate = true
progressBar.setPadding(0, 0, llPadding, 0)
progressBar.layoutParams = llParam
llParam = LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
llParam.gravity = Gravity.CENTER
tvText.layoutParams = llParam
ll.addView(progressBar)
ll.addView(tvText)
val builder = AlertDialog.Builder(context)
builder.setCancelable(false)
builder.setView(ll)
dialog = builder.create()
}
fun setTitle(title: CharSequence?) {
tvText.text = title
}
fun show() {
dialog.show()
val window = dialog.window
if (window != null) {
val layoutParams = WindowManager.LayoutParams()
layoutParams.copyFrom(window.attributes)
layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT
layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT
window.attributes = layoutParams
}
}
override fun dismiss() {
dialog.dismiss()
}
override fun cancel() {
dialog.cancel()
}
} | gpl-3.0 | 592ae31ec0d78d5cda515caa29e1c434 | 27.558442 | 72 | 0.66606 | 5.099768 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/formatter/SpacesAroundOperations.after.kt | 13 | 782 | class Some {
fun some() {
var int: Int = 0
int = 12
int += 12
int -= 12
int *= 12
int /= 12
int %= 12
true && true
true || false
12 === 3
12 !== 3
12 == 3
12 != 3
12 <= 3
12 >= 3
12 < 3
12 > 3
12 + 3 - 12
12 % 3 * 12 / 3
1 .. 2
null ?: 3 + 1
val a = 1
null ?: a + a
}
}
// SET_TRUE: SPACE_AROUND_ASSIGNMENT_OPERATORS
// SET_TRUE: SPACE_AROUND_LOGICAL_OPERATORS
// SET_TRUE: SPACE_AROUND_EQUALITY_OPERATORS
// SET_TRUE: SPACE_AROUND_RELATIONAL_OPERATORS
// SET_TRUE: SPACE_AROUND_ADDITIVE_OPERATORS
// SET_TRUE: SPACE_AROUND_MULTIPLICATIVE_OPERATORS
// SET_TRUE: SPACE_AROUND_RANGE | apache-2.0 | 87c5943966564282298d27d981dd27b0 | 16.795455 | 50 | 0.471867 | 3.72381 | false | false | false | false |
OnyxDevTools/onyx-database-parent | onyx-remote-driver/src/main/kotlin/com/onyx/exception/OnyxServerException.kt | 1 | 540 | package com.onyx.exception
import java.io.PrintWriter
import java.io.Serializable
import java.io.StringWriter
/**
* Created by Tim Osborn on 6/25/16.
*
* Base server exception
*/
abstract class OnyxServerException(override var message: String? = "", override final var cause:Throwable? = null) : OnyxException(message, cause), Serializable {
protected var stack:String = ""
init {
val sw = StringWriter()
val pw = PrintWriter(sw)
cause?.printStackTrace(pw)
this.stack = sw.toString()
}
}
| agpl-3.0 | fd7900380fae93730624f1425a1f2c30 | 23.545455 | 162 | 0.681481 | 4.090909 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/ast/NewClassExpression.kt | 2 | 1018 | // 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.j2k.ast
import org.jetbrains.kotlin.j2k.CodeBuilder
class NewClassExpression(
val name: ReferenceElement?,
val argumentList: ArgumentList,
val qualifier: Expression = Empty,
private val anonymousClass: AnonymousClassBody? = null
) : Expression() {
override fun generateCode(builder: CodeBuilder) {
if (anonymousClass != null) {
builder.append("object:")
}
if (!qualifier.isEmpty) {
builder.append(qualifier).append(if (qualifier.isNullable) "!!." else ".")
}
if (name != null) {
builder.append(name)
}
if (anonymousClass == null || !anonymousClass.extendsInterface) {
builder.append(argumentList)
}
if (anonymousClass != null) {
builder.append(anonymousClass)
}
}
}
| apache-2.0 | af626e7ad8543b0b2965e349a9d37d8a | 28.085714 | 158 | 0.636542 | 4.426087 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/compiler-plugins/annotation-based-compiler-support/gradle/src/org/jetbrains/kotlin/idea/gradleJava/compilerPlugin/annotationBased/AnnotationBasedPluginProjectResolverExtension.kt | 1 | 1892 | // 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.gradleJava.compilerPlugin.annotationBased
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.project.ModuleData
import com.intellij.openapi.util.Key
import org.gradle.tooling.model.idea.IdeaModule
import org.jetbrains.kotlin.idea.gradleTooling.model.annotation.AnnotationBasedPluginModel
import org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension
@Suppress("unused")
abstract class AnnotationBasedPluginProjectResolverExtension<T : AnnotationBasedPluginModel> : AbstractProjectResolverExtension() {
private companion object {
private val LOG = Logger.getInstance(AnnotationBasedPluginProjectResolverExtension::class.java)
}
abstract val modelClass: Class<T>
abstract val userDataKey: Key<T>
override fun getExtraProjectModelClasses() = setOf(modelClass, AnnotationBasedPluginModel::class.java)
override fun getToolingExtensionsClasses() = setOf(
modelClass,
AnnotationBasedPluginProjectResolverExtension::class.java,
Unit::class.java)
override fun populateModuleExtraModels(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) {
val model = resolverCtx.getExtraProject(gradleModule, modelClass)
if (model != null) {
val (className, args) = model.dump()
@Suppress("UNCHECKED_CAST")
val refurbishedModel = Class.forName(className).constructors.single().newInstance(*args) as T
ideModule.putCopyableUserData(userDataKey, refurbishedModel)
}
super.populateModuleExtraModels(gradleModule, ideModule)
}
} | apache-2.0 | 38a55d867b3f0d62b991e5e91aef4d5f | 43.023256 | 158 | 0.766913 | 5.127371 | false | false | false | false |
zielu/GitToolBox | src/main/kotlin/zielu/gittoolbox/metrics/Jmx.kt | 1 | 1866 | package zielu.gittoolbox.metrics
import com.codahale.metrics.MetricRegistry
import com.codahale.metrics.jmx.JmxReporter
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import java.security.Permission
import javax.management.MBeanTrustPermission
internal object Jmx {
private const val DOMAIN = "zielu.gittoolbox"
private val log = Logger.getInstance(Jmx::class.java)
@JvmStatic
fun startReporting(registry: MetricRegistry): MetricsReporter {
return if (shouldExport()) {
val reporter = JmxReporter.forRegistry(registry).inDomain(DOMAIN).build()
reporter.start()
log.info("App metrics JMX reporter started")
JmxMetricsReporter(reporter)
} else {
MetricsReporter.EMPTY
}
}
@JvmStatic
fun startReporting(project: Project, registry: MetricRegistry): MetricsReporter {
return if (shouldExport()) {
val projectName = project.name.replace("\\W".toRegex(), "")
val reporter = JmxReporter.forRegistry(registry).inDomain("$DOMAIN.$projectName").build()
reporter.start()
log.info("Project $projectName metrics JMX reporter started")
JmxMetricsReporter(reporter)
} else {
MetricsReporter.EMPTY
}
}
private fun shouldExport(): Boolean {
return System.getSecurityManager()?.let { securityManager ->
val permission: Permission = MBeanTrustPermission("register")
return try {
securityManager.checkPermission(permission)
true
} catch (e: SecurityException) {
log.warn("Cannot export JMX metrics", e)
false
}
} ?: true
}
}
private class JmxMetricsReporter(private val reporter: JmxReporter) : MetricsReporter {
private val log = Logger.getInstance(JmxMetricsReporter::class.java)
override fun dispose() {
reporter.close()
log.info("Disposed")
}
}
| apache-2.0 | 283f182bf7cceac86b3b3684060d58d3 | 30.1 | 95 | 0.712219 | 4.529126 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/inspections/UnclearPrecedenceOfBinaryExpressionInspectionTest.kt | 4 | 4679 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import junit.framework.TestCase
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
class UnclearPrecedenceOfBinaryExpressionInspectionTest : KotlinLightCodeInsightFixtureTestCase() {
fun `test elvis elvis`() = doTest("fun foo(i: Int?, j: Int?, k: Int?) = i ?: j <caret>?: k")
fun `test elvis as`() = doTest(
"fun foo(i: Int?, j: Int?) = i ?: j<caret> as String?",
"fun foo(i: Int?, j: Int?) = i ?: (j as String?)"
)
fun `test elvis eqeq`() = doTest(
"fun foo(a: Int?, b: Int?, c: Int?) = <warning>a ?: b<caret> == c</warning>",
"fun foo(a: Int?, b: Int?, c: Int?) = (a ?: b) == c"
)
fun `test comments`() = doTest(
"fun test(i: Int?, b: Boolean?) = <warning>b /* a */ <caret>?: /* b */ i /* c */ == /* d */ null</warning>",
"fun test(i: Int?, b: Boolean?) = (b /* a */ ?: /* b */ i) /* c */ == /* d */ null"
)
fun `test quickfix is absent for same priority tokens`() = doTest("fun foo() = 1 + 2 <caret>+ 3")
fun `test put parentheses through already presented parentheses`() = doTest(
"fun foo(a: Int?) = a ?<caret>: (1 + 2 * 4)",
"fun foo(a: Int?) = a ?: (1 + (2 * 4))"
)
fun `test obvious arithmetic is reported with reportEvenObviousCases flag is on`() = doTest(
"fun foo() = <warning>1 + 2<caret> * 4</warning>",
"fun foo() = 1 + (2 * 4)",
reportEvenObviousCases = true
)
fun `test parentheses should be everywhere if reportEvenObviousCases flag is on`() = doTest(
"fun foo(a: Int?) = <warning>a ?: 1 + <caret>2 * 4</warning>",
"fun foo(a: Int?) = a ?: (1 + (2 * 4))",
reportEvenObviousCases = true
)
fun `test only non obvious parentheses should be put if reportEvenObviousCases flag is off`() = doTest(
"fun foo(a: Int?) = <warning>a ?: 1 + <caret>2 * 4</warning>",
"fun foo(a: Int?) = a ?: (1 + 2 * 4)"
)
fun `test elvis is`() = doTest(
"fun foo(a: Boolean?, b: Any) = <warning>a ?: <caret>b is Int</warning>",
"fun foo(a: Boolean?, b: Any) = (a ?: b) is Int"
)
fun `test elvis plus`() = doTest(
"fun foo(a: Int?) = <warning>a ?: <caret>1 + 2</warning>",
"fun foo(a: Int?) = a ?: (1 + 2)"
)
fun `test top level presented parentheses`() = doTest(
"fun foo() = <warning>(if (true) 1 else null) ?: <caret>1 xor 2</warning>",
"fun foo() = (if (true) 1 else null) ?: (1 xor 2)"
)
fun `test eq elvis`() = doTest("fun test(i: Int?): Int { val y: Int; y = i <caret>?: 1; return y}")
fun `test already has parentheses`() = doTest("fun foo(i: Int?) = (i <caret>?: 0) + 1")
fun `test infixFun plus`() = doTest(
"fun foo() = 1 xor 2 <caret>+ 8",
"fun foo() = 1 xor (2 + 8)"
)
fun `test plus range`() = doTest(
"fun foo() = 1 + <caret>2..4",
"fun foo() = (1 + 2)..4"
)
fun `test braces inside braces`() = doTest(
"fun foo() = ((1 + <caret>2))..4"
)
fun `test infixFun elvis`() = doTest(
"fun foo(a: Int?) = <warning>a ?: 1 <caret>xor 2</warning>",
"fun foo(a: Int?) = a ?: (1 xor 2)"
)
fun `test multiple infixFun`() = doTest(
"fun foo() = 0 xor 10<caret> and 2"
)
private fun doTest(before: String, after: String? = null, reportEvenObviousCases: Boolean = false) {
require(before.contains("<caret>"))
val unclearPrecedenceOfBinaryExpressionInspection = UnclearPrecedenceOfBinaryExpressionInspection()
unclearPrecedenceOfBinaryExpressionInspection.reportEvenObviousCases = reportEvenObviousCases
myFixture.enableInspections(unclearPrecedenceOfBinaryExpressionInspection)
try {
myFixture.configureByText("foo.kt", before)
myFixture.checkHighlighting(true, false, false)
val intentionMsg = KotlinBundle.message("unclear.precedence.of.binary.expression.quickfix")
if (after != null) {
val intentionAction = myFixture.findSingleIntention(intentionMsg)
myFixture.launchAction(intentionAction)
myFixture.checkResult(after)
} else {
TestCase.assertTrue(myFixture.filterAvailableIntentions(intentionMsg).isEmpty())
}
} finally {
myFixture.disableInspections(unclearPrecedenceOfBinaryExpressionInspection)
}
}
}
| apache-2.0 | 0985bc1d285212d4b3ec447cd4e12fca | 40.40708 | 158 | 0.578542 | 3.841544 | false | true | false | false |
sargunster/CakeParse | src/main/kotlin/me/sargunvohra/lib/cakeparse/lexer/Lexer.kt | 1 | 2954 | package me.sargunvohra.lib.cakeparse.lexer
import me.sargunvohra.lib.cakeparse.exception.LexerException
import java.io.InputStream
import java.io.InputStreamReader
import java.io.StringReader
import java.util.*
/**
* Defines a lexer over a set of token definitions. A single lexer can be used to lex multiple inputs.
*
* @param tokens the set of tokens that this lexer looks for in the input. The set must not be empty.
*/
class Lexer(tokens: Set<Token>) {
private val patterns = tokens.filter { it.pattern != null }.associate {
it to it.pattern!!.toRegex().toPattern()
}
init {
require(patterns.isNotEmpty()) { "Must provide at least one token with a pattern" }
}
/**
* Read a string and produce a stream of tokens.
*
* @param input the string to read from.
*
* @return a sequence of tokens. This sequence can only be iterated once.
*/
fun lex(input: String) = lex(StringReader(input))
/**
* Read an input stream and produce a stream of tokens.
*
* @param input the input stream to read from.
*
* @return a sequence of tokens. This sequence can only be iterated once.
*/
fun lex(input: InputStream) = lex(InputStreamReader(input))
/**
* Read any reader and produce a stream of tokens.
*
* @param input the readable object to read from.
*
* @return a sequence of tokens. This sequence can only be iterated once.
*/
fun lex(input: Readable) = object : Sequence<TokenInstance> {
override fun iterator(): Iterator<TokenInstance> {
return object : Iterator<TokenInstance> {
private val scanner = Scanner(input).useDelimiter("")
private var currentPos = 0
private var currentRow = 1
private var currentCol = 1
override fun hasNext() = scanner.hasNext()
override fun next(): TokenInstance {
for ((type, pattern) in patterns) {
try {
scanner.skip(pattern)
} catch (e: NoSuchElementException) {
continue
}
val match = scanner.match().group()
val result = TokenInstance(type, match, currentPos, currentRow, currentCol)
currentPos += match.length
currentRow += match.count { it == '\n' }
currentCol += match.length
val lastIndex = match.lastIndexOf('\n')
if (lastIndex >= 0)
currentCol = match.length - lastIndex
return result
}
throw LexerException(currentPos, currentRow, currentCol, scanner.next(".")[0])
}
}
}
}.constrainOnce()
} | apache-2.0 | 5b8b2519be70561b2a39384dc69ef1c6 | 32.202247 | 102 | 0.557888 | 5.1019 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/data/migration/migrations/ReplaceActionsWithScriptsMigration.kt | 1 | 2588 | package ch.rmy.android.http_shortcuts.data.migration.migrations
import com.google.gson.JsonObject
import io.realm.DynamicRealm
import io.realm.FieldAttribute
import org.json.JSONArray
class ReplaceActionsWithScriptsMigration : BaseMigration {
override val version: Int
get() = 27
override fun migrateRealm(realm: DynamicRealm) {
val schema = realm.schema
schema.get("Shortcut")!!
.addField("codeOnPrepare", String::class.java, FieldAttribute.REQUIRED)
.addField("codeOnSuccess", String::class.java, FieldAttribute.REQUIRED)
.addField("codeOnFailure", String::class.java, FieldAttribute.REQUIRED)
realm.where("Shortcut")
.findAll()
.forEach { shortcut ->
shortcut.setString("codeOnPrepare", jsonActionListToJsCode(shortcut.getString("serializedBeforeActions")))
shortcut.setString("codeOnSuccess", jsonActionListToJsCode(shortcut.getString("serializedSuccessActions")))
shortcut.setString("codeOnFailure", jsonActionListToJsCode(shortcut.getString("serializedFailureActions")))
}
schema.get("Shortcut")!!
.removeField("serializedBeforeActions")
.removeField("serializedSuccessActions")
.removeField("serializedFailureActions")
}
private fun jsonActionListToJsCode(jsonList: String?): String {
val codeBuilder = StringBuilder()
val array = JSONArray(jsonList ?: "[]")
for (i in 0 until array.length()) {
val action = array.getJSONObject(i)
codeBuilder.append("_runAction(\"")
codeBuilder.append(action.getString("type"))
codeBuilder.append("\", ")
codeBuilder.append(action.getJSONObject("data").toString())
codeBuilder.append("); /* built-in */\n")
}
return codeBuilder.toString()
}
override fun migrateImport(base: JsonObject) {
for (category in base["categories"].asJsonArray) {
for (shortcutObj in category.asJsonObject["shortcuts"].asJsonArray) {
val shortcut = shortcutObj.asJsonObject
shortcut.addProperty("codeOnPrepare", jsonActionListToJsCode(shortcut.get("serializedBeforeActions")?.asString))
shortcut.addProperty("codeOnSuccess", jsonActionListToJsCode(shortcut.get("serializedSuccessActions")?.asString))
shortcut.addProperty("codeOnFailure", jsonActionListToJsCode(shortcut.get("serializedFailureActions")?.asString))
}
}
}
}
| mit | 341f109b367ed376f1258c0147a65a46 | 42.864407 | 129 | 0.662287 | 5.303279 | false | false | false | false |
7449/Album | wechat/src/main/java/com/gallery/ui/wechat/widget/WeChatGalleryItem.kt | 1 | 2089 | package com.gallery.ui.wechat.widget
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import com.gallery.core.entity.ScanEntity
import com.gallery.ui.wechat.R
import com.gallery.ui.wechat.databinding.WechatGalleryLayoutItemBinding
import com.gallery.ui.wechat.extension.colorExpand
import com.gallery.ui.wechat.extension.formatTimeVideo
class WeChatGalleryItem @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
private val viewBinding: WechatGalleryLayoutItemBinding =
WechatGalleryLayoutItemBinding.inflate(LayoutInflater.from(getContext()), this, true)
val imageView: ImageView
get() = viewBinding.viewWeChatImageView
private val gifView: View
get() = viewBinding.viewWeChatGif
private val videoView: TextView
get() = viewBinding.viewWeChatVideo
private val bottomView: View
get() = viewBinding.viewWeChatBottomView
private val selectView: View
get() = viewBinding.viewWeChatBackSelect
fun update(scanEntity: ScanEntity) {
selectView.visibility = if (scanEntity.isSelected) VISIBLE else GONE
gifView.visibility = if (scanEntity.isGif) VISIBLE else GONE
videoView.visibility = if (scanEntity.isVideo) VISIBLE else GONE
bottomView.visibility = if (scanEntity.isVideo) VISIBLE else GONE
bottomView.setBackgroundColor(
if (scanEntity.isGif) Color.TRANSPARENT else context.colorExpand(
R.color.wechat_gallery_color_B3000000
)
)
bottomView.visibility = if (scanEntity.isVideo || scanEntity.isGif) VISIBLE else GONE
videoView.text = if (scanEntity.isVideo) scanEntity.duration.formatTimeVideo() else ""
}
} | mpl-2.0 | b53e368f5649aec0b5cb479057fc7d32 | 36.018182 | 97 | 0.714217 | 4.78032 | false | false | false | false |
busybusy/AnalyticsKit-Android | analyticskit/src/test/kotlin/com/busybusy/analyticskit_android/AnalyticsEventTest.kt | 2 | 1958 | /*
* Copyright 2016 - 2022 busybusy, 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.busybusy.analyticskit_android
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
/**
* Tests the [AnalyticsEvent] class.
*
* @author John Hunt on 3/5/16.
*/
class AnalyticsEventTest {
@Test
fun testBuilder_withAttributes() {
val name = "Yeah, this should work"
val animalText = "The quick brown fox jumps over the lazy dog"
val event = AnalyticsEvent(name)
.putAttribute("the answer", 42)
.putAttribute("animal text", animalText)
assertThat(event.name()).isEqualTo(name)
assertThat(event.attributes).isNotNull
assertThat(event.attributes!!.keys).containsOnly("the answer", "animal text")
assertThat(event.attributes!!.values).containsOnly(42, animalText)
}
@Test
fun testBuilder_noAttributes() {
val name = "Yeah, this should work"
val event = AnalyticsEvent(name)
assertThat(event.name()).isEqualTo(name)
assertThat(event.attributes).isNull()
}
@Test
fun testBuilder_specifyPriority() {
val name = "Priority 7 event"
val event = AnalyticsEvent(name)
.setPriority(7)
assertThat(event.name()).isEqualTo(name)
assertThat(event.attributes).isNull()
assertThat(event.priority).isEqualTo(7)
}
}
| apache-2.0 | 81cab4d3d1b49cd0a84c733d9e0e2c48 | 33.350877 | 85 | 0.669561 | 4.247289 | false | true | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/framework/src/main/kotlin/ch/rmy/android/framework/ui/views/LabelledSpinner.kt | 1 | 2764 | package ch.rmy.android.framework.ui.views
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.core.content.res.use
import ch.rmy.android.framework.databinding.LabelledSpinnerBinding
import ch.rmy.android.framework.extensions.indexOfFirstOrNull
import ch.rmy.android.framework.extensions.layoutInflater
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.filterNotNull
class LabelledSpinner @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
) :
LinearLayoutCompat(context, attrs, defStyleAttr) {
private val binding = LabelledSpinnerBinding.inflate(layoutInflater, this)
private val _selectionChanges = MutableStateFlow<String?>(null)
val selectionChanges: Flow<String> = _selectionChanges.asStateFlow().filterNotNull()
var items: List<Item> = emptyList()
set(value) {
field = value
binding.spinner.adapter = ArrayAdapter(context, android.R.layout.simple_spinner_dropdown_item, value.map { it.value ?: it.key })
}
fun setItemsFromPairs(items: List<Pair<String, String>>) {
this.items = items.map { (key, value) -> Item(key, value) }
}
fun setItemsFromPairs(vararg items: Pair<String, String>) {
setItemsFromPairs(items.asList())
}
init {
orientation = VERTICAL
binding.spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(p0: AdapterView<*>?, p1: View?, position: Int, id: Long) {
selectedItem = items[position].key
}
override fun onNothingSelected(p0: AdapterView<*>?) {
}
}
if (attrs != null) {
context.obtainStyledAttributes(attrs, ATTRIBUTE_IDS).use { a ->
binding.label.text = a.getText(ATTRIBUTE_IDS.indexOf(android.R.attr.text)) ?: ""
}
}
}
var selectedItem: String = ""
set(value) {
val index = items
.indexOfFirstOrNull { it.key == value }
?: return
val before = field
field = value
binding.spinner.setSelection(index)
if (before != value && before.isNotEmpty()) {
_selectionChanges.value = value
}
}
data class Item(val key: String, val value: String? = null)
companion object {
private val ATTRIBUTE_IDS = intArrayOf(android.R.attr.text)
}
}
| mit | 5fa2956e60262bcde39b54a87fd0ac6e | 32.707317 | 140 | 0.661722 | 4.606667 | false | false | false | false |
googlearchive/android-InteractiveSliceProvider | app/src/main/java/com/example/android/interactivesliceprovider/MainActivity.kt | 1 | 5331 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.interactivesliceprovider
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.preference.PreferenceManager
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.edit
import androidx.core.net.toUri
import androidx.slice.SliceManager
import com.google.firebase.appindexing.FirebaseAppIndex
import java.net.URLDecoder
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Grants permission to all non-default slices.
// IMPORTANT NOTE: This will not be needed when the API is launched publicly. It is only
// required at the current time for the EAP.
grantNonDefaultSlicePermission()
val defaultUriEncoded = getResources().getString(R.string.default_slice_uri)
// Decode for special characters that may appear in URI. Review Android documentation on
// special characters for more information:
// https://developer.android.com/guide/topics/resources/string-resource#FormattingAndStyling
val defaultUriDecoded = URLDecoder.decode(defaultUriEncoded, "UTF-8")
// Grants permission for default slice.
grantSlicePermissions(defaultUriDecoded.toUri())
setContentView(R.layout.activity_main)
}
private fun grantSlicePermissions(uri: Uri, notifyIndexOfChange: Boolean = true) {
// Grant permissions to AGSA
SliceManager.getInstance(this).grantSlicePermission(
"com.google.android.googlequicksearchbox",
uri
)
// grant permission to GmsCore
SliceManager.getInstance(this).grantSlicePermission(
"com.google.android.gms",
uri
)
if (notifyIndexOfChange) {
// Notify change. Ensure that it does not happen on every onCreate()
// calls as notify change triggers reindexing which can clear usage
// signals of your app and hence impact your app’s ranking. One way to
// do this is to use shared preferences.
val sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(applicationContext)
if (!sharedPreferences.getBoolean(PREF_GRANT_SLICE_PERMISSION, false)) {
contentResolver.notifyChange(uri, null /* content observer */)
sharedPreferences.edit {
putBoolean(PREF_GRANT_SLICE_PERMISSION, true)
}
}
}
}
/*
* Grants permissions for non-default URLs, so they can be shown in google search on device.
* IMPORTANT NOTE: As stated earlier, this will not be required soon (and not for launch), so
* you can assume you won't need to loop through all your non-default slice URIs for the launch.
*/
private fun grantNonDefaultSlicePermission () {
val nonDefaultUris = listOf(
applicationContext.resources.getString(R.string.wifi_slice_uri),
applicationContext.resources.getString(R.string.note_slice_uri),
applicationContext.resources.getString(R.string.ride_slice_uri),
applicationContext.resources.getString(R.string.toggle_slice_uri),
applicationContext.resources.getString(R.string.gallery_slice_uri),
applicationContext.resources.getString(R.string.weather_slice_uri),
applicationContext.resources.getString(R.string.reservation_slice_uri),
applicationContext.resources.getString(R.string.list_slice_uri),
applicationContext.resources.getString(R.string.grid_slice_uri),
applicationContext.resources.getString(R.string.input_slice_uri),
applicationContext.resources.getString(R.string.range_slice_uri)
)
for(nonDefaultUri in nonDefaultUris) {
grantSlicePermissions(
Uri.parse(nonDefaultUri),
false
)
}
}
fun onClickIndexSlices (view: View) {
val intent = Intent(this, AppIndexingUpdateReceiver::class.java)
intent.action = FirebaseAppIndex.ACTION_UPDATE_INDEX
sendBroadcast(intent)
}
companion object {
private const val PREF_GRANT_SLICE_PERMISSION = "permission_slice_status"
fun getPendingIntent(context: Context): PendingIntent {
val intent = Intent(context, MainActivity::class.java)
return PendingIntent.getActivity(context, 0, intent, 0)
}
}
} | apache-2.0 | 05ea46eb9cad473533fa7173457d9e68 | 40 | 100 | 0.682867 | 4.875572 | false | false | false | false |
bmaslakov/kotlin-algorithm-club | src/test/io/uuddlrlrba/ktalgs/datastructures/StackTest.kt | 1 | 2486 | /*
* Copyright (c) 2017 Kotlin Algorithm Club
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.uuddlrlrba.ktalgs.datastructures
import org.junit.Assert
import org.junit.Test
import java.util.*
class StackTest {
@Test
fun emptyTest() {
val stack = Stack<Int>()
Assert.assertEquals(0, stack.size)
Assert.assertTrue(stack.isEmpty())
}
@Test(expected=NoSuchElementException::class)
fun exceptionTest() {
val stack = Stack<Int>()
stack.peek()
}
@Test
fun naiveTest() {
val stack = Stack<Int>()
for (i in 0..10) {
stack.push(i)
}
for (i in 10 downTo 0) {
Assert.assertEquals(i, stack.peek())
Assert.assertEquals(i, stack.poll())
}
Assert.assertEquals(0, stack.size)
}
@Test
fun naiveIteratorTest() {
val stack = Stack<Int>()
for (i in 0..10) {
stack.push(i)
}
var k = 10
for (i in stack) {
Assert.assertEquals(i, k--)
}
}
@Test
fun naiveContainsTest() {
val stack = Stack<Int>()
for (i in 0..10) {
stack.push(i)
}
for (i in 0..10) {
Assert.assertTrue(stack.contains(i))
}
Assert.assertFalse(stack.contains(100))
Assert.assertFalse(stack.contains(101))
Assert.assertFalse(stack.contains(103))
}
}
| mit | f5933b55b937cabcb6b49ed1a185b737 | 28.595238 | 81 | 0.633548 | 4.192243 | false | true | false | false |
JetBrains/teamcity-azure-plugin | plugin-azure-server/src/main/kotlin/jetbrains/buildServer/clouds/azure/arm/throttler/AzureThrottlerConfigurableImpl.kt | 1 | 4448 | /*
* Copyright 2000-2021 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.clouds.azure.arm.throttler
import com.intellij.openapi.diagnostic.Logger
import com.microsoft.azure.credentials.ApplicationTokenCredentials
import com.microsoft.azure.credentials.AzureTokenCredentials
import com.microsoft.azure.management.Azure
import com.microsoft.azure.management.resources.fluentcore.arm.implementation.AzureConfigurableImpl
import jetbrains.buildServer.clouds.azure.arm.connector.AzureApiConnectorImpl
import jetbrains.buildServer.clouds.azure.arm.connector.CredentialsAuthenticator
import jetbrains.buildServer.serverSide.TeamCityProperties
import okhttp3.Interceptor
import java.io.File
import java.io.IOException
import java.net.InetSocketAddress
import java.net.Proxy
class AzureThrottlerConfigurableImpl : AzureConfigurableImpl<Azure.Configurable>(), AzureConfigurableWithNetworkInterceptors {
override fun withNetworkInterceptor(interceptor: Interceptor): AzureConfigurableWithNetworkInterceptors {
restClientBuilder.withNetworkInterceptor(interceptor)
return this
}
override fun authenticate(credentials: AzureTokenCredentials): Azure.Authenticated {
return if (credentials.defaultSubscriptionId() != null) Azure.authenticate(this.buildRestClient(credentials), credentials.domain(), credentials.defaultSubscriptionId()) else Azure.authenticate(this.buildRestClient(credentials), credentials.domain())
}
@Throws(IOException::class)
override fun authenticate(credentialsFile: File): Azure.Authenticated {
val credentials = ApplicationTokenCredentials.fromFile(credentialsFile)
return Azure.authenticate(this.buildRestClient(credentials), credentials.domain(), credentials.defaultSubscriptionId())
}
/**
* Configures http proxy settings.
*/
override fun configureProxy(): AzureConfigurableWithNetworkInterceptors {
val builder = StringBuilder()
// Set HTTP proxy
val httpProxyHost = TeamCityProperties.getProperty(HTTP_PROXY_HOST)
val httpProxyPort = TeamCityProperties.getInteger(HTTP_PROXY_PORT, 80)
if (httpProxyHost.isNotBlank()) {
this.withProxy(Proxy(Proxy.Type.HTTP, InetSocketAddress(httpProxyHost, httpProxyPort)))
builder.append("$httpProxyHost:$httpProxyPort")
}
// Set HTTPS proxy
val httpsProxyHost = TeamCityProperties.getProperty(HTTPS_PROXY_HOST)
val httpsProxyPort = TeamCityProperties.getInteger(HTTPS_PROXY_PORT, 443)
if (httpsProxyHost.isNotBlank()) {
this.withProxy(Proxy(Proxy.Type.HTTP, InetSocketAddress(httpsProxyHost, httpsProxyPort)))
builder.setLength(0)
builder.append("$httpsProxyHost:$httpsProxyPort")
}
// Set proxy authentication
val httpProxyUser = TeamCityProperties.getProperty(HTTP_PROXY_USER)
val httpProxyPassword = TeamCityProperties.getProperty(HTTP_PROXY_PASSWORD)
if (httpProxyUser.isNotBlank() && httpProxyPassword.isNotBlank()) {
val authenticator = CredentialsAuthenticator(httpProxyUser, httpProxyPassword)
this.withProxyAuthenticator(authenticator)
builder.insert(0, "$httpProxyUser@")
}
if (builder.isNotEmpty()) {
LOG.debug("Using proxy server $builder for connection")
}
return this
}
companion object {
private val LOG = Logger.getInstance(AzureApiConnectorImpl::class.java.name)
private const val HTTP_PROXY_HOST = "http.proxyHost"
private const val HTTP_PROXY_PORT = "http.proxyPort"
private const val HTTPS_PROXY_HOST = "https.proxyHost"
private const val HTTPS_PROXY_PORT = "https.proxyPort"
private const val HTTP_PROXY_USER = "http.proxyUser"
private const val HTTP_PROXY_PASSWORD = "http.proxyPassword"
}
}
| apache-2.0 | f798d29ca3ff6b1195e253b3e96189a4 | 44.85567 | 257 | 0.743031 | 4.829533 | false | true | false | false |
grote/BlitzMail | src/de/grobox/blitzmail/send/SenderService.kt | 1 | 2983 | package de.grobox.blitzmail.send
import android.app.IntentService
import android.content.Intent
import android.net.ConnectivityManager
import android.os.Handler
import android.widget.Toast
import android.widget.Toast.LENGTH_LONG
import de.grobox.blitzmail.BuildConfig
import de.grobox.blitzmail.MailStorage
import de.grobox.blitzmail.R
import de.grobox.blitzmail.notification.MailNotificationManager
import de.grobox.blitzmail.notification.NOTIFICATION_ID_SENDING
import de.grobox.blitzmail.notification.getMailNotificationManager
import de.grobox.blitzmail.preferences.getProperties
import org.json.JSONObject
const val MAIL = "mail"
const val MAIL_ID = "id"
const val MAIL_BODY = "body"
const val MAIL_SUBJECT = "subject"
const val MAIL_CC = "cc"
const val MAIL_DATE = "date"
const val MAIL_ATTACHMENTS = "attachments"
class SenderService : IntentService("SenderService") {
private lateinit var mailNotificationManager: MailNotificationManager
private lateinit var connectivityManager: ConnectivityManager
override fun onCreate() {
super.onCreate()
mailNotificationManager = getMailNotificationManager(applicationContext)
connectivityManager = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
}
override fun onHandleIntent(intent: Intent?) {
if (intent == null) return
mailNotificationManager.createNotificationChannel();
startForeground(NOTIFICATION_ID_SENDING, mailNotificationManager.getForegroundNotification());
intent.getStringExtra(MAIL)?.let {
// save mail before sending all saved mails
MailStorage.saveMail(this, JSONObject(it))
}
// send all saved mails
val mails = MailStorage.getMails(this)
mails.keys().forEach {
val mail = mails.getJSONObject(it);
sendMail(mail)
}
}
override fun onDestroy() {
super.onDestroy()
stopForeground(true)
}
private fun sendMail(mail: JSONObject) {
val mailId = mail.getInt(MAIL_ID)
val subject = mail.getString(MAIL_SUBJECT)
try {
MailSender(getProperties(applicationContext), mail).sendMail()
mailNotificationManager.showSuccessNotification(mailId, subject)
// Everything went fine, so delete mail from local storage
MailStorage.deleteMail(applicationContext, mailId.toString())
} catch (e: Exception) {
e.printStackTrace()
val networkInfo = connectivityManager.activeNetworkInfo
if (BuildConfig.PRO && (networkInfo == null || !networkInfo.isConnected)) {
scheduleSending(0)
Handler(mainLooper).post {
Toast.makeText(applicationContext, getString(R.string.mail_queued), LENGTH_LONG).show()
}
} else {
mailNotificationManager.showErrorNotification(e, mailId.toString())
}
}
}
}
| agpl-3.0 | 3083d5362c8418d91d796770590c7e77 | 33.686047 | 107 | 0.693597 | 5.021886 | false | false | false | false |
osfans/trime | app/src/main/java/com/osfans/trime/ui/components/FolderPickerPreference.kt | 1 | 2823 | package com.osfans.trime.ui.components
import android.content.Context
import android.content.res.TypedArray
import android.net.Uri
import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.activity.result.ActivityResultLauncher
import androidx.appcompat.app.AlertDialog
import androidx.core.net.toUri
import androidx.preference.Preference
import com.osfans.trime.R
import com.osfans.trime.databinding.FolderPickerDialogBinding
import com.osfans.trime.util.UriUtils.toUri
import java.io.File
class FolderPickerPreference : Preference {
private var value = ""
lateinit var documentTreeLauncher: ActivityResultLauncher<Uri?>
lateinit var dialogView: FolderPickerDialogBinding
@Suppress("unused")
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) :
this(context, attrs, androidx.preference.R.attr.preferenceStyle)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
context.theme.obtainStyledAttributes(attrs, R.styleable.FolderPickerPreferenceAttrs, 0, 0).run {
try {
if (getBoolean(R.styleable.FolderPickerPreferenceAttrs_useSimpleSummaryProvider, false)) {
summaryProvider = SummaryProvider<FolderPickerPreference> { it.currentValue }
}
} finally {
recycle()
}
}
}
private val currentValue: String
get() = getPersistedString(value)
override fun onGetDefaultValue(a: TypedArray, index: Int): Any {
return a.getString(index) ?: ""
}
override fun onSetInitialValue(defaultValue: Any?) {
value = defaultValue as? String ?: getPersistedString("")
}
override fun onClick() = showPickerDialog()
private fun showPickerDialog() {
val initValue = currentValue
dialogView = FolderPickerDialogBinding.inflate(LayoutInflater.from(context))
dialogView.editText.setText(initValue)
dialogView.button.setOnClickListener {
documentTreeLauncher.launch(File(initValue).toUri())
}
AlertDialog.Builder(context)
.setTitle([email protected])
.setView(dialogView.root)
.setPositiveButton(android.R.string.ok) { _, _ ->
val value = dialogView.editText.text.toString()
if (callChangeListener(value)) {
persistString(value)
notifyChanged()
}
}
.setNeutralButton(R.string.pref__default) { _, _ ->
persistString(value)
notifyChanged()
}
.setNegativeButton(android.R.string.cancel, null)
.show()
}
}
| gpl-3.0 | 20c92643c46d182e26a1b45f0d18c4a2 | 36.64 | 114 | 0.664896 | 5.01421 | false | false | false | false |
kaltura/playkit-android | playkit/src/main/java/com/kaltura/playkit/ads/AdvertisingContainer.kt | 1 | 14753 | package com.kaltura.playkit.ads
import androidx.annotation.Nullable
import com.google.gson.Gson
import com.kaltura.playkit.PKLog
import com.kaltura.playkit.utils.Consts
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
/**
* Class to map the Advertising object to our internal helper DataStructure
*/
internal class AdvertisingContainer {
private val log = PKLog.get(AdvertisingContainer::class.java.simpleName)
private var adsConfigMap: MutableMap<Long, AdBreakConfig?>? = null
private var cuePointsList: LinkedList<Long>? = null
private var midrollAdPositionType: AdBreakPositionType = AdBreakPositionType.POSITION
private var midrollFrequency = Long.MIN_VALUE
private var playAdsAfterTime = Long.MIN_VALUE
private var adType: AdType = AdType.AD_URL
private var returnToLive: Boolean = false
internal fun setAdvertisingConfig(advertisingConfig: AdvertisingConfig?) {
advertisingConfig?.let {
parseAdTypes(it)
}
}
/**
* Parse the Ads from the external Ads' data structure
*/
private fun parseAdTypes(advertisingConfig: AdvertisingConfig?) {
log.d("parseAdTypes")
advertisingConfig?.advertising?.let { adBreaks ->
val adBreaksList = ArrayList<AdBreakConfig>()
cuePointsList = LinkedList()
playAdsAfterTime = if (advertisingConfig.adTimeUnit == AdTimeUnit.SECONDS && (advertisingConfig.playAdsAfterTime != -1L || advertisingConfig.playAdsAfterTime > 0)) {
advertisingConfig.playAdsAfterTime * Consts.MILLISECONDS_MULTIPLIER
} else {
advertisingConfig.playAdsAfterTime
}
advertisingConfig.adType.let {
adType = it
}
returnToLive = advertisingConfig.returnToLive
for (adBreak: AdBreak? in adBreaks) {
adBreak?.let adBreakLoop@{ singleAdBreak ->
// Only one ad can be configured for Every AdBreakPositionType
if ((singleAdBreak.position == 0L || singleAdBreak.position == -1L) &&
(singleAdBreak.adBreakPositionType == AdBreakPositionType.EVERY)) {
log.w("Preroll or Postroll ad should not be configured with AdBreakPositionType.EVERY\n" +
"Dropping such AdBreak")
return@adBreakLoop
}
if (midrollAdPositionType == AdBreakPositionType.POSITION && adBreak.adBreakPositionType == AdBreakPositionType.EVERY) {
midrollAdPositionType = AdBreakPositionType.EVERY
midrollFrequency = if (advertisingConfig.adTimeUnit == AdTimeUnit.SECONDS) singleAdBreak.position * Consts.MILLISECONDS_MULTIPLIER else singleAdBreak.position
} else if (midrollAdPositionType == AdBreakPositionType.EVERY && adBreak.adBreakPositionType == AdBreakPositionType.EVERY) {
log.w("There should not be multiple Midrolls for AdBreakPositionType EVERY.\n" +
"Keep One MidRoll ad which will play at the given second.")
midrollAdPositionType = AdBreakPositionType.POSITION
midrollFrequency = 0L
return@adBreakLoop
}
if (adBreak.adBreakPositionType == AdBreakPositionType.PERCENTAGE) {
if (midrollAdPositionType == AdBreakPositionType.EVERY) {
log.w("There should not be a combination of PERCENTAGE and EVERY.")
return@adBreakLoop
}
if (singleAdBreak.position < 0 || singleAdBreak.position > 100) {
log.w("AdBreak having PERCENTAGE type \n " +
"should neither give percentage values less than 0 nor \n " +
"greater than 100.")
return@adBreakLoop
}
midrollAdPositionType = AdBreakPositionType.PERCENTAGE
}
var singleAdBreakPosition = singleAdBreak.position
if (advertisingConfig.adTimeUnit == AdTimeUnit.SECONDS &&
(singleAdBreak.adBreakPositionType == AdBreakPositionType.POSITION || singleAdBreak.adBreakPositionType == AdBreakPositionType.EVERY)) {
// Convert to milliseconds
singleAdBreakPosition = if (singleAdBreak.position > 0) (singleAdBreak.position * Consts.MILLISECONDS_MULTIPLIER) else singleAdBreak.position
}
var singleAdBreakPositionType = singleAdBreak.adBreakPositionType
// Special case when Pre/Post AdBreak is configured with PERCENTAGE
// Changing 100 percentage to -1 and setting type as Position
// so that further percentage to position logic will not get hampered
if (singleAdBreak.adBreakPositionType == AdBreakPositionType.PERCENTAGE) {
if (singleAdBreak.position == 100L) {
singleAdBreakPosition = -1L
}
if (singleAdBreak.position == 0L || singleAdBreak.position == 100L) {
singleAdBreakPositionType = AdBreakPositionType.POSITION
}
}
val adPodConfigList = parseAdPodConfig(singleAdBreak)
// Create ad break list and mark them ready
val adBreakConfig = AdBreakConfig(singleAdBreakPositionType, singleAdBreakPosition, AdState.READY, adPodConfigList)
adBreaksList.add(adBreakConfig)
}
}
sortAdsByPosition(adBreaksList)
}
}
/**
* Parse Each AdBreak. AdBreak may contain list of ad pods
* Mark all the ad pods Ready.
*/
internal fun parseAdPodConfig(singleAdBreak: AdBreak): List<AdPodConfig> {
log.d("parseAdPodConfig")
val adPodConfigList = mutableListOf<AdPodConfig>()
for (adPod: List<String>? in singleAdBreak.ads) {
val adsList = parseEachAdUrl(adPod)
val hasWaterFalling = adsList.size > 1
val adPodConfig = AdPodConfig(AdState.READY, adsList, hasWaterFalling)
adPodConfigList.add(adPodConfig)
}
return adPodConfigList
}
/**
* PlayAdNow JSON parsing
*/
internal fun parseAdBreakGSON(singleAdBreak: String): AdBreak? {
log.d("parseAdBreakGSON")
try {
val adBreak = Gson().fromJson(singleAdBreak, AdBreak::class.java)
if (adBreak != null) {
return adBreak
} else {
log.e("AdBreak Json is invalid")
}
} catch (e: Exception) {
log.e("AdBreak Json Exception: ${e.message}")
}
return null
}
/**
* AdPod may contain the list of Ads (including waterfalling ads)
* Mark all the ads Ready.
*/
private fun parseEachAdUrl(ads: List<String>?): List<Ad> {
log.d("parseEachAdUrl")
val adUrls = mutableListOf<Ad>()
if (ads != null) {
for (url: String in ads) {
adUrls.add(Ad(AdState.READY, url))
}
}
return adUrls
}
/**
* Sorting ads by position: App can pass the AdBreaks in any sequence
* Here we are arranging the ads in Pre(0)/Mid(n)/Post(-1) adroll order
* Here Mid(n) n denotes the time/percentage
*/
private fun sortAdsByPosition(adBreaksList: ArrayList<AdBreakConfig>) {
log.d("sortAdsByPosition")
if (adBreaksList.isNotEmpty()) {
adBreaksList.sortWith(compareBy { it.adPosition })
prepareAdsMapAndList(adBreaksList)
movePostRollAdToLastInList()
}
}
/**
* After the Ads sorting, create a map with position and the relevant AdBreakConfig
* Prepare a CuePoints List. List is being monitored on the controller level
* to understand the current and upcoming cuepoint
*/
private fun prepareAdsMapAndList(adBreakConfigList: ArrayList<AdBreakConfig>) {
log.d("prepareAdsMapAndList")
if (adBreakConfigList.isNotEmpty()) {
adsConfigMap = hashMapOf()
for (adBreakConfig: AdBreakConfig in adBreakConfigList) {
adsConfigMap?.put(adBreakConfig.adPosition, adBreakConfig)
cuePointsList?.add(adBreakConfig.adPosition)
}
}
}
/**
* After the sorting -1 will be on the top,
* so remove it and put it at the last (Postroll)
*/
private fun movePostRollAdToLastInList() {
log.d("movePostRollAdToLastInList")
cuePointsList?.let {
if (it.first == -1L) {
it.remove(-1)
it.addLast(-1)
}
}
}
/**
* Used only if AdBreakPositionType is PERCENTAGE
* Remove and Add the Map's Adbreak Position as per the player duration (Replace not allowed for key in Map)
* Replace the List's Adbreak Position as per the player duration
*/
fun updatePercentageBasedPosition(playerDuration: Long?) {
log.d("updatePercentageBasedPosition PlayerDuration is $playerDuration")
playerDuration?.let {
if (it <= 0) {
return
}
}
adsConfigMap?.let { adsMap ->
val iterator = adsMap.keys.iterator()
var tempMapForUpdatedConfigs: HashMap<Long, AdBreakConfig?>? = HashMap(adsMap.size)
while (iterator.hasNext()) {
val entry = iterator.next()
val config = adsMap[entry]
if (config?.adBreakPositionType == AdBreakPositionType.PERCENTAGE) {
playerDuration?.let {
// Copy of adconfig object
val newAdBreakConfig = config.copy()
// Remove the actual adconfig from map
iterator.remove()
// Update the copied object with updated position for percentage
val oldAdPosition = newAdBreakConfig.adPosition
val updatedPosition = playerDuration.times(oldAdPosition).div(100) // Ex: 23456
val updatedRoundedOfPositionMs = (updatedPosition.div(Consts.MILLISECONDS_MULTIPLIER)) * Consts.MILLISECONDS_MULTIPLIER // It will be changed to 23000
newAdBreakConfig.adPosition = updatedRoundedOfPositionMs
// Put back again the object in the temp map (Because Iterator doesn't have put method
// hence to avoidConcurrentModificationException, need to use temp map and putall the values after the iteration
// Don't use ConcurrentHashmap as it can be overkilling
tempMapForUpdatedConfigs?.put(newAdBreakConfig.adPosition, newAdBreakConfig)
cuePointsList?.forEachIndexed { index, adPosition ->
if (adPosition == oldAdPosition) {
cuePointsList?.set(index, updatedRoundedOfPositionMs)
}
}
}
}
}
tempMapForUpdatedConfigs?.let {
if (it.isNotEmpty()) {
adsMap.putAll(it)
}
it.clear()
}
tempMapForUpdatedConfigs = null
}
sortCuePointsList()
}
/**
* Sort the cue points list again
* Move the postroll to the last
*/
private fun sortCuePointsList() {
log.d("sortCuePointsList")
cuePointsList?.sort()
movePostRollAdToLastInList()
}
fun getEveryBasedCuePointsList(playerDuration: Long?, frequency: Long): List<Long>? {
log.d("getEveryBasedCuePointsList PlayerDuration is $playerDuration")
playerDuration?.let {
if (it <= 0) {
return null
}
}
if (frequency > Long.MIN_VALUE) {
val updatedCuePointsList = mutableListOf<Long>()
playerDuration?.let { duration ->
val updatedRoundedOfDurationMs =
(duration.div(Consts.MILLISECONDS_MULTIPLIER)) * Consts.MILLISECONDS_MULTIPLIER
val factor = updatedRoundedOfDurationMs / frequency
for (factorValue in 1..factor) {
updatedCuePointsList.add(frequency * factorValue)
}
}
log.d("getEveryBasedCuePointsList $updatedCuePointsList")
if (updatedCuePointsList.isNotEmpty()) {
if (cuePointsList?.first == 0L) {
updatedCuePointsList.add(0, 0)
}
if (cuePointsList?.last == -1L) {
updatedCuePointsList.add(-1)
}
}
log.d(" final updatedCuePointsList = $updatedCuePointsList")
return updatedCuePointsList
}
return null
}
/**
* Get Midroll ad break position type (POSITION, PERCENTAGE, EVERY)
*/
fun getMidrollAdBreakPositionType(): AdBreakPositionType {
log.d("getMidrollAdBreakPositionType")
return midrollAdPositionType
}
/**
* If Midroll ad break position type is EVERY
* Then at what frequency ad will be played
*/
fun getMidrollFrequency(): Long {
log.d("getMidrollFrequency")
return midrollFrequency
}
/**
* Getter for CuePoints list
*/
@Nullable
fun getCuePointsList(): LinkedList<Long>? {
log.d("getCuePointsList")
return cuePointsList
}
/**
* Get MidRoll ads if there is any
*/
@Nullable
fun getAdsConfigMap(): MutableMap<Long, AdBreakConfig?>? {
log.d("getAdsConfigMap")
return adsConfigMap
}
/**
* Get PlayAdsAfterTime value from AdvertisingConfig
*/
fun getPlayAdsAfterTime(): Long {
return playAdsAfterTime
}
/**
* Get adType (VAST URL or VAST response)
*/
fun getAdType(): AdType {
return adType
}
/**
* Only for LIVE Media
* After the AdPlayback, player will seek to the live edge or not
*/
fun isReturnToLive(): Boolean {
return returnToLive
}
}
| agpl-3.0 | e2bb3f09906a318e83688a7e8ddd53c5 | 37.823684 | 182 | 0.580695 | 5.525468 | false | true | false | false |
AK-47-D/cms | src/main/kotlin/com/ak47/cms/cms/dto/TechArticleDto.kt | 1 | 806 | package com.ak47.cms.cms.dto
import com.ak47.cms.cms.entity.TechArticle
import java.util.*
class TechArticleDto : TechArticle {
var tagDetail = ""
constructor(
id: Long,
url: String,
title: String,
simpleContent: String,
showContent: String,
tagId: Int,
tagDetail: String,
category: String,
gmtCreate: Date,
gmtModified: Date
) : super() {
this.id = id
this.url = url
this.title = title
this.simpleContent = simpleContent
this.showContent = showContent
this.tagId = tagId
this.tagDetail = tagDetail
this.category = category
this.gmtCreate = gmtCreate
this.gmtModified = gmtModified
}
}
| apache-2.0 | b7f0069d2b0bfe370b7f48b3d928bc13 | 23.424242 | 42 | 0.558313 | 4.31016 | false | false | false | false |
jayrave/falkon | falkon-mapper-basic/src/main/kotlin/com/jayrave/falkon/mapper/TableConfigurationExtn.kt | 1 | 4489 | package com.jayrave.falkon.mapper
/**
* Registers converters for the following types
*
* **Primitives**
* - [Byte]
* - [Char]
* - [Short]
* - [Int]
* - [Long]
* - [Float]
* - [Double]
* - [Boolean]
*
* **Non primitives - both nullable (?) & non-null forms**
* - [Byte]
* - [Char]
* - [Short]
* - [Int]
* - [Long]
* - [Float]
* - [Double]
* - [Boolean]
* - [String]
* - [ByteArray]
*
* CAUTION: Previously registers converters will be overwritten
*/
fun TableConfigurationImpl.registerDefaultConverters() {
val nullableByteConverter = NullableByteConverter()
val nullableCharConverter = NullableCharConverter()
val nullableShortConverter = NullableShortConverter()
val nullableIntConverter = NullableIntConverter()
val nullableLongConverter = NullableLongConverter()
val nullableFloatConverter = NullableFloatConverter()
val nullableDoubleConverter = NullableDoubleConverter()
val nullableBooleanConverter = NullableBooleanConverter()
val nonNullByteConverter = NullableToNonNullConverter(nullableByteConverter)
val nonNullCharConverter = NullableToNonNullConverter(nullableCharConverter)
val nonNullShortConverter = NullableToNonNullConverter(nullableShortConverter)
val nonNullIntConverter = NullableToNonNullConverter(nullableIntConverter)
val nonNullLongConverter = NullableToNonNullConverter(nullableLongConverter)
val nonNullFloatConverter = NullableToNonNullConverter(nullableFloatConverter)
val nonNullDoubleConverter = NullableToNonNullConverter(nullableDoubleConverter)
val nonNullBooleanConverter = NullableToNonNullConverter(nullableBooleanConverter)
// Register for primitives => Byte, Char, Short, Int, Long, Float, Double & Boolean
registerForNonNullValues(Byte::class.javaPrimitiveType!!, nonNullByteConverter)
registerForNonNullValues(Char::class.javaPrimitiveType!!, nonNullCharConverter)
registerForNonNullValues(Short::class.javaPrimitiveType!!, nonNullShortConverter)
registerForNonNullValues(Int::class.javaPrimitiveType!!, nonNullIntConverter)
registerForNonNullValues(Long::class.javaPrimitiveType!!, nonNullLongConverter)
registerForNonNullValues(Float::class.javaPrimitiveType!!, nonNullFloatConverter)
registerForNonNullValues(Double::class.javaPrimitiveType!!, nonNullDoubleConverter)
registerForNonNullValues(Boolean::class.javaPrimitiveType!!, nonNullBooleanConverter)
// Register for non nullable non-primitives => Byte, Char, Short, Int, Long,
// Float, Double & Boolean
registerForNonNullValues(Byte::class.javaObjectType, nonNullByteConverter)
registerForNonNullValues(Char::class.javaObjectType, nonNullCharConverter)
registerForNonNullValues(Short::class.javaObjectType, nonNullShortConverter)
registerForNonNullValues(Int::class.javaObjectType, nonNullIntConverter)
registerForNonNullValues(Long::class.javaObjectType, nonNullLongConverter)
registerForNonNullValues(Float::class.javaObjectType, nonNullFloatConverter)
registerForNonNullValues(Double::class.javaObjectType, nonNullDoubleConverter)
registerForNonNullValues(Boolean::class.javaObjectType, nonNullBooleanConverter)
// Register for nullable non-primitives => Byte?, Char?, Short?, Int?, Long?,
// Float?, Double? & Boolean?
registerForNullableValues(Byte::class.javaObjectType, nullableByteConverter, false)
registerForNullableValues(Char::class.javaObjectType, nullableCharConverter, false)
registerForNullableValues(Short::class.javaObjectType, nullableShortConverter, false)
registerForNullableValues(Int::class.javaObjectType, nullableIntConverter, false)
registerForNullableValues(Long::class.javaObjectType, nullableLongConverter, false)
registerForNullableValues(Float::class.javaObjectType, nullableFloatConverter, false)
registerForNullableValues(Double::class.javaObjectType, nullableDoubleConverter, false)
registerForNullableValues(Boolean::class.javaObjectType, nullableBooleanConverter, false)
// Register for nullable & non nullable non-primitives => String, String?,
// ByteArray, ByteArray?
registerForNullableValues(String::class.javaObjectType, NullableStringConverter(), true)
registerForNullableValues(ByteArray::class.javaObjectType, NullableBlobConverter(), true)
}
| apache-2.0 | b512ab72b377482d25dadd809c47da78 | 50.597701 | 93 | 0.758966 | 5.792258 | false | false | false | false |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/shows/tools/ShowTools2.kt | 1 | 16494 | package com.battlelancer.seriesguide.shows.tools
import android.content.Context
import android.widget.Toast
import androidx.collection.SparseArrayCompat
import com.battlelancer.seriesguide.R
import com.battlelancer.seriesguide.SgApp
import com.battlelancer.seriesguide.backend.settings.HexagonSettings
import com.battlelancer.seriesguide.enums.NetworkResult
import com.battlelancer.seriesguide.modules.ApplicationContext
import com.battlelancer.seriesguide.provider.SeriesGuideContract
import com.battlelancer.seriesguide.provider.SeriesGuideDatabase
import com.battlelancer.seriesguide.provider.SgRoomDatabase
import com.battlelancer.seriesguide.notifications.NotificationService
import com.battlelancer.seriesguide.sync.HexagonShowSync
import com.battlelancer.seriesguide.sync.SgSyncAdapter
import com.uwetrottmann.androidutils.AndroidUtils
import com.uwetrottmann.seriesguide.backend.shows.model.SgCloudShow
import dagger.Lazy
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus
import javax.inject.Inject
import kotlin.collections.set
import com.battlelancer.seriesguide.enums.Result as SgResult
/**
* Provides some show operations as (async) suspend functions, running within global scope.
*/
class ShowTools2 @Inject constructor(
@param:ApplicationContext private val context: Context,
private val hexagonShowSync: Lazy<HexagonShowSync>
) {
/**
* Gets row ID of a show by TMDB id first, then if given by TVDB id and null TMDB id (show is
* not migrated, yet). Null if not in database or matched by TVDB id, but has different TMDB id.
*/
fun getShowId(showTmdbId: Int, showTvdbId: Int?): Long? {
val helper = SgRoomDatabase.getInstance(context).sgShow2Helper()
val showIdByTmdbId = helper.getShowIdByTmdbId(showTmdbId)
if (showIdByTmdbId > 0) return showIdByTmdbId
if (showTvdbId != null) {
// Note: TVDB might have a single show that is split into two or more shows on TMDB,
// so on TMDB the same TVDB is linked for both. To not prevent adding the second one,
// only return show ID if it was not migrated to avoid adding a duplicate show.
val showIdByTvdbId = helper.getShowIdByTvdbIdWithNullTmdbId(showTvdbId)
if (showIdByTvdbId > 0) return showIdByTvdbId
}
return null
}
/**
* Returns the Trakt id of a show, or `null` if it is invalid or there is none.
*/
fun getShowTraktId(showId: Long): Int? {
val traktIdOrZero = SgRoomDatabase.getInstance(context).sgShow2Helper()
.getShowTraktId(showId)
return if (traktIdOrZero <= 0) {
null
} else {
traktIdOrZero
}
}
/**
* Posted if a show is about to get removed.
*/
data class OnRemovingShowEvent(val showId: Long)
/**
* Posted if show was just removed (or failure).
*/
data class OnShowRemovedEvent(
val showTmdbId: Int,
/** One of [com.battlelancer.seriesguide.enums.NetworkResult]. */
val resultCode: Int
)
/**
* Removes a show and its seasons and episodes, including search docs. Sends isRemoved flag to
* Hexagon so the show will not be auto-added on any device connected to Hexagon.
*
* Posts [OnRemovingShowEvent] when starting and [OnShowRemovedEvent] once completed.
*/
fun removeShow(showId: Long) {
SgApp.coroutineScope.launch(SgApp.SINGLE) {
withContext(Dispatchers.Main) {
EventBus.getDefault().post(OnRemovingShowEvent(showId))
}
// Get TMDB id for OnShowRemovedEvent before removing show.
val showTmdbId = withContext(Dispatchers.IO) {
SgRoomDatabase.getInstance(context).sgShow2Helper().getShowTmdbId(showId)
}
val result = removeShowAsync(showId)
withContext(Dispatchers.Main) {
if (result == NetworkResult.OFFLINE) {
Toast.makeText(context, R.string.offline, Toast.LENGTH_LONG).show()
} else if (result == NetworkResult.ERROR) {
Toast.makeText(context, R.string.delete_error, Toast.LENGTH_LONG).show()
}
EventBus.getDefault().post(OnShowRemovedEvent(showTmdbId, result))
}
}
}
/**
* Returns [com.battlelancer.seriesguide.enums.NetworkResult].
*/
private suspend fun removeShowAsync(showId: Long): Int {
// Send to cloud.
val isCloudFailed = withContext(Dispatchers.Default) {
if (!HexagonSettings.isEnabled(context)) {
return@withContext false
}
if (isNotConnected(context)) {
return@withContext true
}
val showTmdbId =
SgRoomDatabase.getInstance(context).sgShow2Helper().getShowTmdbId(showId)
if (showTmdbId == 0) {
// If this is a legacy show (has TVDB ID but no TMDB ID), still allow removal
// from local database. Do not send to Cloud but pretend no failure.
val showTvdbId =
SgRoomDatabase.getInstance(context).sgShow2Helper().getShowTvdbId(showId)
return@withContext showTvdbId == 0
}
// Sets the isRemoved flag of the given show on Hexagon, so the show will
// not be auto-added on any device connected to Hexagon.
val show = SgCloudShow()
show.tmdbId = showTmdbId
show.isRemoved = true
val success = uploadShowToCloud(show)
return@withContext !success
}
// Do not save to local database if sending to cloud has failed.
if (isCloudFailed) return SgResult.ERROR
return withContext(Dispatchers.IO) {
// Remove database entries in stages, so if an earlier stage fails,
// user can try again. Also saves memory by using smaller database transactions.
val database = SgRoomDatabase.getInstance(context)
var rowsUpdated = database.sgEpisode2Helper().deleteEpisodesOfShow(showId)
if (rowsUpdated == -1) return@withContext SgResult.ERROR
rowsUpdated = database.sgSeason2Helper().deleteSeasonsOfShow(showId)
if (rowsUpdated == -1) return@withContext SgResult.ERROR
rowsUpdated = database.sgShow2Helper().deleteShow(showId)
if (rowsUpdated == -1) return@withContext SgResult.ERROR
SeriesGuideDatabase.rebuildFtsTable(context)
SgResult.SUCCESS
}
}
/**
* Saves new favorite flag to the local database and, if signed in, up into the cloud as well.
*/
fun storeIsFavorite(showId: Long, isFavorite: Boolean) {
SgApp.coroutineScope.launch {
storeIsFavoriteAsync(showId, isFavorite)
}
}
private suspend fun storeIsFavoriteAsync(showId: Long, isFavorite: Boolean) {
// Send to cloud.
val isCloudFailed = withContext(Dispatchers.Default) {
if (!HexagonSettings.isEnabled(context)) {
return@withContext false
}
if (isNotConnected(context)) {
return@withContext true
}
val showTmdbId =
SgRoomDatabase.getInstance(context).sgShow2Helper().getShowTmdbId(showId)
if (showTmdbId == 0) {
return@withContext true
}
val show = SgCloudShow()
show.tmdbId = showTmdbId
show.isFavorite = isFavorite
val success = uploadShowToCloud(show)
return@withContext !success
}
// Do not save to local database if sending to cloud has failed.
if (isCloudFailed) return
// Save to local database.
withContext(Dispatchers.IO) {
SgRoomDatabase.getInstance(context).sgShow2Helper().setShowFavorite(showId, isFavorite)
// Also notify URI used by lists.
context.contentResolver
.notifyChange(SeriesGuideContract.ListItems.CONTENT_WITH_DETAILS_URI, null)
}
// display info toast
withContext(Dispatchers.Main) {
Toast.makeText(
context, context.getString(
if (isFavorite)
R.string.favorited
else
R.string.unfavorited
), Toast.LENGTH_SHORT
).show()
}
}
/**
* Saves new hidden flag to the local database and, if signed in, up into the cloud as well.
*/
fun storeIsHidden(showId: Long, isHidden: Boolean) {
SgApp.coroutineScope.launch {
storeIsHiddenAsync(showId, isHidden)
}
}
private suspend fun storeIsHiddenAsync(showId: Long, isHidden: Boolean) {
// Send to cloud.
val isCloudFailed = withContext(Dispatchers.Default) {
if (!HexagonSettings.isEnabled(context)) {
return@withContext false
}
if (isNotConnected(context)) {
return@withContext true
}
val showTmdbId =
SgRoomDatabase.getInstance(context).sgShow2Helper().getShowTmdbId(showId)
if (showTmdbId == 0) {
return@withContext true
}
val show = SgCloudShow()
show.tmdbId = showTmdbId
show.isHidden = isHidden
val success = uploadShowToCloud(show)
return@withContext !success
}
// Do not save to local database if sending to cloud has failed.
if (isCloudFailed) return
// Save to local database.
withContext(Dispatchers.IO) {
SgRoomDatabase.getInstance(context).sgShow2Helper().setShowHidden(showId, isHidden)
}
// display info toast
withContext(Dispatchers.Main) {
Toast.makeText(
context, context.getString(
if (isHidden)
R.string.hidden
else
R.string.unhidden
), Toast.LENGTH_SHORT
).show()
}
}
/**
* Saves new notify flag to the local database and, if signed in, up into the cloud as well.
*/
fun storeNotify(showId: Long, notify: Boolean) {
SgApp.coroutineScope.launch {
storeNotifyAsync(showId, notify)
}
}
private suspend fun storeNotifyAsync(showId: Long, notify: Boolean) {
// Send to cloud.
val isCloudFailed = withContext(Dispatchers.Default) {
if (!HexagonSettings.isEnabled(context)) {
return@withContext false
}
if (isNotConnected(context)) {
return@withContext true
}
val showTmdbId =
SgRoomDatabase.getInstance(context).sgShow2Helper().getShowTmdbId(showId)
if (showTmdbId == 0) {
return@withContext true
}
val show = SgCloudShow()
show.tmdbId = showTmdbId
show.notify = notify
val success = uploadShowToCloud(show)
return@withContext !success
}
// Do not save to local database if sending to cloud has failed.
if (isCloudFailed) return
// Save to local database.
withContext(Dispatchers.IO) {
SgRoomDatabase.getInstance(context).sgShow2Helper().setShowNotify(showId, notify)
}
// new notify setting may determine eligibility for notifications
withContext(Dispatchers.Default) {
NotificationService.trigger(context)
}
}
/**
* Removes hidden flag from all hidden shows in the local database and, if signed in, sends to
* the cloud as well.
*/
fun storeAllHiddenVisible() {
SgApp.coroutineScope.launch {
// Send to cloud.
val isCloudFailed = withContext(Dispatchers.Default) {
if (!HexagonSettings.isEnabled(context)) {
return@withContext false
}
if (isNotConnected(context)) {
return@withContext true
}
val hiddenShowTmdbIds = withContext(Dispatchers.IO) {
SgRoomDatabase.getInstance(context).sgShow2Helper().getHiddenShowsTmdbIds()
}
val shows = hiddenShowTmdbIds.map { tmdbId ->
val show = SgCloudShow()
show.tmdbId = tmdbId
show.isHidden = false
show
}
val success = withContext(Dispatchers.IO) {
hexagonShowSync.get().upload(shows)
}
return@withContext !success
}
// Do not save to local database if sending to cloud has failed.
if (isCloudFailed) return@launch
// Save to local database.
withContext(Dispatchers.IO) {
SgRoomDatabase.getInstance(context).sgShow2Helper().makeHiddenVisible()
}
}
}
fun storeLanguage(showId: Long, languageCode: String) = SgApp.coroutineScope.launch {
// Send to cloud.
val isCloudFailed = withContext(Dispatchers.Default) {
if (!HexagonSettings.isEnabled(context)) {
return@withContext false
}
if (isNotConnected(context)) {
return@withContext true
}
val showTmdbId =
SgRoomDatabase.getInstance(context).sgShow2Helper().getShowTmdbId(showId)
if (showTmdbId == 0) {
return@withContext true
}
val show = SgCloudShow()
show.tmdbId = showTmdbId
show.language = languageCode
val success = uploadShowToCloud(show)
return@withContext !success
}
// Do not save to local database if sending to cloud has failed.
if (isCloudFailed) return@launch
// Save to local database and schedule sync.
withContext(Dispatchers.IO) {
// change language
val database = SgRoomDatabase.getInstance(context)
database.sgShow2Helper().updateLanguage(showId, languageCode)
// reset episode last update time so all get updated
database.sgEpisode2Helper().resetLastUpdatedForShow(showId)
// trigger update
SgSyncAdapter.requestSyncSingleImmediate(context, false, showId)
}
withContext(Dispatchers.Main) {
// show immediate feedback, also if offline and sync won't go through
if (AndroidUtils.isNetworkConnected(context)) {
// notify about upcoming sync
Toast.makeText(context, R.string.update_scheduled, Toast.LENGTH_SHORT).show()
} else {
// offline
Toast.makeText(context, R.string.update_no_connection, Toast.LENGTH_LONG).show()
}
}
}
private suspend fun isNotConnected(context: Context): Boolean {
val isConnected = AndroidUtils.isNetworkConnected(context)
// display offline toast
if (!isConnected) {
withContext(Dispatchers.Main) {
Toast.makeText(context, R.string.offline, Toast.LENGTH_LONG).show()
}
}
return !isConnected
}
private suspend fun uploadShowToCloud(show: SgCloudShow): Boolean {
return hexagonShowSync.get().upload(show)
}
fun getTmdbIdsToPoster(): SparseArrayCompat<String> {
val shows = SgRoomDatabase.getInstance(context).sgShow2Helper().getShowsMinimal()
val map = SparseArrayCompat<String>()
shows.forEach {
if (it.tmdbId != null && it.tmdbId != 0) {
map.put(it.tmdbId, it.posterSmall)
}
}
return map
}
fun getTmdbIdsToShowIds(): Map<Int, Long> {
val showIds = SgRoomDatabase.getInstance(context).sgShow2Helper().getShowIds()
val map = mutableMapOf<Int, Long>()
showIds.forEach {
if (it.tmdbId != null) map[it.tmdbId] = it.id
}
return map
}
}
| apache-2.0 | 94e3e1f0f6eab0ec109b92e68c963dff | 35.816964 | 100 | 0.60525 | 5.22955 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.